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
aarch64.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 ...
C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { arg.layout.homogeneous_aggregate(cx).and_then(|unit| { let size = arg.layout.size; // Ensure we have at most four uniquely addressable members. if size > unit.size.checked_mul(4, cx).unwrap() { return ...
fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>) -> Option<Uniform> where Ty: TyLayoutMethods<'a, C> + Copy,
random_line_split
aarch64.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 ...
<'a, Ty, C>(cx: &C, fty: &mut FnType<'a, Ty>) where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { if!fty.ret.is_ignore() { classify_ret_ty(cx, &mut fty.ret); } for arg in &mut fty.args { if arg.is_ignore() { continue; } ...
compute_abi_info
identifier_name
lib.rs
#![crate_type = "dylib"] #![feature(plugin_registrar, rustc_private)] //! # Rustplacements //! //! This is a compiler plugin for the [Rust language](https://www.rust-lang.org/en-US/) that replaces all of your string literals //! in the source code with random text. Well, it's not really random. You can choose to repla...
rans(ctxt)), Box(b) => Box(b.trans(ctxt)), InPlace(a, b) => InPlace(a.trans(ctxt), b.trans(ctxt)), Array(v) => Array(v.trans(ctxt)), Call(a, v) => Call(a.trans(ctxt), v.trans(ctxt)), MethodCall(p, v) => MethodCall(p, v.trans(ctxt)), Tup(v) => Tup(v...
t(l.t
identifier_name
lib.rs
#![crate_type = "dylib"] #![feature(plugin_registrar, rustc_private)] //! # Rustplacements //! //! This is a compiler plugin for the [Rust language](https://www.rust-lang.org/en-US/) that replaces all of your string literals //! in the source code with random text. Well, it's not really random. You can choose to repla...
_iter().map(|i| i.trans(ctxt)).collect() } } // We can invoke this rule on most of the struct types. macro_rules! Rustplace { // For many of the structs, the field is called "node" so we simplify that case. ($ty:ident) => (Rustplace!($ty,node);); ($ty:ident,$field:tt) => ( impl Rustplace for $t...
s(self, ctxt: &Context) -> Self { self.into
identifier_body
lib.rs
#![crate_type = "dylib"] #![feature(plugin_registrar, rustc_private)] //! # Rustplacements //! //! This is a compiler plugin for the [Rust language](https://www.rust-lang.org/en-US/) that replaces all of your string literals //! in the source code with random text. Well, it's not really random. You can choose to repla...
use TraitItemKind::*; match self { Const(ty, Some(expr)) => Const(ty, Some(expr.trans(ctxt))), Method(sig, Some(block)) => Method(sig, Some(block.trans(ctxt))), _ => self, } } } impl Rustplace for ImplItemKind { fn trans(self, ctxt: &Context) -> Self ...
} impl Rustplace for TraitItemKind { fn trans(self, ctxt: &Context) -> Self {
random_line_split
rust-indexer.rs
fn use_unmangled_name(def: &data::Def) -> bool { match def.kind { DefKind::ForeignStatic | DefKind::ForeignFunction => true, DefKind::Static | DefKind::Function => { def.attributes.iter().any(|attr| attr.value == "no_mangle") } _ => false, ...
fn pretty_for_def(def: &data::Def, qualname: &str) -> String { let mut pretty = def_kind_to_human(def.kind).to_owned(); pretty.push_str(" "); // We use the unsanitized qualname here because it's more human-readable // and the source-analysis pretty name is allowed to have commas and such pretty.pu...
{ let mut pretty = impl_kind_to_human(&imp.kind).to_owned(); pretty.push_str(" "); pretty.push_str(qualname); pretty }
identifier_body
rust-indexer.rs
fn use_unmangled_name(def: &data::Def) -> bool { match def.kind { DefKind::ForeignStatic | DefKind::ForeignFunction => true, DefKind::Static | DefKind::Function => { def.attributes.iter().any(|attr| attr.value == "no_mangle") } _ => false, ...
(&self) -> Vec<SearchDirectory> { self.deps_dirs .iter() .map(|pb| SearchDirectory { path: pb.clone(), prefix_rewrite: None, }) .collect() } } fn def_kind_to_human(kind: DefKind) -> &'static str { match kind { DefKind:...
search_directories
identifier_name
rust-indexer.rs
fn use_unmangled_name(def: &data::Def) -> bool { match def.kind { DefKind::ForeignStatic | DefKind::ForeignFunction => true, DefKind::Static | DefKind::Function => { def.attributes.iter().any(|attr| attr.value == "no_mangle") } _ => false, ...
if!local_source_path.exists() { warn!( "Skipping nonexistent source file with searchfox path '{}' which mapped to local path '{}'", searchfox_path.display(), local_source_path.display() ); return; }; // Attempt to open the source file to extract ...
random_line_split
traits.rs
use approx::AbsDiffEq; use num::{Bounded, FromPrimitive, Signed}; use na::allocator::Allocator; use na::{DimMin, DimName, Scalar, U1}; use simba::scalar::{ClosedAdd, ClosedMul, ClosedSub}; use std::cmp::PartialOrd; /// A type-level number representing a vector, matrix row, or matrix column, dimension. pub trait Dimen...
+ AbsDiffEq<Epsilon = Self> + Signed + FromPrimitive + Bounded, > Number for T { } #[doc(hidden)] pub trait Alloc<N: Scalar, R: Dimension, C: Dimension = U1>: Allocator<N, R> + Allocator<N, C> + Allocator<N, U1, R> + Allocator<N, U1, C> + Allocato...
+ ClosedSub + ClosedMul
random_line_split
db.rs
use postgres::{Connection, TlsMode}; use postgres::types::ToSql; use postgres::error as sqlerr; use getopts; pub fn build (matches: &getopts::Matches) { if matches.opt_present("i") { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need passw...
} } if matches.opt_present("b") { let conn = Connection::connect("postgres://stratis:stratis@localhost", TlsMode::None).expect("cannot connect to sql"); let build = vec![&include_bytes!("../../sql/create_players.sql")[..], ...
{ println!("build:{:?}\nfor:{:?}\n\n",e,s); }
conditional_block
db.rs
use postgres::{Connection, TlsMode}; use postgres::types::ToSql; use postgres::error as sqlerr; use getopts; pub fn
(matches: &getopts::Matches) { if matches.opt_present("i") { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need password, use -p opt"); let mut s = String::from("postgres://"); s.push_str(&(user+":"+&pass+"@localho...
build
identifier_name
db.rs
use postgres::{Connection, TlsMode}; use postgres::types::ToSql; use postgres::error as sqlerr; use getopts; pub fn build (matches: &getopts::Matches) { if matches.opt_present("i") { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need passw...
{ let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need password, use -p opt"); let mut s = String::from("postgres://"); s.push_str(&(user+":"+&pass+"@localhost")); let conn = Connection::connect(s, ...
identifier_body
db.rs
use postgres::{Connection, TlsMode}; use postgres::types::ToSql; use postgres::error as sqlerr; use getopts; pub fn build (matches: &getopts::Matches) { if matches.opt_present("i") { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need passw...
let conn = Connection::connect("postgres://stratis:stratis@localhost", TlsMode::None).expect("cannot connect to sql"); let build = vec![&include_bytes!("../../sql/create_players.sql")[..], &include_bytes!("../../sql/create_msg.sql")[..], ...
} } if matches.opt_present("b") {
random_line_split
cstore.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 ...
cstore.used_libraries.push(lib); true } pub fn get_used_libraries<'a>(cstore: &'a CStore) -> &'a [@str] { let slice: &'a [@str] = cstore.used_libraries; slice } pub fn add_used_link_args(cstore: &mut CStore, args: &str) { for args.split_iter(' ').advance |s| { cstore.used_link_args.push(s...
{ return false; }
conditional_block
cstore.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 ...
// returns hashes of crates directly used by this crate. Hashes are sorted by // (crate name, crate version, crate hash) in lexicographic order (not semver) pub fn get_dep_hashes(cstore: &CStore) -> ~[@str] { struct crate_hash { name: @str, vers: @str, hash: @str } let mut result = ~[]; for cstore.extern...
{ cstore.extern_mod_crate_map.find(&emod_id).map_consume(|x| *x) }
identifier_body
cstore.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 ...
// The crate store - a central repo for information collected about external // crates and libraries use metadata::cstore; use metadata::decoder; use std::hashmap::HashMap; use extra; use syntax::ast; use syntax::parse::token::ident_interner; // A map from external crate numbers (as decoded from some crate file) to...
// except according to those terms.
random_line_split
cstore.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 ...
(cstore: &CStore, cnum: ast::crate_num) -> @str { let cdata = get_crate_data(cstore, cnum); decoder::get_crate_vers(cdata.data) } pub fn set_crate_data(cstore: &mut CStore, cnum: ast::crate_num, data: @crate_metadata) { cstore.metas.insert(cnum, data); } pub fn ...
get_crate_vers
identifier_name
limits.rs
use crate::error::Result; use postgres::Connection; use std::collections::BTreeMap; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Limits { memory: usize, targets: usize, timeout: Duration, networking: bool, max_log_size: usize, } impl Default for Limits { fn...
use crate::test::*; #[test] fn retrieve_limits() { wrapper(|env| { let db = env.db(); let krate = "hexponent"; // limits work if no crate has limits set let hexponent = Limits::for_crate(&db.conn(), krate)?; assert_eq!(hexponent, Limits::...
mod test { use super::*;
random_line_split
limits.rs
use crate::error::Result; use postgres::Connection; use std::collections::BTreeMap; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Limits { memory: usize, targets: usize, timeout: Duration, networking: bool, max_log_size: usize, } impl Default for Limits { fn...
pub(crate) fn max_log_size(&self) -> usize { self.max_log_size } pub(crate) fn targets(&self) -> usize { self.targets } pub(crate) fn for_website(&self) -> BTreeMap<String, String> { let mut res = BTreeMap::new(); res.insert("Available RAM".into(), SIZE_SCALE(self...
{ self.networking }
identifier_body
limits.rs
use crate::error::Result; use postgres::Connection; use std::collections::BTreeMap; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Limits { memory: usize, targets: usize, timeout: Duration, networking: bool, max_log_size: usize, } impl Default for Limits { fn...
res.insert( "Maximum number of build targets".into(), self.targets.to_string(), ); res } } const TIME_SCALE: fn(usize) -> String = |v| scale(v, 60, &["seconds", "minutes", "hours"]); const SIZE_SCALE: fn(usize) -> String = |v| scale(v, 1024, &["bytes", "KB", "MB", "...
{ res.insert("Network access".into(), "blocked".into()); }
conditional_block
limits.rs
use crate::error::Result; use postgres::Connection; use std::collections::BTreeMap; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Limits { memory: usize, targets: usize, timeout: Duration, networking: bool, max_log_size: usize, } impl Default for Limits { fn...
(conn: &Connection, name: &str) -> Result<Self> { let mut limits = Self::default(); let res = conn.query( "SELECT * FROM sandbox_overrides WHERE crate_name = $1;", &[&name], )?; if!res.is_empty() { let row = res.get(0); if let Some(memory)...
for_crate
identifier_name
resource.rs
use alloc::boxed::Box; use system::error::{Error, Result, EBADF}; use system::syscall::Stat; /// Resource seek #[derive(Copy, Clone, Debug)] pub enum ResourceSeek { /// Start point Start(usize), /// Current point Current(isize), /// End point End(isize), } /// A system resource #[allow(unused...
(&mut self, buf: &[u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Seek to the given offset fn seek(&mut self, pos: ResourceSeek) -> Result<usize> { Err(Error::new(EBADF)) } fn stat(&self, stat: &mut Stat) -> Result<usize> { Err(Error::new(EBADF)) } /// Sync a...
write
identifier_name
resource.rs
use alloc::boxed::Box; use system::error::{Error, Result, EBADF}; use system::syscall::Stat; /// Resource seek #[derive(Copy, Clone, Debug)] pub enum ResourceSeek { /// Start point Start(usize), /// Current point Current(isize), /// End point End(isize), } /// A system resource #[allow(unused...
/// Return the path of this resource fn path(&self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Read data to buffer fn read(&mut self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Write to resource fn write(&mut self, buf: &[u8]) -...
}
random_line_split
resource.rs
use alloc::boxed::Box; use system::error::{Error, Result, EBADF}; use system::syscall::Stat; /// Resource seek #[derive(Copy, Clone, Debug)] pub enum ResourceSeek { /// Start point Start(usize), /// Current point Current(isize), /// End point End(isize), } /// A system resource #[allow(unused...
/// Return the path of this resource fn path(&self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Read data to buffer fn read(&mut self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Write to resource fn write(&mut self, buf: &[u8])...
{ Err(Error::new(EBADF)) }
identifier_body
mod_neg.rs
use num::arithmetic::traits::{ModNeg, ModNegAssign}; use num::basic::traits::Zero; use std::ops::Sub; fn mod_neg<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: T, m: T) -> T { if x == T::ZERO { T::ZERO } else
} fn mod_neg_assign<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: &mut T, m: T) { if *x!= T::ZERO { *x = m - *x; } } macro_rules! impl_mod_neg { ($t:ident) => { impl ModNeg for $t { type Output = $t; /// Computes `-self` mod `m`. Assumes the input is already reduce...
{ m - x }
conditional_block
mod_neg.rs
use num::arithmetic::traits::{ModNeg, ModNegAssign}; use num::basic::traits::Zero; use std::ops::Sub; fn mod_neg<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: T, m: T) -> T
fn mod_neg_assign<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: &mut T, m: T) { if *x!= T::ZERO { *x = m - *x; } } macro_rules! impl_mod_neg { ($t:ident) => { impl ModNeg for $t { type Output = $t; /// Computes `-self` mod `m`. Assumes the input is already reduced ...
{ if x == T::ZERO { T::ZERO } else { m - x } }
identifier_body
mod_neg.rs
use num::arithmetic::traits::{ModNeg, ModNegAssign}; use num::basic::traits::Zero; use std::ops::Sub; fn
<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: T, m: T) -> T { if x == T::ZERO { T::ZERO } else { m - x } } fn mod_neg_assign<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: &mut T, m: T) { if *x!= T::ZERO { *x = m - *x; } } macro_rules! impl_mod_neg { ($t:ident) => { ...
mod_neg
identifier_name
mod_neg.rs
use num::arithmetic::traits::{ModNeg, ModNegAssign}; use num::basic::traits::Zero; use std::ops::Sub; fn mod_neg<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: T, m: T) -> T { if x == T::ZERO { T::ZERO } else { m - x } } fn mod_neg_assign<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: &mut T, ...
($t:ident) => { impl ModNeg for $t { type Output = $t; /// Computes `-self` mod `m`. Assumes the input is already reduced mod `m`. /// /// $f(x, m) = y$, where $x, y < m$ and $-x \equiv y \mod m$. /// /// # Worst-case complexity ...
} macro_rules! impl_mod_neg {
random_line_split
err.rs
use std::error::Error; use std::fmt; use ::dynamic::CompositerError; use ::graphic::ManagerError; use ::pty_proc::shell::ShellError; pub type Result<T> = ::std::result::Result<T, NekoError>; /// The enum `NekoError` defines the possible errors /// from constructor Neko. #[derive(Debug)] pub enum NekoError { /// ...
(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } impl Error for NekoError { /// The function `description` returns a short description of /// the error. fn description(&self) -> &str { match *self { NekoError::DynamicFail(_) => "The dynamic library interface has\ ...
fmt
identifier_name
err.rs
use std::error::Error; use std::fmt; use ::dynamic::CompositerError; use ::graphic::ManagerError; use ::pty_proc::shell::ShellError; pub type Result<T> = ::std::result::Result<T, NekoError>; /// The enum `NekoError` defines the possible errors /// from constructor Neko. #[derive(Debug)] pub enum NekoError { /// ...
impl Error for NekoError { /// The function `description` returns a short description of /// the error. fn description(&self) -> &str { match *self { NekoError::DynamicFail(_) => "The dynamic library interface has\ occured an error.", NekoError::Gr...
fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } }
random_line_split
move_vm.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::FuzzTargetImpl; use anyhow::{bail, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_proptest_helpers::ValueGenerator; use move_core_types::value::MoveTypeLayout; use move_vm_types::values::{prop::lay...
impl FuzzTargetImpl for ValueTarget { fn description(&self) -> &'static str { "VM values + types (custom deserializer)" } fn generate(&self, _idx: usize, gen: &mut ValueGenerator) -> Option<Vec<u8>> { let (layout, value) = gen.generate(layout_and_value_strategy()); // Values as cur...
random_line_split
move_vm.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::FuzzTargetImpl; use anyhow::{bail, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_proptest_helpers::ValueGenerator; use move_core_types::value::MoveTypeLayout; use move_vm_types::values::{prop::lay...
} fn is_valid_layout(layout: &MoveTypeLayout) -> bool { use MoveTypeLayout as L; match layout { L::Bool | L::U8 | L::U64 | L::U128 | L::Address | L::Signer => true, L::Vector(layout) => is_valid_layout(layout), L::Struct(struct_layout) => { if struct_layout.fields().is_e...
{ let _ = deserialize(data); }
identifier_body
move_vm.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::FuzzTargetImpl; use anyhow::{bail, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_proptest_helpers::ValueGenerator; use move_core_types::value::MoveTypeLayout; use move_vm_types::values::{prop::lay...
(&self, data: &[u8]) { let _ = deserialize(data); } } fn is_valid_layout(layout: &MoveTypeLayout) -> bool { use MoveTypeLayout as L; match layout { L::Bool | L::U8 | L::U64 | L::U128 | L::Address | L::Signer => true, L::Vector(layout) => is_valid_layout(layout), L::Struct...
fuzz
identifier_name
move_vm.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::FuzzTargetImpl; use anyhow::{bail, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_proptest_helpers::ValueGenerator; use move_core_types::value::MoveTypeLayout; use move_vm_types::values::{prop::lay...
let layout_data = &data[..layout_len]; let value_data = &data[layout_len..]; let layout: MoveTypeLayout = bcs::from_bytes(layout_data)?; // The fuzzer may alter the raw bytes, resulting in invalid layouts that will not // pass the bytecode verifier. We need to filter these out as they can show up...
{ bail!("too little data"); }
conditional_block
first_run.rs
use std::fs::create_dir; use std::path::Path; /// Used just to check for the existence of the default path. Prints out /// useful messages as to what's happening. /// /// # Examples /// /// ```rust /// extern crate rand; /// /// use common::first_run::check_first_run; /// use rand::random; /// use std::fs::{create_dir...
let _ = remove_dir(path); } #[test] fn returns_ok_if_already_exists() { let path = rand_names::project_path(); let _ = create_dir(&path); assert!(check_first_run(&path).is_ok()); let _ = remove_dir(path); } }
assert!(!path.exists()); assert!(check_first_run(&path).is_ok()); // Side effects assert!(path.exists());
random_line_split
first_run.rs
use std::fs::create_dir; use std::path::Path; /// Used just to check for the existence of the default path. Prints out /// useful messages as to what's happening. /// /// # Examples /// /// ```rust /// extern crate rand; /// /// use common::first_run::check_first_run; /// use rand::random; /// use std::fs::{create_dir...
; Ok(()) } #[cfg(test)] mod test { use super::*; use rand_names; use std::fs::remove_dir; #[test] fn creates_dir_if_not_exist() { let path = rand_names::project_path(); assert!(!path.exists()); assert!(check_first_run(&path).is_ok()); // Side effects assert!(p...
{ create_dir(muxed_dir).map_err(|e| format!("We noticed the configuration directory: `{}` didn't exist so we tried to create it, but something went wrong: {}", muxed_dir.display(), e))?; println!("Looks like this is your first time here. Muxed could't find the configuration directory: `{}`", muxed_dir.d...
conditional_block
first_run.rs
use std::fs::create_dir; use std::path::Path; /// Used just to check for the existence of the default path. Prints out /// useful messages as to what's happening. /// /// # Examples /// /// ```rust /// extern crate rand; /// /// use common::first_run::check_first_run; /// use rand::random; /// use std::fs::{create_dir...
#[cfg(test)] mod test { use super::*; use rand_names; use std::fs::remove_dir; #[test] fn creates_dir_if_not_exist() { let path = rand_names::project_path(); assert!(!path.exists()); assert!(check_first_run(&path).is_ok()); // Side effects assert!(path.exists()); ...
{ if !muxed_dir.exists() { create_dir(muxed_dir).map_err(|e| format!("We noticed the configuration directory: `{}` didn't exist so we tried to create it, but something went wrong: {}", muxed_dir.display(), e))?; println!("Looks like this is your first time here. Muxed could't find the configuration ...
identifier_body
first_run.rs
use std::fs::create_dir; use std::path::Path; /// Used just to check for the existence of the default path. Prints out /// useful messages as to what's happening. /// /// # Examples /// /// ```rust /// extern crate rand; /// /// use common::first_run::check_first_run; /// use rand::random; /// use std::fs::{create_dir...
() { let path = rand_names::project_path(); assert!(!path.exists()); assert!(check_first_run(&path).is_ok()); // Side effects assert!(path.exists()); let _ = remove_dir(path); } #[test] fn returns_ok_if_already_exists() { let path = rand_names::project_path...
creates_dir_if_not_exist
identifier_name
add.rs
use std::string::{String}; use std::sync::{Arc};
fn operation<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1!= 1 && x2 == 1 { let transform = vec[1].buffer(); Tensor::from_vec(Vec2(x1, y1), vec[0].buffer().iter().enumerate().map(|(i...
use std::ops::{Mul, Add}; use math::{Vec2}; use node::{Node, Graph}; use tensor::{Tensor};
random_line_split
add.rs
use std::string::{String}; use std::sync::{Arc}; use std::ops::{Mul, Add}; use math::{Vec2}; use node::{Node, Graph}; use tensor::{Tensor}; fn
<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1!= 1 && x2 == 1 { let transform = vec[1].buffer(); Tensor::from_vec(Vec2(x1, y1), vec[0].buffer().iter().enumerate().map(|(i, &x)| x + t...
operation
identifier_name
add.rs
use std::string::{String}; use std::sync::{Arc}; use std::ops::{Mul, Add}; use math::{Vec2}; use node::{Node, Graph}; use tensor::{Tensor}; fn operation<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T>
fn operation_prime<T>(gradient: &Tensor<T>, vec: Vec<&Tensor<T>>) -> Vec<Tensor<T>> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1!= 1 && x2 == 1 { let mut vector_grad = Vec::with_capacity(y1); for i in 0..y1 { ...
{ let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1 != 1 && x2 == 1 { let transform = vec[1].buffer(); Tensor::from_vec(Vec2(x1, y1), vec[0].buffer().iter().enumerate().map(|(i, &x)| x + transform[i % y1]).collect()) } else { &vec[0] + &vec[1] } }
identifier_body
add.rs
use std::string::{String}; use std::sync::{Arc}; use std::ops::{Mul, Add}; use math::{Vec2}; use node::{Node, Graph}; use tensor::{Tensor}; fn operation<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x...
else { vec![gradient.clone(), gradient.clone()] } } fn calc_dim(dims: Vec<Vec2>) -> Vec2 { let Vec2(x1, y1) = dims[0]; let Vec2(x2, y2) = dims[1]; assert!(x1 == 0 && x2 == 1 || x1 == x2); assert_eq!(y1, y2); dims[0] } pub fn add<T>(node_id: String, a: Arc<Graph<T>>, b: Arc<Graph<T>>) ...
{ let mut vector_grad = Vec::with_capacity(y1); for i in 0..y1 { let mut k = gradient.get(Vec2(0, i)); for j in 1..x1 { k = k + gradient.get(Vec2(j, i)); } vector_grad.push(k); } vec![gradient.clone(), Tensor::from_vec(Vec2...
conditional_block
sw_vers.rs
/* * Mac OS X related checks */ use std::process::Command; use regex::Regex; pub struct SwVers { pub product_name: Option<String>, pub product_version: Option<String>, pub build_version: Option<String> } fn extract_from_regex(stdout: &String, regex: Regex) -> Option<String> { match regex.captures_it...
Some(parse(stdout.to_string())) } pub fn parse(version_str: String) -> SwVers { let product_name_regex = Regex::new(r"ProductName:\s([\w\s]+)\n").unwrap(); let product_version_regex = Regex::new(r"ProductVersion:\s(\w+\.\w+\.\w+)").unwrap(); let build_number_regex = Regex::new(r"BuildVersion:\s(\w+)")....
Err(_) => return None }; let stdout = String::from_utf8_lossy(&output.stdout);
random_line_split
sw_vers.rs
/* * Mac OS X related checks */ use std::process::Command; use regex::Regex; pub struct SwVers { pub product_name: Option<String>, pub product_version: Option<String>, pub build_version: Option<String> } fn extract_from_regex(stdout: &String, regex: Regex) -> Option<String> { match regex.captures_it...
pub fn parse(version_str: String) -> SwVers { let product_name_regex = Regex::new(r"ProductName:\s([\w\s]+)\n").unwrap(); let product_version_regex = Regex::new(r"ProductVersion:\s(\w+\.\w+\.\w+)").unwrap(); let build_number_regex = Regex::new(r"BuildVersion:\s(\w+)").unwrap(); SwVers { produ...
{ let output = match Command::new("sw_vers").output() { Ok(output) => output, Err(_) => return None }; let stdout = String::from_utf8_lossy(&output.stdout); Some(parse(stdout.to_string())) }
identifier_body
sw_vers.rs
/* * Mac OS X related checks */ use std::process::Command; use regex::Regex; pub struct SwVers { pub product_name: Option<String>, pub product_version: Option<String>, pub build_version: Option<String> } fn
(stdout: &String, regex: Regex) -> Option<String> { match regex.captures_iter(&stdout).next() { Some(m) => { match m.get(1) { Some(s) => { Some(s.as_str().to_owned()) }, None => None } }, None => None...
extract_from_regex
identifier_name
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use std::cell::RefCell; use cpython::*; use ::bookmarkstore::BookmarkStore; use cpython_ext::{PyNone, PyPa...
py_class!(class bookmarkstore |py| { data bm_store: RefCell<BookmarkStore>; def __new__(_cls, path: &PyPath) -> PyResult<bookmarkstore> { let bm_store = { BookmarkStore::new(path.as_path()) .map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))? }; ...
{ let name = [package, "bookmarkstore"].join("."); let m = PyModule::new(py, &name)?; m.add_class::<bookmarkstore>(py)?; Ok(m) }
identifier_body
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use std::cell::RefCell; use cpython::*; use ::bookmarkstore::BookmarkStore; use cpython_ext::{PyNone, PyPa...
def update(&self, bookmark: &str, node: PyBytes) -> PyResult<PyNone> { let mut bm_store = self.bm_store(py).borrow_mut(); let hgid = HgId::from_slice(node.data(py)) .map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?; bm_store.update(bookmark, hgid) ...
BookmarkStore::new(path.as_path()) .map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))? }; bookmarkstore::create_instance(py, RefCell::new(bm_store)) }
random_line_split
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use std::cell::RefCell; use cpython::*; use ::bookmarkstore::BookmarkStore; use cpython_ext::{PyNone, PyPa...
(py: Python, package: &str) -> PyResult<PyModule> { let name = [package, "bookmarkstore"].join("."); let m = PyModule::new(py, &name)?; m.add_class::<bookmarkstore>(py)?; Ok(m) } py_class!(class bookmarkstore |py| { data bm_store: RefCell<BookmarkStore>; def __new__(_cls, path: &PyPath) -> PyR...
init_module
identifier_name
test_rng.rs
extern crate cryptopals; extern crate rand; extern crate time; use cryptopals::crypto::rng::{MT, untemper}; use rand::{Rng, SeedableRng, thread_rng};
#[test] fn test_rng_deterministic() { let mut m1: MT = SeedableRng::from_seed(314159); let mut m2: MT = SeedableRng::from_seed(314159); for _ in 0.. 1024 { assert_eq!(m1.gen::<u32>(), m2.gen::<u32>()); } } #[test] fn test_seed_recovery_from_time() { let mut time = get_time().sec; time +...
use time::{get_time};
random_line_split
test_rng.rs
extern crate cryptopals; extern crate rand; extern crate time; use cryptopals::crypto::rng::{MT, untemper}; use rand::{Rng, SeedableRng, thread_rng}; use time::{get_time}; #[test] fn test_rng_deterministic()
#[test] fn test_seed_recovery_from_time() { let mut time = get_time().sec; time += thread_rng().gen_range(40, 1000); let mut m: MT = SeedableRng::from_seed(time as u32); let output = m.gen::<u32>(); for seed in get_time().sec + 2000.. 0 { let mut checker: MT = SeedableRng::from_seed(seed a...
{ let mut m1: MT = SeedableRng::from_seed(314159); let mut m2: MT = SeedableRng::from_seed(314159); for _ in 0 .. 1024 { assert_eq!(m1.gen::<u32>(), m2.gen::<u32>()); } }
identifier_body
test_rng.rs
extern crate cryptopals; extern crate rand; extern crate time; use cryptopals::crypto::rng::{MT, untemper}; use rand::{Rng, SeedableRng, thread_rng}; use time::{get_time}; #[test] fn test_rng_deterministic() { let mut m1: MT = SeedableRng::from_seed(314159); let mut m2: MT = SeedableRng::from_seed(314159); ...
} } #[test] fn test_untemper() { let mut m: MT = SeedableRng::from_seed(314159); for i in 0.. 624 { let output = m.gen::<u32>(); assert_eq!(untemper(output), m.state[i]); } } #[test] fn test_rng_clone_from_output() { let mut m: MT = SeedableRng::from_seed(314159); let mut stat...
{ assert_eq!(seed, time); break; }
conditional_block
test_rng.rs
extern crate cryptopals; extern crate rand; extern crate time; use cryptopals::crypto::rng::{MT, untemper}; use rand::{Rng, SeedableRng, thread_rng}; use time::{get_time}; #[test] fn test_rng_deterministic() { let mut m1: MT = SeedableRng::from_seed(314159); let mut m2: MT = SeedableRng::from_seed(314159); ...
() { let mut time = get_time().sec; time += thread_rng().gen_range(40, 1000); let mut m: MT = SeedableRng::from_seed(time as u32); let output = m.gen::<u32>(); for seed in get_time().sec + 2000.. 0 { let mut checker: MT = SeedableRng::from_seed(seed as u32); if checker.gen::<u32>() =...
test_seed_recovery_from_time
identifier_name
manager.rs
// Copyright 2015-2018 Deyan Ginev. See the LICENSE // file at the top-level directory of this distribution. // // Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed // except according to those terms. use std::collections::HashM...
else if sink_thread.join().is_err() { println!("Sink thread died unexpectedly!"); Err(zmq::Error::ETERM) } else if finalize_thread.join().is_err() { println!("DB thread died unexpectedly!"); Err(zmq::Error::ETERM) } else { println!("Manager successfully terminated!"); Ok(())...
{ println!("Ventilator thread died unexpectedly!"); Err(zmq::Error::ETERM) }
conditional_block
manager.rs
// Copyright 2015-2018 Deyan Ginev. See the LICENSE // file at the top-level directory of this distribution. // // Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed // except according to those terms. use std::collections::HashM...
Ventilator { port: source_port, queue_size: source_queue_size, message_size: source_message_size, backend_address: source_backend_address.clone(), } .start( &vent_services_arc, &vent_progress_queue_arc, &vent_done_queue_arc, job_limit, ...
{ // We'll use some local memoization shared between source and sink: let services: HashMap<String, Option<Service>> = HashMap::new(); let progress_queue: HashMap<i64, TaskProgress> = HashMap::new(); let done_queue: Vec<TaskReport> = Vec::new(); let services_arc = Arc::new(Mutex::new(services)); ...
identifier_body
manager.rs
// Copyright 2015-2018 Deyan Ginev. See the LICENSE // file at the top-level directory of this distribution. // // Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed // except according to those terms. use std::collections::HashM...
{ /// port for requesting/dispatching jobs pub source_port: usize, /// port for responding/receiving results pub result_port: usize, /// the size of the dispatch queue /// (also the batch size for Task store queue requests) pub queue_size: usize, /// size of an individual message chunk sent via zeromq ...
TaskManager
identifier_name
manager.rs
// Copyright 2015-2018 Deyan Ginev. See the LICENSE // file at the top-level directory of this distribution. // // Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed // except according to those terms. use std::collections::HashM...
Ok(()) } } }
random_line_split
kalloc.rs
// The MIT License (MIT) // // Copyright (c) 2015 Kashyap // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, m...
} } fn kfree(v : Address) { //struct run *r; if ((v % PG_SIZE) > 0) || (v2p(v) >= PHYSTOP) { panic("kfree"); } unsafe { if v < end { panic("kfree"); } } unsafe { // Fill with junk to catch dangling refs. memset(v as * mut u8, 1, PG_SIZE as usize); }...
{ break; }
conditional_block
kalloc.rs
// The MIT License (MIT) // // Copyright (c) 2015 Kashyap // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, m...
} fn kfree(v : Address) { //struct run *r; if ((v % PG_SIZE) > 0) || (v2p(v) >= PHYSTOP) { panic("kfree"); } unsafe { if v < end { panic("kfree"); } } unsafe { // Fill with junk to catch dangling refs. memset(v as * mut u8, 1, PG_SIZE as usize); } //...
{ let mut address = pg_roundup(vstart); // Keep it around for future debugging //unsafe { // asm!("mov $0 , %rax" : /* no outputs */ : "r"(vend) : "eax"); // asm!("mov $0 , %rbx" : /* no outputs */ : "r"(address) : "eax"); //} unsafe { end = vstart; } loop { kfree(address); address = address + PG_SIZE;...
identifier_body
kalloc.rs
// The MIT License (MIT) // // Copyright (c) 2015 Kashyap // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, m...
static mut kmem : KmemT = KmemT{ lock: DUMMY_LOCK, use_lock: 0} ; static mut end : Address = 0; pub fn kinit1(vstart: Address, vend: Address) { unsafe { init_lock(& mut kmem.lock, "kmem"); kmem.use_lock = 0; } free_range(vstart, vend); } fn free_range(vstart: Address, vend: Address) { let mut address = pg_ro...
random_line_split
kalloc.rs
// The MIT License (MIT) // // Copyright (c) 2015 Kashyap // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, m...
(vstart: Address, vend: Address) { unsafe { init_lock(& mut kmem.lock, "kmem"); kmem.use_lock = 0; } free_range(vstart, vend); } fn free_range(vstart: Address, vend: Address) { let mut address = pg_roundup(vstart); // Keep it around for future debugging //unsafe { // asm!("mov $0, %rax" : /* no outputs */ ...
kinit1
identifier_name
boiler_dispatch.rs
//! Experimental boiler library for dispatching messages to handlers use boiler::{Message, EMsg}; pub trait MessageHandler { fn invoke(&mut self, message: Message); } impl<F: FnMut(Message)> MessageHandler for F { fn invoke(&mut self, message: Message) { self(message); } } pub struct MessageDisp...
// We were unable to find anything, call the fallback self.invoke_fallback(message); } fn invoke_fallback(&mut self, message: Message) { if let &mut Some(ref mut handler) = &mut self.fallback { handler(message); } } }
{ handler.invoke(message); return; }
conditional_block
boiler_dispatch.rs
//! Experimental boiler library for dispatching messages to handlers use boiler::{Message, EMsg}; pub trait MessageHandler { fn invoke(&mut self, message: Message); } impl<F: FnMut(Message)> MessageHandler for F { fn invoke(&mut self, message: Message) { self(message); } } pub struct MessageDisp...
} fn invoke_fallback(&mut self, message: Message) { if let &mut Some(ref mut handler) = &mut self.fallback { handler(message); } } }
} // We were unable to find anything, call the fallback self.invoke_fallback(message);
random_line_split
boiler_dispatch.rs
//! Experimental boiler library for dispatching messages to handlers use boiler::{Message, EMsg}; pub trait MessageHandler { fn invoke(&mut self, message: Message); } impl<F: FnMut(Message)> MessageHandler for F { fn
(&mut self, message: Message) { self(message); } } pub struct MessageDispatcher<'a> { handlers: Vec<Option<Box<MessageHandler + 'a>>>, fallback: Option<Box<FnMut(Message)>> } impl<'a> MessageDispatcher<'a> { pub fn new() -> Self { // Fill the vector with Nones, we can't use vec! for th...
invoke
identifier_name
boiler_dispatch.rs
//! Experimental boiler library for dispatching messages to handlers use boiler::{Message, EMsg}; pub trait MessageHandler { fn invoke(&mut self, message: Message); } impl<F: FnMut(Message)> MessageHandler for F { fn invoke(&mut self, message: Message) { self(message); } } pub struct MessageDisp...
pub fn handle(&mut self, message: Message) { if let &mut Some(ref mut handler) = &mut self.handlers[message.header.emsg() as usize] { handler.invoke(message); return; } // We were unable to find anything, call the fallback self.invoke_fallback(message); ...
{ self.fallback = Some(handler); }
identifier_body
response.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/. * * Copyright (c) 2016 Jacob Peddicord <jacob@peddicord.net> */ use serde_json::{self, Error}; use submission::Sub...
}
}
random_line_split
response.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/. * * Copyright (c) 2016 Jacob Peddicord <jacob@peddicord.net> */ use serde_json::{self, Error}; use submission::Sub...
{ None, GeneralFailure { stderr: String }, TestFailures { pass: u8, fail: u8, diff: String }, InternalError(String), } #[derive(Debug, Serialize)] pub struct Response { id: u32, user: u32, problem: String, result: SubmissionStatus, meta: SubmissionMeta, } impl Response { pub f...
SubmissionMeta
identifier_name
root_moves_list.rs
use std::slice; use std::ops::{Deref,DerefMut,Index,IndexMut}; use std::iter::{Iterator,IntoIterator,FusedIterator,TrustedLen,ExactSizeIterator}; use std::ptr; use std::mem; use std::sync::atomic::{Ordering,AtomicUsize}; use pleco::{MoveList, BitMove}; use super::{RootMove, MAX_MOVES}; pub struct RootMoveList { ...
#[inline] fn size_hint(&self) -> (usize, Option<usize>) { (self.len - self.idx, Some(self.len - self.idx)) } } impl<'a> IntoIterator for &'a RootMoveList { type Item = RootMove; type IntoIter = MoveIter<'a>; #[inline] fn into_iter(self) -> Self::IntoIter { MoveIter { ...
{ if self.idx >= self.len { None } else { unsafe { let m = *self.movelist.get_unchecked(self.idx); self.idx += 1; Some(m) } } }
identifier_body
root_moves_list.rs
use std::slice; use std::ops::{Deref,DerefMut,Index,IndexMut}; use std::iter::{Iterator,IntoIterator,FusedIterator,TrustedLen,ExactSizeIterator}; use std::ptr; use std::mem; use std::sync::atomic::{Ordering,AtomicUsize}; use pleco::{MoveList, BitMove}; use super::{RootMove, MAX_MOVES}; pub struct RootMoveList { ...
(&mut self, moves: &MoveList) { self.len.store(moves.len(), Ordering::SeqCst); for (i, mov) in moves.iter().enumerate() { self[i] = RootMove::new(*mov); } } /// Applies `RootMove::rollback()` to each `RootMove` inside. #[inline] pub fn rollback(&mut self) { s...
replace
identifier_name
root_moves_list.rs
use std::slice; use std::ops::{Deref,DerefMut,Index,IndexMut}; use std::iter::{Iterator,IntoIterator,FusedIterator,TrustedLen,ExactSizeIterator}; use std::ptr; use std::mem; use std::sync::atomic::{Ordering,AtomicUsize}; use pleco::{MoveList, BitMove}; use super::{RootMove, MAX_MOVES}; pub struct RootMoveList { ...
/// Converts to a `MoveList`. pub fn to_list(&self) -> MoveList { let vec = self.iter().map(|m| m.bit_move).collect::<Vec<BitMove>>(); MoveList::from(vec) } /// Returns the previous best score. #[inline] pub fn prev_best_score(&self) -> i32 { unsafe { self.g...
random_line_split
root_moves_list.rs
use std::slice; use std::ops::{Deref,DerefMut,Index,IndexMut}; use std::iter::{Iterator,IntoIterator,FusedIterator,TrustedLen,ExactSizeIterator}; use std::ptr; use std::mem; use std::sync::atomic::{Ordering,AtomicUsize}; use pleco::{MoveList, BitMove}; use super::{RootMove, MAX_MOVES}; pub struct RootMoveList { ...
else { unsafe { let m = *self.movelist.get_unchecked(self.idx); self.idx += 1; Some(m) } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { (self.len - self.idx, Some(self.len - self.idx)) } } impl<'a>...
{ None }
conditional_block
unix.rs
use libloading::Library; use std::fs::ReadDir; use types::Identifier; /// Grabs all `Library` entries found within a given directory pub(crate) struct LibraryIterator { directory: ReadDir, } impl LibraryIterator { pub(crate) fn new(directory: ReadDir) -> LibraryIterator { LibraryIterator { directory } } } im...
continue; } } } else { continue; } } None } }
{ while let Some(entry) = self.directory.next() { let entry = if let Ok(entry) = entry { entry } else { continue }; let path = entry.path(); // An entry is a library if it is a file with a 'so' extension. if path.is_file() && path.extension().map_or(false, |ext| e...
identifier_body
unix.rs
use libloading::Library; use std::fs::ReadDir; use types::Identifier; /// Grabs all `Library` entries found within a given directory pub(crate) struct LibraryIterator { directory: ReadDir, } impl LibraryIterator { pub(crate) fn new(directory: ReadDir) -> LibraryIterator { LibraryIterator { directory } } } im...
} None } }
{ continue; }
conditional_block
unix.rs
use libloading::Library; use std::fs::ReadDir; use types::Identifier; /// Grabs all `Library` entries found within a given directory pub(crate) struct LibraryIterator { directory: ReadDir, } impl LibraryIterator { pub(crate) fn new(directory: ReadDir) -> LibraryIterator { LibraryIterator { directory } } } im...
} } else { continue; } } None } }
eprintln!("ion: failed to load library: {:?}, {:?}", path, why); continue; }
random_line_split
unix.rs
use libloading::Library; use std::fs::ReadDir; use types::Identifier; /// Grabs all `Library` entries found within a given directory pub(crate) struct
{ directory: ReadDir, } impl LibraryIterator { pub(crate) fn new(directory: ReadDir) -> LibraryIterator { LibraryIterator { directory } } } impl Iterator for LibraryIterator { // The `Identifier` is the name of the namespace for which values may be pulled. // The `Library` is a handle to dynamic libr...
LibraryIterator
identifier_name
win.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.foreground = color; self.apply(); Ok(true) } fn bg(&mut self, color: color::Color) -> io::Result<bool> { self.background = color; self.apply(); Ok(true) } fn attr(&mut self, attr: attr::Attr) -> io::Result<bool> { match attr { ...
} impl<T: Write+Send+'static> Terminal<T> for WinConsole<T> { fn fg(&mut self, color: color::Color) -> io::Result<bool> {
random_line_split
win.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: Write> Write for WinConsole<T> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.buf.write(buf) } fn flush(&mut self) -> io::Result<()> { self.buf.flush() } } impl<T: Write+Send+'static> Terminal<T> for WinConsole<T> { fn fg(&mut self, color: color::Color) -...
{ let fg; let bg; unsafe { let mut buffer_info = ::std::mem::uninitialized(); if GetConsoleScreenBufferInfo(GetStdHandle(-11), &mut buffer_info) != 0 { fg = bits_to_color(buffer_info.wAttributes); bg = bits_to_color(buffer_info.wAttributes ...
identifier_body
win.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...
(bits: u16) -> color::Color { let color = match bits & 0x7 { 0 => color::BLACK, 0x1 => color::BLUE, 0x2 => color::GREEN, 0x4 => color::RED, 0x6 => color::YELLOW, 0x5 => color::MAGENTA, 0x3 => color::CYAN, 0x7 => color::WHITE, _ => unreachable!(...
bits_to_color
identifier_name
systick.rs
//! # SysTick for the Cortex-M4F //! //! Each Cortex-M4 has a timer peripheral typically used for OS scheduling tick. //! Here we configure it as a countdown timer that overflows every 2**24 ticks //! (so about once a second at 16MHz), and maintain a separate atomic overflow //! count to accurately track time since pow...
else { // No overflow, good to go (overflow1, ticks) } } /// Calculates the elapsed period in SysTicks between `start` and the current value. pub fn get_since(start: usize) -> usize { let now = get_ticks(); // SysTick counts down! This subtraction is opposite to what you expect. let de...
{ // A overflow occurred while we were reading the tick register // Should be safe to try again (overflow2, get_ticks()) }
conditional_block
systick.rs
//! # SysTick for the Cortex-M4F //! //! Each Cortex-M4 has a timer peripheral typically used for OS scheduling tick. //! Here we configure it as a countdown timer that overflows every 2**24 ticks //! (so about once a second at 16MHz), and maintain a separate atomic overflow //! count to accurately track time since pow...
lazy_static! { /// total number of times SysTick has wrapped pub static ref SYSTICK_WRAP_COUNT:AtomicUsize = ATOMIC_USIZE_INIT; } // **************************************************************************** // // Private Types // // **************************************************************************...
// // **************************************************************************** /// SysTick is a 24-bit timer pub const SYSTICK_MAX: usize = (1 << 24) - 1;
random_line_split
systick.rs
//! # SysTick for the Cortex-M4F //! //! Each Cortex-M4 has a timer peripheral typically used for OS scheduling tick. //! Here we configure it as a countdown timer that overflows every 2**24 ticks //! (so about once a second at 16MHz), and maintain a separate atomic overflow //! count to accurately track time since pow...
() { SYSTICK_WRAP_COUNT.fetch_add(1, Ordering::Relaxed); } /// Returns how many times SysTick has overflowed. pub fn get_overflows() -> usize { SYSTICK_WRAP_COUNT.load(Ordering::Relaxed) } /// Gets the current SysTick value pub fn get_ticks() -> usize { unsafe { (*cm_periph::SYST::ptr()).cvr.read() as usi...
isr
identifier_name
systick.rs
//! # SysTick for the Cortex-M4F //! //! Each Cortex-M4 has a timer peripheral typically used for OS scheduling tick. //! Here we configure it as a countdown timer that overflows every 2**24 ticks //! (so about once a second at 16MHz), and maintain a separate atomic overflow //! count to accurately track time since pow...
/// How long since the system booted in ticks. /// The u64 is good for 584,000 years. pub fn run_time_ticks() -> u64 { let (overflows, ticks) = get_overflows_ticks(); let mut result: u64; result = overflows as u64; result *= (SYSTICK_MAX + 1) as u64; result += (SYSTICK_MAX - ticks) as u64; res...
{ let now = get_ticks(); // SysTick counts down! This subtraction is opposite to what you expect. let delta = start.wrapping_sub(now) & SYSTICK_MAX; delta }
identifier_body
main.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![feature(iterator_for_each)] #[macro_use] extern crate clap; extern crate iota_kerl; extern crate iota_sign; extern crate iota_trytes; extern crate log4rs; #[macro_use] extern crate log; #[macro_use] extern crate mysql...
() { let matches = app::build().get_matches(); let args = Args::parse(&matches).unwrap_or_else(|err| { eprintln!("Invalid arguments: {}", err); exit(1); }); let Args { zmq_uri, mysql_uri, retry_interval, update_interval, calculation_threads, calculation_limit, generation_limi...
main
identifier_name
main.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![feature(iterator_for_each)] #[macro_use] extern crate clap; extern crate iota_kerl; extern crate iota_sign; extern crate iota_trytes; extern crate log4rs; #[macro_use] extern crate log; #[macro_use] extern crate mysql...
exit(1); }); let (insert_tx, insert_rx) = mpsc::channel(); let (approve_tx, approve_rx) = mpsc::channel(); let (solidate_tx, solidate_rx) = mpsc::channel(); let (calculate_tx, calculate_rx) = mpsc::channel(); let ctx = zmq::Context::new(); let socket = ctx.socket(zmq::SUB).expect("ZMQ socket create f...
{ let matches = app::build().get_matches(); let args = Args::parse(&matches).unwrap_or_else(|err| { eprintln!("Invalid arguments: {}", err); exit(1); }); let Args { zmq_uri, mysql_uri, retry_interval, update_interval, calculation_threads, calculation_limit, generation_limit, ...
identifier_body
main.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![feature(iterator_for_each)] #[macro_use] extern crate clap; extern crate iota_kerl; extern crate iota_sign; extern crate iota_trytes; extern crate log4rs; #[macro_use] extern crate log; #[macro_use] extern crate mysql...
solidate_rx, mysql_uri, retry_interval, transaction_mapper: transaction_mapper.clone(), }; let calculate_threads = CalculateThreads { calculate_rx, mysql_uri, retry_interval, calculation_threads, calculation_limit, transaction_mapper: transaction_mapper.clone(), }; let zm...
transaction_mapper: transaction_mapper.clone(), bundle_mapper: bundle_mapper.clone(), }; let solidate_thread = SolidateThread {
random_line_split
discriminant_value-wrapper.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
Second(u64) } pub fn main() { assert!(mem::discriminant(&ADT::First(0,0)) == mem::discriminant(&ADT::First(1,1))); assert!(mem::discriminant(&ADT::Second(5)) == mem::discriminant(&ADT::Second(6))); assert!(mem::discriminant(&ADT::First(2,2))!= mem::discriminant(&ADT::Second(2))); let _ = mem::dis...
enum ADT { First(u32, u32),
random_line_split
discriminant_value-wrapper.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ First(u32, u32), Second(u64) } pub fn main() { assert!(mem::discriminant(&ADT::First(0,0)) == mem::discriminant(&ADT::First(1,1))); assert!(mem::discriminant(&ADT::Second(5)) == mem::discriminant(&ADT::Second(6))); assert!(mem::discriminant(&ADT::First(2,2))!= mem::discriminant(&ADT::Second(2))...
ADT
identifier_name
mpatch.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use libc::ssize_t; use mpatch_sys::*; unsafe extern "C" fn get_next_lin...
assert!(full_text.is_err()); // Delta doesn't match base_text let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\xFF\x00\x00\x01\x00\x00\x00\x00\x0Adeltafied "]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); } }
b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adelta", ]; let full_text = get_full_text(&base_text[..], &deltas);
random_line_split
mpatch.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use libc::ssize_t; use mpatch_sys::*; unsafe extern "C" fn get_next_lin...
#[test] fn test_apply_delta() { let base_text = b"My data"; let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied "]; let full_text = get_full_text(&base_text[..], &deltas).unwrap(); assert_eq!(b"My deltafied data", full_text[..]...
{ let base_text = b""; let full_text = get_full_text(&base_text[..], &vec![]).unwrap(); assert_eq!(base_text, full_text.as_slice()); }
identifier_body
mpatch.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use libc::ssize_t; use mpatch_sys::*; unsafe extern "C" fn get_next_lin...
unsafe { let patch: *mut mpatch_flist = mpatch_fold( deltas as *const Vec<&[u8]> as *mut c_void, Some(get_next_link), 0, deltas.len() as isize, ); if patch.is_null() { return Err("mpatch failed to process the deltas"); } ...
{ return Ok(base_text.to_vec()); }
conditional_block
mpatch.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use libc::ssize_t; use mpatch_sys::*; unsafe extern "C" fn get_next_lin...
() { let base_text = b""; let full_text = get_full_text(&base_text[..], &vec![]).unwrap(); assert_eq!(base_text, full_text.as_slice()); } #[test] fn test_apply_delta() { let base_text = b"My data"; let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\x03\x00\x00\...
no_deltas_empty_base
identifier_name
scope.rs
use std::fmt; use std::cmp::Eq; use std::hash::Hash; use std::collections::HashMap; use util::*; use error::*; use traits::*; use super::*; #[derive(Clone)] pub struct ProcessingScope<T: Hash + Eq> { scope_id: String, parent_id: Option<String>, environment: ProcessingScopeEnvironment, scoped_ident...
} pub fn id(&self) -> &str { &self.scope_id } pub fn add_ident( &mut self, key: String, binding: CommonBindings<T>, ) -> DocumentProcessingResult<()> { self.scoped_idents.insert(key, binding); Ok(()) } pub fn get_ident(&mut self, key: &str) ...
scoped_idents: Default::default(), shaped_idents: Default::default(), element_bindings: Default::default(), }
random_line_split
scope.rs
use std::fmt; use std::cmp::Eq; use std::hash::Hash; use std::collections::HashMap; use util::*; use error::*; use traits::*; use super::*; #[derive(Clone)] pub struct ProcessingScope<T: Hash + Eq> { scope_id: String, parent_id: Option<String>, environment: ProcessingScopeEnvironment, scoped_ident...
pub fn add_element_binding( &mut self, key: String, common_binding: CommonBindings<T>, ) -> DocumentProcessingResult<()> { self.element_bindings.insert(key, common_binding); Ok(()) } pub fn get_element_binding(&mut self, key: &str) -> Option<CommonBindings<T>> ...
{ self.shaped_idents.get(key).map(|v| v.to_owned()) }
identifier_body
scope.rs
use std::fmt; use std::cmp::Eq; use std::hash::Hash; use std::collections::HashMap; use util::*; use error::*; use traits::*; use super::*; #[derive(Clone)] pub struct ProcessingScope<T: Hash + Eq> { scope_id: String, parent_id: Option<String>, environment: ProcessingScopeEnvironment, scoped_ident...
(&self) -> &str { &self.scope_id } pub fn add_ident( &mut self, key: String, binding: CommonBindings<T>, ) -> DocumentProcessingResult<()> { self.scoped_idents.insert(key, binding); Ok(()) } pub fn get_ident(&mut self, key: &str) -> Option<CommonBind...
id
identifier_name
invocation.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket 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 // (...
impl<'a> Invocation<'a> { pub fn new(state: &str, print_invocation: bool, tool: &str, opts: &'a [String]) -> Invocation<'a> { Invocation { state_file: Path::new(state), print_invocation: print_invocation, tool: from_str(tool).e...
opts: &'a [String], }
random_line_split
invocation.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket 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 // (...
pub fn run(&self) { use std::io::fs::File; use serialize::ebml::reader::Decoder; use serialize::ebml::Doc; // don't try-block this; if we can't read the state file, we really do need to fail!(). let state = { let state_bytes = try!({try!(File::open(self.state_fi...
{ Invocation { state_file: Path::new(state), print_invocation: print_invocation, tool: from_str(tool).expect("unknown tool specified; this is more than likely a bug"), opts: opts, } }
identifier_body
invocation.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket 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 // (...
Cxx => { } Ar => { } Ld => { } } } }
{ }
conditional_block
invocation.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket 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 // (...
(state: &str, print_invocation: bool, tool: &str, opts: &'a [String]) -> Invocation<'a> { Invocation { state_file: Path::new(state), print_invocation: print_invocation, tool: from_str(tool).expect("unknown tool specified; this is m...
new
identifier_name
riscv32imc_esp_espidf.rs
use crate::spec::{LinkerFlavor, PanicStrategy, RelocModel}; use crate::spec::{Target, TargetOptions}; pub fn target() -> Target
// Support for atomics is necessary for the Rust STD library, which is supported by the ESP-IDF framework. max_atomic_width: Some(32), atomic_cas: true, features: "+m,+c".to_string(), executables: true, panic_strategy: PanicStrategy::Abort, ...
{ Target { data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(), llvm_target: "riscv32".to_string(), pointer_width: 32, arch: "riscv32".to_string(), options: TargetOptions { families: vec!["unix".to_string()], os: "espidf".to_string(), ...
identifier_body
riscv32imc_esp_espidf.rs
use crate::spec::{LinkerFlavor, PanicStrategy, RelocModel}; use crate::spec::{Target, TargetOptions}; pub fn
() -> Target { Target { data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(), llvm_target: "riscv32".to_string(), pointer_width: 32, arch: "riscv32".to_string(), options: TargetOptions { families: vec!["unix".to_string()], os: "espidf".to_string()...
target
identifier_name
riscv32imc_esp_espidf.rs
use crate::spec::{LinkerFlavor, PanicStrategy, RelocModel}; use crate::spec::{Target, TargetOptions}; pub fn target() -> Target {
options: TargetOptions { families: vec!["unix".to_string()], os: "espidf".to_string(), env: "newlib".to_string(), vendor: "espressif".to_string(), linker_flavor: LinkerFlavor::Gcc, linker: Some("riscv32-esp-elf-gcc".to_string()), ...
Target { data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(), llvm_target: "riscv32".to_string(), pointer_width: 32, arch: "riscv32".to_string(),
random_line_split