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
keystore.rs
#![allow(non_snake_case)] use serde_json::{self, Value}; use request::Handler; use error::ConsulResult; use std::error::Error; pub struct Keystore{ handler: Handler }
} } pub fn set_key(&self, key: String, value: String) -> ConsulResult<()> { self.handler.put(&key, value, Some("application/json"))?; Ok(()) } pub fn acquire_lock(&self, key: String, address: String, session_id: &String) -> ConsulResult<bool> { let uri = format!("{}?acq...
impl Keystore { pub fn new(address: &str) -> Keystore { Keystore { handler: Handler::new(&format!("{}/v1/kv", address))
random_line_split
keystore.rs
#![allow(non_snake_case)] use serde_json::{self, Value}; use request::Handler; use error::ConsulResult; use std::error::Error; pub struct Keystore{ handler: Handler } impl Keystore { pub fn new(address: &str) -> Keystore { Keystore { handler: Handler::new(&format!("{}/v1/kv", address)) ...
} pub fn release_lock(&self, key: String, address: &str, session_id: &String) -> ConsulResult<bool> { let uri = format!("{}?release={}", key, session_id); let result = self.handler.put(&uri, address.to_owned(), Some("application/json"))?; if result == "true" { Ok(true) ...
{ Ok(false) }
conditional_block
keystore.rs
#![allow(non_snake_case)] use serde_json::{self, Value}; use request::Handler; use error::ConsulResult; use std::error::Error; pub struct Keystore{ handler: Handler } impl Keystore { pub fn new(address: &str) -> Keystore { Keystore { handler: Handler::new(&format!("{}/v1/kv", address)) ...
pub fn release_lock(&self, key: String, address: &str, session_id: &String) -> ConsulResult<bool> { let uri = format!("{}?release={}", key, session_id); let result = self.handler.put(&uri, address.to_owned(), Some("application/json"))?; if result == "true" { Ok(true) } ...
{ let uri = format!("{}?acquire={}", key, session_id); let result = self.handler.put(&uri, address, Some("application/json"))?; if result == "true" { Ok(true) } else { Ok(false) } }
identifier_body
re_builder.rs
// Copyright 2014-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-MI...
{ pub pats: Vec<String>, pub size_limit: usize, pub dfa_size_limit: usize, pub case_insensitive: bool, pub multi_line: bool, pub dot_matches_new_line: bool, pub swap_greed: bool, pub ignore_whitespace: bool, pub unicode: bool, } impl Default for RegexOptions { fn default() -> S...
RegexOptions
identifier_name
re_builder.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// except according to those terms. /// The set of user configurable options for compiling zero or more regexes. #[derive(Clone, Debug)] pub struct RegexOptions { pub pats: Vec<String>, pub size_limit: usize, pub dfa_size_limit: usize, pub case_insensitive: bool, pub multi_line: bool, pub dot_m...
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
main.rs
use std::env; use std::process::exit; use std::fs::File; use std::io::BufReader; use std::io::BufWriter; use std::io::prelude::*; use std::collections::HashMap; enum OpcodeType { LocRequired, LocAndLabelRequred, NothingRequired, NotAnOpcode } static PROG_NAME: &'static str = "acslasmc v0.1"; static PR...
(var_map: &mut HashMap<String, u32>, counter: &mut u32, loc: &str) -> u32 { let owned_loc = loc.to_owned(); match var_map.get(&owned_loc) { Some(x) => return *x, None => () } var_map.insert(owned_loc, *counter); *counter += 1; *counter - 1 } fn opcode_type(potential_opcode: &str...
req_mem
identifier_name
main.rs
use std::env; use std::process::exit; use std::fs::File; use std::io::BufReader; use std::io::BufWriter; use std::io::prelude::*; use std::collections::HashMap; enum OpcodeType { LocRequired, LocAndLabelRequred, NothingRequired, NotAnOpcode } static PROG_NAME: &'static str = "acslasmc v0.1"; static PR...
println!("{}", PROG_NAME_LINE); let mut args = env::args(); let input_file_path = match args.nth(1) { Some(x) => x, None => { println!("Please pass a source file with ACSL assembly code and a target file for generated C code as arguments."); return 2; } }...
fn encapsulated_main() -> i32 {
random_line_split
main.rs
use std::env; use std::process::exit; use std::fs::File; use std::io::BufReader; use std::io::BufWriter; use std::io::prelude::*; use std::collections::HashMap; enum OpcodeType { LocRequired, LocAndLabelRequred, NothingRequired, NotAnOpcode } static PROG_NAME: &'static str = "acslasmc v0.1"; static PR...
fn opcode_type(potential_opcode: &str) -> OpcodeType { match potential_opcode { "LOAD" | "STORE" | "ADD" | "SUB" | "MULT" | "DIV" | "BE" | "BG" | "BL" | "BU" | "READ" | "PRINT" => OpcodeType::LocRequired, "END" => OpcodeType::NothingRequired, "DC" => OpcodeType::LocAndLabelRequred, ...
{ let owned_loc = loc.to_owned(); match var_map.get(&owned_loc) { Some(x) => return *x, None => () } var_map.insert(owned_loc, *counter); *counter += 1; *counter - 1 }
identifier_body
timeout_check.rs
use crate::{ bot::BotEnv, tasks::{RunsTask, Wait}, database::models::Timeout, }; use chrono::{ Duration, prelude::*, }; use diesel::prelude::*; use std::{ sync::Arc, thread, }; #[derive(Default)] pub struct TimeoutCheckTask { ran_once: bool, } pub fn remove_timeout(env: &BotEnv, timeout: &Timeout) ...
env.config.read().timeouts.role_check_interval.unwrap_or(300) } else { self.ran_once = true; 0 }; thread::sleep(Duration::seconds(sleep).to_std().unwrap()); let now = Utc::now(); let next_five_minutes = (now + Duration::minutes(5)).timestamp(); let mut timeout...
impl RunsTask for TimeoutCheckTask { fn start(mut self, env: Arc<BotEnv>) { loop { let sleep = if self.ran_once {
random_line_split
timeout_check.rs
use crate::{ bot::BotEnv, tasks::{RunsTask, Wait}, database::models::Timeout, }; use chrono::{ Duration, prelude::*, }; use diesel::prelude::*; use std::{ sync::Arc, thread, }; #[derive(Default)] pub struct TimeoutCheckTask { ran_once: bool, } pub fn remove_timeout(env: &BotEnv, timeout: &Timeout) ...
(mut self, env: Arc<BotEnv>) { loop { let sleep = if self.ran_once { env.config.read().timeouts.role_check_interval.unwrap_or(300) } else { self.ran_once = true; 0 }; thread::sleep(Duration::seconds(sleep).to_std().unwrap()); let now = Utc::now(); let next...
start
identifier_name
timeout_check.rs
use crate::{ bot::BotEnv, tasks::{RunsTask, Wait}, database::models::Timeout, }; use chrono::{ Duration, prelude::*, }; use diesel::prelude::*; use std::{ sync::Arc, thread, }; #[derive(Default)] pub struct TimeoutCheckTask { ran_once: bool, } pub fn remove_timeout(env: &BotEnv, timeout: &Timeout) ...
, }; timeouts.retain(|t| t.ends() <= next_five_minutes); if timeouts.is_empty() { continue; } let thread_env = Arc::clone(&env); std::thread::spawn(move || { for (wait, timeout) in Wait::new(timeouts.into_iter().map(|t| (t.ends(), t))) { std::thread::sleep...
{ warn!("could not load timeouts: {}", e); continue; }
conditional_block
timeout_check.rs
use crate::{ bot::BotEnv, tasks::{RunsTask, Wait}, database::models::Timeout, }; use chrono::{ Duration, prelude::*, }; use diesel::prelude::*; use std::{ sync::Arc, thread, }; #[derive(Default)] pub struct TimeoutCheckTask { ran_once: bool, } pub fn remove_timeout(env: &BotEnv, timeout: &Timeout)
impl RunsTask for TimeoutCheckTask { fn start(mut self, env: Arc<BotEnv>) { loop { let sleep = if self.ran_once { env.config.read().timeouts.role_check_interval.unwrap_or(300) } else { self.ran_once = true; 0 }; thread::sleep(Duration::seconds(sleep).to_std().unwr...
{ // FIXME: this may not work if the character is not in the cache, but this is needed to compile let mut member = match env.cache().read().member(*timeout.server_id, *timeout.user_id) { Some(m) => m, None => { warn!("could not get member for timeout check: missing in cache"); return; }, }...
identifier_body
mut_.rs
use std::fmt::{self, Debug}; use std::marker; use std::mem; use std::ops::{Index, IndexMut, Deref}; use base; use base::Stride as Base; /// A mutable strided slice. This is equivalent to `&mut [T]`, that /// only refers to every `n`th `T`. /// /// This can be viewed as an immutable strided slice via the `Deref` /// im...
impl<'a, T> IndexMut<usize> for Stride<'a, T> { fn index_mut<'b>(&'b mut self, n: usize) -> &'b mut T { self.get_mut(n).expect("Stride.index_mut: index out of bounds") } } impl<'a, T> Deref for Stride<'a, T> { type Target = ::imm::Stride<'a, T>; fn deref<'b>(&'b self) -> &'b ::imm::Stride<'a, T...
random_line_split
mut_.rs
use std::fmt::{self, Debug}; use std::marker; use std::mem; use std::ops::{Index, IndexMut, Deref}; use base; use base::Stride as Base; /// A mutable strided slice. This is equivalent to `&mut [T]`, that /// only refers to every `n`th `T`. /// /// This can be viewed as an immutable strided slice via the `Deref` /// im...
() { let v = &mut [1u8, 2, 3, 4, 5]; let mut s = Stride::new(v); eq!(s.reborrow(), [1,2,3,4,5]); eq!(s.reborrow(), [1,2,3,4,5]); } }
reborrow
identifier_name
mut_.rs
use std::fmt::{self, Debug}; use std::marker; use std::mem; use std::ops::{Index, IndexMut, Deref}; use base; use base::Stride as Base; /// A mutable strided slice. This is equivalent to `&mut [T]`, that /// only refers to every `n`th `T`. /// /// This can be viewed as an immutable strided slice via the `Deref` /// im...
} /// An iterator over `n` mutable substrides of a given stride, each of /// which points to every `n`th element starting at successive /// offsets. pub struct Substrides<'a, T: 'a> { base: base::Substrides<'a, T>, } impl<'a, T> Iterator for Substrides<'a, T> { type Item = Stride<'a, T>; fn next(&mut sel...
{ unsafe { mem::transmute(self) } }
identifier_body
url.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/. */ //! Common handling for the specified value CSS url() values. use gecko_bindings::structs::{ServoBundledURI, URLE...
/// Convert from nsStyleImageRequest to SpecifiedUrl. pub unsafe fn from_image_request(image_request: &nsStyleImageRequest) -> Result<SpecifiedUrl, ()> { if image_request.mImageValue.mRawPtr.is_null() { return Err(()); } let image_value = image_request.mImageValue.mRawPtr.as...
random_line_split
url.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/. */ //! Common handling for the specified value CSS url() values. use gecko_bindings::structs::{ServoBundledURI, URLE...
}
{ use gecko_bindings::bindings::Gecko_ImageValue_SizeOfIncludingThis; let mut n = 0; // XXX: measure `serialization` once bug 1397971 lands // We ignore `extra_data`, because RefPtr is tricky, and there aren't // many of them in practise (sharing is common). if let So...
identifier_body
url.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/. */ //! Common handling for the specified value CSS url() values. use gecko_bindings::structs::{ServoBundledURI, URLE...
(&mut self) { use gecko_bindings::bindings::Gecko_ImageValue_Create; debug_assert_eq!(self.image_value, None); self.image_value = { unsafe { let arc_offset = Arc::into_raw_offset(self.serialization.clone()); let ptr = Gecko_ImageValue_Create( ...
build_image_value
identifier_name
url.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/. */ //! Common handling for the specified value CSS url() values. use gecko_bindings::structs::{ServoBundledURI, URLE...
let image_value = image_request.mImageValue.mRawPtr.as_ref().unwrap(); let ref url_value_data = image_value._base; let mut result = try!(Self::from_url_value_data(url_value_data)); result.build_image_value(); Ok(result) } /// Returns true if this URL looks like a fragm...
{ return Err(()); }
conditional_block
node.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program 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. // Th...
<'a> { /// Null avl node; could be an empty root or an empty branch entry. Empty, /// Leaf node; has key slice and value. Value may not be empty. Leaf(NodeKey, &'a [u8]), /// Branch node; has a key, 2 child nodes (each possibly null) and a height. Branch(u32, NodeKey, [&'a [u8]; 2]), } impl<'a>...
Node
identifier_name
node.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program 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. // Th...
// an empty branch index. Prototype::Data(0) => Node::Empty, // something went wrong. _ => panic!("Rlp is not valid."), } } /// Encode the node into RLP. /// /// Will always return the direct node RLP even if it's 32 or more bytes. To get the ...
{ let r = Rlp::new(node_rlp); match r.prototype() { // either leaf or extension - decode first item with NibbleSlice::??? // and use is_leaf return to figure out which. // if leaf, second item is a value (is_data()) // if extension, second item is a node (...
identifier_body
node.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program 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. // Th...
} } impl<'a> From<Node<'a>> for OwnedNode { fn from(node: Node<'a>) -> Self { match node { Node::Empty => OwnedNode::Empty, Node::Leaf(k, v) => OwnedNode::Leaf(k.into(), DBValue::from_slice(v)), Node::Branch(h, k, c) => { let mut children = [HashKey::...
} OwnedNode::Branch(h, k.clone(), children) } }
random_line_split
polygonal.rs
use super::misc::isint; pub struct Polys { n: u64, step: u8 } pub fn polys(s: u8) -> Polys { Polys { n: 1, step: s - 2 } } impl Iterator for Polys { type Item = u64; fn next(&mut self) -> Option<u64> { let ans = Some(self.n); self.n += self.step as u64; ans } } pub fn tris() -> Polys { polys(3) } pub fn...
pub fn penta(x: u64) -> u64 { x * (3 * x - 1) / 2 } pub fn hexa(x: u64) -> u64 { x * (2 * x - 1) }
{ x * x }
identifier_body
polygonal.rs
use super::misc::isint; pub struct Polys { n: u64, step: u8 } pub fn polys(s: u8) -> Polys { Polys { n: 1, step: s - 2 } } impl Iterator for Polys { type Item = u64; fn next(&mut self) -> Option<u64> { let ans = Some(self.n); self.n += self.step as u64; ans } } pub fn tris() -> Polys { polys(3) } pub fn...
pub fn poly(s: u8, x: u64) -> u64 { let s = s as u64; ((s - 2) * x * x - (s - 4) * x) / 2 } pub fn tri(x: u64) -> u64 { x * (x + 1) / 2 } pub fn sqr(x: u64) -> u64 { x * x } pub fn penta(x: u64) -> u64 { x * (3 * x - 1) / 2 } pub fn hexa(x: u64) -> u64 { x * (2 * x - 1) }
pub fn ispenta(x: u64) -> bool { isint((((x * 24 + 1) as f64).sqrt() + 1.0) / 6.0) } pub fn ishexa(x: u64) -> bool { isint((((x * 8 + 1) as f64).sqrt() + 1.0) / 4.0) }
random_line_split
polygonal.rs
use super::misc::isint; pub struct Polys { n: u64, step: u8 } pub fn polys(s: u8) -> Polys { Polys { n: 1, step: s - 2 } } impl Iterator for Polys { type Item = u64; fn next(&mut self) -> Option<u64> { let ans = Some(self.n); self.n += self.step as u64; ans } } pub fn tris() -> Polys { polys(3) } pub fn...
(x: u64) -> u64 { x * x } pub fn penta(x: u64) -> u64 { x * (3 * x - 1) / 2 } pub fn hexa(x: u64) -> u64 { x * (2 * x - 1) }
sqr
identifier_name
server.rs
//! Server API //! //! # Decode PING Base Frame from client //! //! ``` //! # extern crate bytes; //! # extern crate tokio_io; //! # extern crate twist; //! # //! # use bytes::BytesMut; //! # use twist::server::{BaseFrameCodec, OpCode};
//! # //! # const PING: [u8; 6] = [0x89, 0x80, 0x00, 0x00, 0x00, 0x01]; //! # //! # fn main() { //! let ping_vec = PING.to_vec(); //! let mut eb = BytesMut::with_capacity(256); //! eb.extend(ping_vec); //! let mut fc: BaseFrameCodec = Default::default(); //! let mut encoded = BytesMut::with_capacity...
//! # use tokio_io::codec::{Decoder, Encoder};
random_line_split
moves-based-on-type-match-bindings.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn touch<A>(_a: &A) {} fn f10() { let x = Foo {f: "hi".to_owned()}; let y = match x { Foo {f} => {} //~ NOTE moved here }; touch(&x); //~ ERROR use of partially moved value: `x` } fn main() {}
struct Foo<A> { f: A } fn guard(_s: StrBuf) -> bool {fail!()}
random_line_split
moves-based-on-type-match-bindings.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
//~ NOTE moved here }; touch(&x); //~ ERROR use of partially moved value: `x` } fn main() {}
{}
conditional_block
moves-based-on-type-match-bindings.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<A>(_a: &A) {} fn f10() { let x = Foo {f: "hi".to_owned()}; let y = match x { Foo {f} => {} //~ NOTE moved here }; touch(&x); //~ ERROR use of partially moved value: `x` } fn main() {}
touch
identifier_name
moves-based-on-type-match-bindings.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn f10() { let x = Foo {f: "hi".to_owned()}; let y = match x { Foo {f} => {} //~ NOTE moved here }; touch(&x); //~ ERROR use of partially moved value: `x` } fn main() {}
{}
identifier_body
applayer.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
else { Self::ok() } } } /// Rust parser declaration #[repr(C)] pub struct RustParser { /// Parser name. pub name: *const c_char, /// Default port pub default_port: *const c_char, /// IP Protocol (core::IPPROTO_UDP, core::IPPROTO_TCP, etc.) pub ippro...
{ Self::err() }
conditional_block
applayer.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
(tx_ptr: *mut std::os::raw::c_void, tx_id: u64, has_next: bool) -> AppLayerGetTxIterTuple { AppLayerGetTxIterTuple { tx_ptr: tx_ptr, tx_id: tx_id, has_next: has_next, } } pub fn not_found() -> AppLayerGetTxIterTuple { AppLayerGetTxIterTuple { tx_ptr: std::ptr::nul...
with_values
identifier_name
applayer.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
} /// LoggerFlags tracks which loggers have already been executed. #[repr(C)] #[derive(Debug,PartialEq)] pub struct LoggerFlags { flags: u32, } impl LoggerFlags { pub fn new() -> LoggerFlags { return LoggerFlags{ flags: 0, } } pub fn get(&self) -> u32 { self.flags...
tx_ptr: std::ptr::null_mut(), tx_id: 0, has_next: false, } }
random_line_split
applayer.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
pub fn set_log_flags(&mut self, flags: u8) { self.log_flags = flags; } pub fn get_log_flags(&self) -> u8 { self.log_flags } } #[repr(C)] #[derive(Debug,PartialEq)] pub struct AppLayerTxData { /// config: log flags pub config: AppLayerTxConfig, /// logger flags for tx loggi...
{ self.log_flags |= flags; }
identifier_body
fn.rs
// One input reference with lifetime `'a` which must live // at least as long as the function. fn print_one<'a>(x: &'a i32) { println!("`print_one`: x is {}", x); } // Mutable references are possible with lifetimes as well. fn add_one<'a>(x: &'a mut i32) { *x += 1;
fn print_multi<'a, 'b>(x: &'a i32, y: &'b i32) { println!("`print_multi`: x is {}, y is {}", x, y); } // This is invalid. An `i32` would be created, a reference // would be created, then immediately the data would be // dropped leaving a reference to invalid data to be returned. // // The reason the problem is cau...
} // Multiple elements with different lifetimes. In this case, it // would be fine for both to have the same lifetime `'a`, but // in more complex cases, different lifetimes may be required.
random_line_split
fn.rs
// One input reference with lifetime `'a` which must live // at least as long as the function. fn print_one<'a>(x: &'a i32) { println!("`print_one`: x is {}", x); } // Mutable references are possible with lifetimes as well. fn add_one<'a>(x: &'a mut i32) { *x += 1; } // Multiple elements with different lifeti...
() { let x = 7; let y = 9; print_one(&x); print_multi(&x, &y); let z = pass_x(&x, &y); print_one(z); let mut t = 3; add_one(&mut t); print_one(&t); }
main
identifier_name
fn.rs
// One input reference with lifetime `'a` which must live // at least as long as the function. fn print_one<'a>(x: &'a i32) { println!("`print_one`: x is {}", x); } // Mutable references are possible with lifetimes as well. fn add_one<'a>(x: &'a mut i32)
// Multiple elements with different lifetimes. In this case, it // would be fine for both to have the same lifetime `'a`, but // in more complex cases, different lifetimes may be required. fn print_multi<'a, 'b>(x: &'a i32, y: &'b i32) { println!("`print_multi`: x is {}, y is {}", x, y); } // This is invalid. An...
{ *x += 1; }
identifier_body
normal.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 mut lnorm = LogNormal::new(10.0, 10.0); let mut rng = task_rng(); for _ in range(0, 1000) { lnorm.sample(&mut rng); lnorm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_log_normal_invalid_sd() { LogNormal::new(10.0, -1.0)...
test_log_normal
identifier_name
normal.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 ...
} StandardNormal(ziggurat( rng, true, // this is symmetric &ziggurat_tables::ZIG_NORM_X, &ziggurat_tables::ZIG_NORM_F, pdf, zero_case)) } } /// The normal distribution `N(mean, std_dev**2)`. /// /// This uses the ZIGNOR variant of the Zi...
{ ziggurat_tables::ZIG_NORM_R - x }
conditional_block
normal.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 ...
if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } } StandardNormal(ziggurat( rng, true, // this is symmetric &ziggurat_tables::ZIG_NORM_X, &ziggurat_tables::ZIG_NORM_F, pdf, zero_case)) } }...
}
random_line_split
normal.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 ...
} impl Sample<f64> for Normal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Normal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(n) = rng.gen::<StandardNormal>(); self.mean + self.std_dev * n } } ///...
{ assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); Normal { mean: mean, std_dev: std_dev } }
identifier_body
lift.rs
#![allow(dead_code, unused)] #![feature(type_ascription)] use std::collections::linked_list::LinkedList; use std::collections::vec_deque::VecDeque; use std::collections::{BinaryHeap, BTreeSet, HashSet}; pub trait Higher<A> { type B; //current type inside higher type, i.e Vec<B> type C; //swapped higher type, i...
($t:ident) => { impl<T: Clone> Monoid for $t<T> { fn id() -> Self::A { $t::new() } } } } ///Macro to implement ordered SemiGroups like BTreeSet which have a new method #[macro_export] macro_rules! monoid_ord { ($t:ident) => { impl<T: Clone + O...
} ///A macro to implement monoid for Semigroups which have a new method #[macro_export] macro_rules! monoid {
random_line_split
main.rs
extern crate clap; use std::io::prelude::*; use std::fs::File; #[derive(Debug)] /// Iterator over parts of str in delimiters struct Delimited<'a> { inner: &'a str, start_char: char, end_char: char, } impl<'a> Iterator for Delimited<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Ite...
let start = s.find('[').map(|p| p + 1).unwrap_or(s.len()); Delimited { inner: &s[start..], start_char: '[', end_char: ']', } } struct SearchWindows<'a> { current: Option<&'a str>, inner: Delimited<'a>, get_window: Box<Fn(&str) -> Option<&str>>, predicate: Box<Fn(&str...
end_char: '[', } } fn interiors(s: &str) -> Delimited {
random_line_split
main.rs
extern crate clap; use std::io::prelude::*; use std::fs::File; #[derive(Debug)] /// Iterator over parts of str in delimiters struct Delimited<'a> { inner: &'a str, start_char: char, end_char: char, } impl<'a> Iterator for Delimited<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Ite...
let end = self.inner.len(); let next_end = self.inner .find(self.end_char) .unwrap_or(end); let (delimited, rest) = self.inner.split_at(next_end); let next_start = rest.find(self.start_char) .map(|p| p + 1) .unwrap_or(end - delimited.len()); ...
{ return None; }
conditional_block
main.rs
extern crate clap; use std::io::prelude::*; use std::fs::File; #[derive(Debug)] /// Iterator over parts of str in delimiters struct Delimited<'a> { inner: &'a str, start_char: char, end_char: char, } impl<'a> Iterator for Delimited<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Ite...
fn supports_tls(candidate: &str) -> bool { anti_abbas(candidate).next().is_none() && abbas(candidate).next().is_some() } fn supports_ssl(candidate: &str) -> bool { abas(candidate).any(|aba| { anti_abas(candidate).any(|bab| is_corresponding_bab(aba, bab)) }) } fn parse_args() -> std::io::Result<B...
{ if aba.len() != 3 || candidate.len() != 3 { return false; } let mut cand_iter = candidate.chars(); let a = cand_iter.next().unwrap(); let b = cand_iter.next().unwrap(); let c = cand_iter.next().unwrap(); let mut aba_iter = aba.chars(); aba_iter.next() == Some(b) && aba_...
identifier_body
main.rs
extern crate clap; use std::io::prelude::*; use std::fs::File; #[derive(Debug)] /// Iterator over parts of str in delimiters struct Delimited<'a> { inner: &'a str, start_char: char, end_char: char, } impl<'a> Iterator for Delimited<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Ite...
<F, P>(mut delimiters: Delimited<'a>, get: F, pred: P) -> SearchWindows<'a> where F:'static + Fn(&str) -> Option<&str>, P:'static + Fn(&str) -> bool { SearchWindows { current: delimiters.next(), inner: delimiter...
new
identifier_name
mod.rs
//! let mut headers = Headers::new(); //! //! headers.set(XRequestGuid("a proper guid".to_owned())) //! } //! ``` //! //! This works well for simple "string" headers. But the header system //! actually involves 2 parts: parsing, and formatting. If you need to //! customize either part, you can do so. //! //! #...
// we JUST checked that raw.len() == 1, so raw[0] WILL exist. match match from_utf8(unsafe { &raw.get_unchecked(0)[..] }) { Ok(s) => FromStr::from_str(s).ok(), Err(_) => None }.map(|u| CrazyLength(Some(false), u)) { Some(x) => Ok(x), ...
{ return Err(::Error::Header); }
conditional_block
mod.rs
{ //! let mut headers = Headers::new(); //! //! headers.set(XRequestGuid("a proper guid".to_owned())) //! } //! ``` //! //! This works well for simple "string" headers. But the header system //! actually involves 2 parts: parsing, and formatting. If you need to //! customize either part, you can do so. //! //!...
#[inline] pub fn value<H: Header + HeaderFormat>(&self) -> Option<&'a H> { self.1.typed::<H>() } /// Get just the header value as a String. #[inline] pub fn value_string(&self) -> String { (*self.1).to_string() } } impl<'a> fmt::Display for HeaderView<'a> { fn fmt(&self...
/// Cast the value to a certain Header type.
random_line_split
mod.rs
//! let mut headers = Headers::new(); //! //! headers.set(XRequestGuid("a proper guid".to_owned())) //! } //! ``` //! //! This works well for simple "string" headers. But the header system //! actually involves 2 parts: parsing, and formatting. If you need to //! customize either part, you can do so. //! //! #...
#[test] fn test_headers_show() { let mut headers = Headers::new(); headers.set(ContentLength(15)); headers.set(Host { hostname: "foo.bar".to_owned(), port: None }); let s = headers.to_string(); // hashmap's iterators have arbitrary order, so we must sort first ...
{ let mut headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); *headers.get_mut::<ContentLength>().unwrap() = ContentLength(20); assert_eq!(*headers.get::<ContentLength>().unwrap(), ContentLength(20)); }
identifier_body
mod.rs
{ //! let mut headers = Headers::new(); //! //! headers.set(XRequestGuid("a proper guid".to_owned())) //! } //! ``` //! //! This works well for simple "string" headers. But the header system //! actually involves 2 parts: parsing, and formatting. If you need to //! customize either part, you can do so. //! //!...
() { let mut headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); *headers.get_mut::<ContentLength>().unwrap() = ContentLength(20); assert_eq!(*headers.get::<ContentLength>().unwrap(), ContentLength(20)); } #[test] fn test_headers_show() { let mut headers = He...
test_get_mutable
identifier_name
future.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { let mut f = Future::spawn(proc() "bale".to_string()); assert_eq!(f.get(), "bale".to_string()); } #[test] #[should_fail] fn test_future_panic() { let mut f = Future::spawn(proc() panic!()); let _x: String = f.get(); } #[test] fn test_sendable_future() { ...
test_spawn
identifier_name
future.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
* * The first time that the value is requested it will be retrieved by * calling the function. Note that this function is a local * function. It is not spawned into another task. */ Future {state: Pending(f)} } } impl<A:Send> Future<A> { pub fn from_receiv...
* Create a future from a function.
random_line_split
future.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} #[cfg(test)] mod test { use prelude::*; use sync::Future; use task; use comm::{channel, Sender}; #[test] fn test_from_value() { let mut f = Future::from_value("snail".to_string()); assert_eq!(f.get(), "snail".to_string()); } #[test] fn test_from_receiver() { ...
{ /*! * Create a future from a unique closure. * * The closure will be run in a new task and its result used as the * value of the future. */ let (tx, rx) = channel(); spawn(proc() { // Don't panic if the other end has hung up ...
identifier_body
path.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unl...
None } } None => None, }, Err(_) => None, }; let interpreter_paths: Vec<PathBuf> = match my_interpreter_dep_ident { // We've found the specific release that our Supervisor was built with. Get its path // metadata. ...
let metafile = p.join("DEPS"); if metafile.is_file() { interpreter_dep_from_metafile(metafile) } else {
random_line_split
path.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unl...
(metafile: PathBuf) -> Option<PackageIdent> { let f = match File::open(metafile) { Ok(f) => f, Err(_) => return None, }; let reader = BufReader::new(f); for line in reader.lines() { let line = match line { Ok(l) => l, Err(_) => return None, }; ...
interpreter_dep_from_metafile
identifier_name
path.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unl...
// If we're not running out of a package, then see if any package of the interpreter is // installed. None => { let ident = PackageIdent::from_str(INTERPRETER_IDENT)?; match PackageInstall::load(&ident, None) { // We found a version of the interpreter. Ge...
{ let pkg_install = PackageInstall::load(&ident, None)?; pkg_install.paths()? }
conditional_block
path.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unl...
/// Returns a `PackageIdent` for a interpreter package, assuming it exists in the provided metafile. fn interpreter_dep_from_metafile(metafile: PathBuf) -> Option<PackageIdent> { let f = match File::open(metafile) { Ok(f) => f, Err(_) => return None, }; let reader = BufReader::new(f); ...
{ let mut paths = interpreter_paths()?; path_entries.append(&mut paths); if let Some(val) = env::var_os("PATH") { let mut os_paths = env::split_paths(&val).collect(); path_entries.append(&mut os_paths); } let joined = env::join_paths(path_entries)?; let path_str = joined ...
identifier_body
trait_objects.rs
trait Foo { fn method(&self) -> String; } impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } impl Foo for String { fn method(&self) -> String { format!("String: {}", *self) } } // Static dispatch (No overhead abstraction,'monomorphization,' i.e., rust optimizer creates sep...
// One cannot use trait objects for things that use Self or have type parameters, e.g., // let this_will_not_work = &v as &Clone // Because it is not "Object safe."
{ let x = 5u8; println!("This uses dynamic dispatch (type casting): {:?}", do_something(&x as &Foo)); println!("And so does this (coercion): {:?}", do_something(&x)); }
identifier_body
trait_objects.rs
trait Foo { fn method(&self) -> String; }
impl Foo for String { fn method(&self) -> String { format!("String: {}", *self) } } // Static dispatch (No overhead abstraction,'monomorphization,' i.e., rust optimizer creates seperate functions for u8 and String fn do_something(x: &Foo) { x.method(); } /* fn main() { let x = 2u8; let y = "Bonjour...
impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } }
random_line_split
trait_objects.rs
trait Foo { fn method(&self) -> String; } impl Foo for u8 { fn
(&self) -> String { format!("u8: {}", *self) } } impl Foo for String { fn method(&self) -> String { format!("String: {}", *self) } } // Static dispatch (No overhead abstraction,'monomorphization,' i.e., rust optimizer creates seperate functions for u8 and String fn do_something(x: &Foo) { x.method(); } /*...
method
identifier_name
mod.rs
use futures::Future; use hyper::service::service_fn_ok; use hyper::{Body, Request, Response}; use hyper::{Client, Server, Uri}; use std::str; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::runtime::Runtime; // Return the received request in the response body for testing purposes. pub fn echo_request(reques...
(request: Request<Body>) -> Response<Body> { let client = Client::new(); let work = client.request(request).and_then(Ok); let mut rt = Runtime::new().unwrap(); rt.block_on(work).unwrap() } // Returns a local port number that has not been used yet in parallel test // threads. pub fn get_free_port() -> u...
client_request
identifier_name
mod.rs
use futures::Future; use hyper::service::service_fn_ok; use hyper::{Body, Request, Response}; use hyper::{Client, Server, Uri}; use std::str; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::runtime::Runtime; // Return the received request in the response body for testing purposes. pub fn echo_request(reques...
// this helper function. #[allow(dead_code)] pub fn client_get(url: Uri) -> Response<Body> { let client = Client::new(); let work = client.get(url).and_then(Ok); let mut rt = Runtime::new().unwrap(); rt.block_on(work).unwrap() } #[allow(dead_code)] pub fn client_post(url: Uri, body: &'static str) -> R...
// Since it so complicated to make a client request with a Hyper runtime we have
random_line_split
mod.rs
use futures::Future; use hyper::service::service_fn_ok; use hyper::{Body, Request, Response}; use hyper::{Client, Server, Uri}; use std::str; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::runtime::Runtime; // Return the received request in the response body for testing purposes. pub fn echo_request(reques...
#[allow(dead_code)] pub fn client_post(url: Uri, body: &'static str) -> Response<Body> { let client = Client::new(); let req = Request::builder() .method("POST") .uri(url) .body(Body::from(body)) .unwrap(); let work = client.request(req).and_then(Ok); let mut rt = Runtime...
{ let client = Client::new(); let work = client.get(url).and_then(Ok); let mut rt = Runtime::new().unwrap(); rt.block_on(work).unwrap() }
identifier_body
boron.rs
extern crate hyper; extern crate boron; use std::thread; use std::sync::{Once, ONCE_INIT}; use std::io::{Read, Write}; use hyper::status::StatusCode; use hyper::client::Client; use hyper::client::response::Response as HyperResponse; use boron::server::Boron; use boron::request::Request; use boron::response::Response; ...
res.send(b"I was triggered") }); app.listen("0.0.0.0:4040"); }); loop { if ctx.req_client.get("http://0.0.0.0:4040").send().is_ok() { break; } } }); ctx } ...
{ let ctx = TestContext { req_client: Client::new() }; TEST_INIT.call_once(|| { let _ = thread::spawn(move || { let mut app = Boron::new(); app.get("/", |req: &Request, res: Response| { res.send(b"Hello World!") ...
identifier_body
boron.rs
extern crate hyper; extern crate boron; use std::thread; use std::sync::{Once, ONCE_INIT}; use std::io::{Read, Write}; use hyper::status::StatusCode; use hyper::client::Client; use hyper::client::response::Response as HyperResponse; use boron::server::Boron; use boron::request::Request; use boron::response::Response; ...
} }); ctx } fn request(&self, url: &str) -> HyperResponse { self.req_client.get(url).send().unwrap() } fn body_from_response(&self, res: &mut HyperResponse) -> String { let mut body = String::new(); let _ = res.read_to_string(&mut body); bod...
{ break; }
conditional_block
boron.rs
extern crate hyper; extern crate boron; use std::thread; use std::sync::{Once, ONCE_INIT}; use std::io::{Read, Write}; use hyper::status::StatusCode; use hyper::client::Client; use hyper::client::response::Response as HyperResponse; use boron::server::Boron; use boron::request::Request; use boron::response::Response; ...
() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/throw/error"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::InternalServerError); assert_eq!(body, "Boom!"); } #[test] fn test_pattern_match() { let ctx = TestContext::new(); ...
test_res_methods
identifier_name
boron.rs
extern crate hyper; extern crate boron; use std::thread; use std::sync::{Once, ONCE_INIT}; use std::io::{Read, Write}; use hyper::status::StatusCode; use hyper::client::Client; use hyper::client::response::Response as HyperResponse; use boron::server::Boron; use boron::request::Request; use boron::response::Response; ...
} #[test] fn test_hello_world() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "Hello World!"); } #[test] fn test_some_path() { let ctx = TestContext::new()...
body }
random_line_split
context.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 animation::Animation; use app_units::Au; use dom::OpaqueNode; use error_reporting::ParseErrorReporter; use euc...
use selector_impl::SelectorImplExt; use selector_matching::Stylist; use std::cell::RefCell; use std::collections::HashMap; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex, RwLock}; pub struct SharedStyleContext<Impl: SelectorImplExt> { /// The current viewport size. pub viewport_size: Size2D<Au>, ...
use properties::ComputedValues;
random_line_split
context.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 animation::Animation; use app_units::Au; use dom::OpaqueNode; use error_reporting::ParseErrorReporter; use euc...
<C: ComputedValues> { pub applicable_declarations_cache: RefCell<ApplicableDeclarationsCache<C>>, pub style_sharing_candidate_cache: RefCell<StyleSharingCandidateCache<C>>, } pub trait StyleContext<'a, Impl: SelectorImplExt> { fn shared_context(&self) -> &'a SharedStyleContext<Impl>; fn local_context(&...
LocalStyleContext
identifier_name
lib.rs
/// Solutions to the [Cryptopals Challenges](https://cryptopals.com) /// /// Written whilst leading the *A*spiring *R*ustacean *S*ocial *E*ducation group within LinkedIn pub mod encode; pub mod encrypt; pub mod stat; pub mod transform; pub mod xor_cipher { use super::stat::{Histogram, HistogramError}; use supe...
Err(e) => Err(e), } } Err(_) => Err(HistogramError::HistogramMismatch), } } }
{ let pct_non_alpha = (b_len - s.len()) as f64 / b_len as f64; Ok(raw_score * pct_non_alpha) }
conditional_block
lib.rs
/// Solutions to the [Cryptopals Challenges](https://cryptopals.com) /// /// Written whilst leading the *A*spiring *R*ustacean *S*ocial *E*ducation group within LinkedIn pub mod encode; pub mod encrypt; pub mod stat; pub mod transform; pub mod xor_cipher { use super::stat::{Histogram, HistogramError}; use supe...
if s.len() == 0 { return Err(HistogramError::HistogramMismatch); } let mut byte_distr: Histogram<char> = s.chars().into(); byte_distr.normalize(); match byte_distr.chisq(language) { Ok(raw_score) => ...
.chars() .filter(|&c| c.is_alphabetic()) .collect::<String>();
random_line_split
lib.rs
/// Solutions to the [Cryptopals Challenges](https://cryptopals.com) /// /// Written whilst leading the *A*spiring *R*ustacean *S*ocial *E*ducation group within LinkedIn pub mod encode; pub mod encrypt; pub mod stat; pub mod transform; pub mod xor_cipher { use super::stat::{Histogram, HistogramError}; use supe...
.chars() .filter(|&c| c.is_alphabetic()) .collect::<String>(); if s.len() == 0 { return Err(HistogramError::HistogramMismatch); } let mut byte_distr: Histogram<char> = s.chars().into(); ...
{ let bytes = ciphertext .try_fixed_xor(vec![test_byte; ciphertext.len()].as_slice()) .unwrap(); let b_len = bytes.len(); match String::from_utf8(bytes) { Ok(s) => { if s.len() != b_len { return Err(HistogramError::Histogra...
identifier_body
lib.rs
/// Solutions to the [Cryptopals Challenges](https://cryptopals.com) /// /// Written whilst leading the *A*spiring *R*ustacean *S*ocial *E*ducation group within LinkedIn pub mod encode; pub mod encrypt; pub mod stat; pub mod transform; pub mod xor_cipher { use super::stat::{Histogram, HistogramError}; use supe...
( test_byte: u8, ciphertext: &[u8], language: &Histogram<char>, ) -> Result<f64, HistogramError> { let bytes = ciphertext .try_fixed_xor(vec![test_byte; ciphertext.len()].as_slice()) .unwrap(); let b_len = bytes.len(); match String::from_utf8(by...
score_byte_decode
identifier_name
mod.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...
pub mod params; pub mod spec; pub mod seal; pub mod engine; pub mod state; pub mod ethash; pub mod validator_set; pub mod basic_authority; pub mod authority_round; pub mod tendermint; pub mod null_engine; pub use self::account::Account; pub use self::builtin::{Builtin, Pricing, Linear}; pub use self::genesis::Genesis;...
random_line_split
dictionary.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 ...
(obj: CFDictionaryRef) -> CFDictionary { CFDictionary { obj: obj, } } #[inline] fn type_id(_: Option<CFDictionary>) -> CFTypeID { unsafe { CFDictionaryGetTypeID() } } } impl CFDictionary { pub fn from_CFType_pairs(pairs: &[(CFType, CFType)]) ...
wrap_under_create_rule
identifier_name
dictionary.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 ...
/// An immutable dictionary of key-value pairs. /// /// FIXME(pcwalton): Should be a newtype struct, but that fails due to a Rust compiler bug. pub struct CFDictionary { priv obj: CFDictionaryRef, } impl Drop for CFDictionary { fn drop(&mut self) { unsafe { CFRelease(self.as_CFTypeRef()) ...
struct __CFDictionary; pub type CFDictionaryRef = *__CFDictionary;
random_line_split
dictionary.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 ...
else { None } } } #[inline] pub fn get(&self, key: *c_void) -> *c_void { let value = self.find(key); if value.is_none() { fail!("No entry found for key: {:?}", key); } value.unwrap() } /// A convenience function to re...
{ Some(value) }
conditional_block
dictionary.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 ...
} impl TCFType<CFDictionaryRef> for CFDictionary { fn as_concrete_TypeRef(&self) -> CFDictionaryRef { self.obj } unsafe fn wrap_under_create_rule(obj: CFDictionaryRef) -> CFDictionary { CFDictionary { obj: obj, } } #[inline] fn type_id(_: Option<CFDictiona...
{ unsafe { CFRelease(self.as_CFTypeRef()) } }
identifier_body
associated-types-sugar-path.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let z: usize = bar(2, 4); }
main
identifier_name
associated-types-sugar-path.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub fn main() { let z: usize = bar(2, 4); }
let x: T::A = panic!(); }
random_line_split
associated-types-sugar-path.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} // Using a type via a function. pub fn bar<T: Foo>(a: T, x: T::A) -> T::A { let _: T::A = a.boo(); x } // Using a type via an impl. trait C { fn f(); fn g(&self) { } } struct B<X>(X); impl<T: Foo> C for B<T> { fn f() { let x: T::A = panic!(); } } pub fn main() { let z: usize = ...
{ 5 }
identifier_body
coord_transform.rs
use crate::coordinates::{ConversionTo, CoordinateSystem, Point}; use crate::tensors::Vector; use crate::typenum::consts::U3; use generic_array::arr; struct Cartesian; struct Spherical; impl CoordinateSystem for Cartesian { type Dimension = U3; } impl CoordinateSystem for Spherical { type Dimension = U3; } i...
assert!((v2[1] + 0.5).abs() < 0.00001); assert_eq!(v2[2], 0.0); }
let v = Vector::<Cartesian>::new(p, arr![f64; 0.0, 0.0, 1.0]); let v2: Vector<Spherical> = v.convert(); assert!((v2[0] - 0.5_f64.sqrt()).abs() < 0.00001);
random_line_split
coord_transform.rs
use crate::coordinates::{ConversionTo, CoordinateSystem, Point}; use crate::tensors::Vector; use crate::typenum::consts::U3; use generic_array::arr; struct Cartesian; struct
; impl CoordinateSystem for Cartesian { type Dimension = U3; } impl CoordinateSystem for Spherical { type Dimension = U3; } impl ConversionTo<Spherical> for Cartesian { fn convert_point(p: &Point<Cartesian>) -> Point<Spherical> { let r = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt(); l...
Spherical
identifier_name
quasiquote.rs
// Copyright 2015 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to...
else { None } } fn unquote(&mut self, delim: rust::DelimToken) { let pound_idx = self.current_idx; let mut opened_delims = 1isize; self.bump(2); while!self.at_end() && self.still_in_quote(delim, opened_delims) { opened_delims = opened_delims + self.count_delim(delim);...
{ match self.tokens[self.current_idx + 1].tok { rtok::OpenDelim(d@rust::DelimToken::Paren) | rtok::OpenDelim(d@rust::DelimToken::Brace) => Some(d), _ => None } }
conditional_block
quasiquote.rs
// Copyright 2015 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to...
(&self) -> Option<rust::DelimToken> { if self.current_idx + 1 < self.tokens.len() && self.tokens[self.current_idx].tok == rtok::Pound { match self.tokens[self.current_idx + 1].tok { rtok::OpenDelim(d@rust::DelimToken::Paren) | rtok::OpenDelim(d@rust::DelimToken::Brace) => Some(d), ...
peek_unquote
identifier_name
quasiquote.rs
// Copyright 2015 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to...
fn still_in_quote(&self, delim: rust::DelimToken, opened_delims: isize) -> bool { opened_delims!= 1 || self.token().tok!= rtok::CloseDelim(delim) } fn count_delim(&self, delim: rust::DelimToken) -> isize { match self.token().tok { rtok::CloseDelim(d) if d == delim => -1, rtok::Ope...
{ let pound_idx = self.current_idx; let mut opened_delims = 1isize; self.bump(2); while !self.at_end() && self.still_in_quote(delim, opened_delims) { opened_delims = opened_delims + self.count_delim(delim); self.bump(1); } if self.at_end() || opened_delims != 1 { self...
identifier_body
quasiquote.rs
// Copyright 2015 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at
// Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License...
// http://www.apache.org/licenses/LICENSE-2.0
random_line_split
box.rs
use std::mem; #[allow(dead_code)] struct Point { x: f64, y: f64, } #[allow(dead_code)] struct Rectangle { p1: Point, p2: Point, } fn origin() -> Point { Point { x: 0.0, y: 0.0 } } fn boxed_origin() -> Box<Point>
fn main() { // (all the type annotations are superfluous) // Stack allocated variables let point: Point = origin(); let rectangle: Rectangle = Rectangle { p1: origin(), p2: Point { x: 3.0, y: 4.0 } }; // Heap allocated rectangle let boxed_rectangle: Box<Rectangle> = box Re...
{ // Allocate this point in the heap, and return a pointer to it box Point { x: 0.0, y: 0.0 } }
identifier_body
box.rs
use std::mem; #[allow(dead_code)] struct Point { x: f64, y: f64, } #[allow(dead_code)] struct Rectangle { p1: Point, p2: Point, } fn origin() -> Point { Point { x: 0.0, y: 0.0 } } fn
() -> Box<Point> { // Allocate this point in the heap, and return a pointer to it box Point { x: 0.0, y: 0.0 } } fn main() { // (all the type annotations are superfluous) // Stack allocated variables let point: Point = origin(); let rectangle: Rectangle = Rectangle { p1: origin(), ...
boxed_origin
identifier_name
box.rs
use std::mem; #[allow(dead_code)] struct Point { x: f64, y: f64, } #[allow(dead_code)] struct Rectangle { p1: Point, p2: Point, } fn origin() -> Point { Point { x: 0.0, y: 0.0 } } fn boxed_origin() -> Box<Point> { // Allocate this point in the heap, and return a pointer to it box Point {...
p2: Point { x: 3.0, y: 4.0 } }; // Heap allocated rectangle let boxed_rectangle: Box<Rectangle> = box Rectangle { p1: origin(), p2: origin() }; // The output of functions can be boxed let boxed_point: Box<Point> = box origin(); // Double indirection let box_in_...
p1: origin(),
random_line_split
issue-16098.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { println!("Problem 1: {}", prob1!(1000)); }
main
identifier_name
issue-16098.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ println!("Problem 1: {}", prob1!(1000)); }
identifier_body
issue-16098.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
0 }; ($n:expr) => { if ($n % 3 == 0) || ($n % 5 == 0) { $n + prob1!($n - 1); //~ ERROR recursion limit reached while expanding the macro `prob1` } else { prob1!($n - 1); } }; } fn main() { println!("Problem 1: {}", prob1!(1000)); }
// except according to those terms. macro_rules! prob1 { (0) => {
random_line_split
rpcndr.rs
// Copyright © 2016 winapi-rs developers // 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. // All files in the project carrying such notice may not be copied, modi...
pub type boolean = c_uchar; pub type hyper = __int64; pub type MIDL_uhyper = __uint64; // TODO Finish the rest
pub type byte = c_uchar; pub type cs_byte = byte;
random_line_split
allocator.rs
#[cfg(target_env = "sgx")] use alloc::alloc::{self, Layout}; #[cfg(not(target_env = "sgx"))] use std::alloc::{self, Layout}; use errors::*; const DEFAULT_ALIGN_BYTES: usize = 4; #[derive(PartialEq, Eq)] pub struct Allocation { layout: Layout, ptr: *mut u8, } impl Allocation { /// Allocates a chunk of memory o...
(&self) -> usize { self.layout.size() } /// Returns the byte alignment of the Allocation. pub fn align(&self) -> usize { self.layout.align() } } impl Drop for Allocation { fn drop(&mut self) { unsafe { alloc::dealloc(self.ptr, self.layout.clone()); } } }
size
identifier_name
allocator.rs
#[cfg(target_env = "sgx")] use alloc::alloc::{self, Layout}; #[cfg(not(target_env = "sgx"))] use std::alloc::{self, Layout}; use errors::*; const DEFAULT_ALIGN_BYTES: usize = 4; #[derive(PartialEq, Eq)] pub struct Allocation { layout: Layout, ptr: *mut u8, } impl Allocation { /// Allocates a chunk of memory o...
if ptr.is_null() { alloc::handle_alloc_error(layout); } Ok(Self { ptr: ptr, layout: layout, }) } pub fn as_mut_ptr(&self) -> *mut u8 { self.ptr } /// Returns the size of the Allocation in bytes. pub fn size(&self) -> usize { self.layout.size() } /// Returns the...
let alignment = align.unwrap_or(DEFAULT_ALIGN_BYTES); let layout = Layout::from_size_align(size, alignment)?; let ptr = unsafe { alloc::alloc(layout.clone()) };
random_line_split
allocator.rs
#[cfg(target_env = "sgx")] use alloc::alloc::{self, Layout}; #[cfg(not(target_env = "sgx"))] use std::alloc::{self, Layout}; use errors::*; const DEFAULT_ALIGN_BYTES: usize = 4; #[derive(PartialEq, Eq)] pub struct Allocation { layout: Layout, ptr: *mut u8, } impl Allocation { /// Allocates a chunk of memory o...
/// Returns the byte alignment of the Allocation. pub fn align(&self) -> usize { self.layout.align() } } impl Drop for Allocation { fn drop(&mut self) { unsafe { alloc::dealloc(self.ptr, self.layout.clone()); } } }
{ self.layout.size() }
identifier_body
allocator.rs
#[cfg(target_env = "sgx")] use alloc::alloc::{self, Layout}; #[cfg(not(target_env = "sgx"))] use std::alloc::{self, Layout}; use errors::*; const DEFAULT_ALIGN_BYTES: usize = 4; #[derive(PartialEq, Eq)] pub struct Allocation { layout: Layout, ptr: *mut u8, } impl Allocation { /// Allocates a chunk of memory o...
Ok(Self { ptr: ptr, layout: layout, }) } pub fn as_mut_ptr(&self) -> *mut u8 { self.ptr } /// Returns the size of the Allocation in bytes. pub fn size(&self) -> usize { self.layout.size() } /// Returns the byte alignment of the Allocation. pub fn align(&self) -> usize { ...
{ alloc::handle_alloc_error(layout); }
conditional_block
graphic.rs
use cursive::theme::{BaseColor, Color, ColorStyle}; use cursive::traits::*; use cursive::vec::Vec2; use cursive::Printer; use tutor::{Label, LabeledChord, PrevCharStatus}; pub struct Graphic { switches: Vec<Switch>, } #[derive(Clone, Copy)] pub enum ChordType { Next, Error, Backspace, Persistent,...
fn error_style() -> ColorStyle { ColorStyle::secondary() } fn default_style() -> ColorStyle { ColorStyle::title_secondary() } fn draw(&self, printer: &Printer) { let (x, y) = self.position; let row2_left = format!("│{}", self.label()); let (left, right) = ...
{ // TODO the background color is hardcoded, instead of inheriting from // the theme! ColorStyle::new( Color::Dark(BaseColor::Yellow), Color::Dark(BaseColor::Black), ) }
identifier_body
graphic.rs
use cursive::theme::{BaseColor, Color, ColorStyle}; use cursive::traits::*; use cursive::vec::Vec2; use cursive::Printer; use tutor::{Label, LabeledChord, PrevCharStatus}; pub struct Graphic { switches: Vec<Switch>, } #[derive(Clone, Copy)] pub enum ChordType { Next, Error, Backspace, Persistent,...
> { vec![ (0, 2), (6, 1), (12, 1), (18, 1), (54, 1), (60, 1), (66, 1), (72, 2), (0, 5), (6, 4), (12, 4), (18, 4), (54, 4), (60, 4), (66, 4), (72, 5), (60, 7), (12, 7), ...
> Vec<(usize, usize)
identifier_name