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 |
|---|---|---|---|---|
mod.rs | //! Simulates a chip8 cpu and provides a thread-safe interface to control execution and state.
mod threaded;
#[cfg(test)]
mod tests;
use std::sync::{Arc, RwLock};
use types::*;
use Chip8;
use config::Config;
use instruction::{self, Dest, Operation, Src};
pub use self::threaded::SimulatorTask;
use state::RandomBytes;... |
fn audio(&self) -> Chip8Result<Audio> {
self.core.audio()
}
}
impl Simulator {
/// Returns a new Simulator.
pub fn new(config: &Config, rand_iterator: Option<RandomBytes>) -> Chip8Result<Simulator> {
let core: Chip8 = Chip8::new(config, rand_iterator);
let iset = instruction::S... | {
self.core.buzzer()
} | identifier_body |
mod.rs | //! Simulates a chip8 cpu and provides a thread-safe interface to control execution and state.
mod threaded;
#[cfg(test)]
mod tests;
use std::sync::{Arc, RwLock};
use types::*;
use Chip8;
use config::Config;
use instruction::{self, Dest, Operation, Src};
pub use self::threaded::SimulatorTask;
use state::RandomBytes;... |
Ok(())
}
fn load(&mut self, src: Src) -> Chip8Result<usize> {
self.core.load(src)
}
fn store(&mut self, dest: Dest, value: usize) -> Chip8Result<()> {
self.core.store(dest, value)
}
fn step(&mut self) -> Chip8Result<()> {
let instruction = try!(self.decode_at_a... | {
self.core.st -= 1;
} | conditional_block |
mod.rs | //! Simulates a chip8 cpu and provides a thread-safe interface to control execution and state.
mod threaded;
#[cfg(test)]
mod tests;
use std::sync::{Arc, RwLock};
use types::*;
use Chip8;
use config::Config;
use instruction::{self, Dest, Operation, Src};
pub use self::threaded::SimulatorTask;
use state::RandomBytes;... | (&mut self) -> Chip8Result<Arc<RwLock<Buzzer>>> {
Ok(self.core.buzzer_lock())
}
/// Returns a copy of the lock for the audio.
fn audio_lock(&mut self) -> Chip8Result<Arc<RwLock<Audio>>> {
Ok(self.core.audio_lock())
}
}
| buzzer_lock | identifier_name |
mod.rs | //! Simulates a chip8 cpu and provides a thread-safe interface to control execution and state.
mod threaded;
#[cfg(test)]
mod tests;
use std::sync::{Arc, RwLock};
use types::*;
use Chip8;
use config::Config;
use instruction::{self, Dest, Operation, Src};
pub use self::threaded::SimulatorTask;
use state::RandomBytes;... | pub fn new(config: &Config, rand_iterator: Option<RandomBytes>) -> Chip8Result<Simulator> {
let core: Chip8 = Chip8::new(config, rand_iterator);
let iset = instruction::Set::new(config);
let mut s = Simulator {
core: core,
instruction_set: iset,
};
try... | /// Returns a new Simulator. | random_line_split |
decoder.rs | //! Parse and decode COSE signatures.
use cbor::CborType;
use cbor::decoder::decode;
use {CoseError, SignatureAlgorithm};
use util::get_sig_struct_bytes;
use std::collections::BTreeMap;
pub const COSE_SIGN_TAG: u64 = 98;
/// The result of `decode_signature` holding a decoded COSE signature.
#[derive(Debug)]
pub stru... | }
/// Decode COSE signature bytes and return a vector of `CoseSignature`.
///
///```rust,ignore
/// COSE_Sign = [
/// Headers,
/// payload : bstr / nil,
/// signatures : [+ COSE_Signature]
/// ]
///
/// Headers = (
/// protected : empty_or_serialized_map,
/// unprotected : header_map
/// )
///```
p... | random_line_split | |
decoder.rs | //! Parse and decode COSE signatures.
use cbor::CborType;
use cbor::decoder::decode;
use {CoseError, SignatureAlgorithm};
use util::get_sig_struct_bytes;
use std::collections::BTreeMap;
pub const COSE_SIGN_TAG: u64 = 98;
/// The result of `decode_signature` holding a decoded COSE signature.
#[derive(Debug)]
pub stru... | (map: &CborType) -> Result<(), CoseError> {
let unpacked = unpack!(Map, map);
if!unpacked.is_empty() {
return Err(CoseError::MalformedInput);
}
Ok(())
}
// This syntax is a little unintuitive. Taken together, the two previous definitions essentially
// mean:
//
// COSE_Sign = [
// protected... | ensure_empty_map | identifier_name |
decoder.rs | //! Parse and decode COSE signatures.
use cbor::CborType;
use cbor::decoder::decode;
use {CoseError, SignatureAlgorithm};
use util::get_sig_struct_bytes;
use std::collections::BTreeMap;
pub const COSE_SIGN_TAG: u64 = 98;
/// The result of `decode_signature` holding a decoded COSE signature.
#[derive(Debug)]
pub stru... |
/// Ensure that the referenced `CborType` is an empty map.
fn ensure_empty_map(map: &CborType) -> Result<(), CoseError> {
let unpacked = unpack!(Map, map);
if!unpacked.is_empty() {
return Err(CoseError::MalformedInput);
}
Ok(())
}
// This syntax is a little unintuitive. Taken together, the tw... | {
match map.get(key) {
Some(x) => Ok(x.clone()),
_ => Err(CoseError::MissingHeader),
}
} | identifier_body |
decoder.rs | //! Parse and decode COSE signatures.
use cbor::CborType;
use cbor::decoder::decode;
use {CoseError, SignatureAlgorithm};
use util::get_sig_struct_bytes;
use std::collections::BTreeMap;
pub const COSE_SIGN_TAG: u64 = 98;
/// The result of `decode_signature` holding a decoded COSE signature.
#[derive(Debug)]
pub stru... |
let mut result = Vec::new();
for cose_signature in signatures {
// cose_sign_array[0] holds the protected body header.
let signature = decode_signature_struct(cose_signature, payload, &cose_sign_array[0])?;
result.push(signature);
}
Ok(result)
}
| {
return Err(CoseError::MalformedInput);
} | conditional_block |
demo.rs | extern crate nest;
use nest::*;
use std::f32::consts::PI;
use std::time::Instant;
fn | () {
let mut app = Window::new("Demo", 640, 480).expect("error: failed to open window");
let start = Instant::now();
// Load the petal texture.
let petal_texture = app.load_image("examples/petal.png").unwrap();
// Create an image rectangle from the petal texture with a width of 0.4 and proportiona... | main | identifier_name |
demo.rs | extern crate nest;
use nest::*;
use std::f32::consts::PI;
use std::time::Instant;
fn main() {
let mut app = Window::new("Demo", 640, 480).expect("error: failed to open window");
let start = Instant::now();
// Load the petal texture.
let petal_texture = app.load_image("examples/petal.png").unwrap();
... |
// Print "Space!" if they hit space.
Event::KeyboardInput(KeyState::Pressed, Some(Key::Space)) => println!("Space!"),
_ => {}
}
}
// Draw the flower rotating at 1 rad/sec.
app.draw(flower.rotate(start.elapsed().to_secs()));
}
}
| {
return
} | conditional_block |
demo.rs | extern crate nest;
use nest::*;
use std::f32::consts::PI;
use std::time::Instant;
fn main() | Event::Closed | Event::KeyboardInput(KeyState::Pressed, Some(Key::Escape)) => {
return
}
// Print "Space!" if they hit space.
Event::KeyboardInput(KeyState::Pressed, Some(Key::Space)) => println!("Space!"),
_ => {}
... | {
let mut app = Window::new("Demo", 640, 480).expect("error: failed to open window");
let start = Instant::now();
// Load the petal texture.
let petal_texture = app.load_image("examples/petal.png").unwrap();
// Create an image rectangle from the petal texture with a width of 0.4 and proportional h... | identifier_body |
demo.rs | extern crate nest;
use nest::*;
use std::f32::consts::PI;
use std::time::Instant;
fn main() {
let mut app = Window::new("Demo", 640, 480).expect("error: failed to open window");
let start = Instant::now();
// Load the petal texture.
let petal_texture = app.load_image("examples/petal.png").unwrap();
... | // Print "Space!" if they hit space.
Event::KeyboardInput(KeyState::Pressed, Some(Key::Space)) => println!("Space!"),
_ => {}
}
}
// Draw the flower rotating at 1 rad/sec.
app.draw(flower.rotate(start.elapsed().to_secs()));
}
} | match event {
// Close if they close the window or hit escape.
Event::Closed | Event::KeyboardInput(KeyState::Pressed, Some(Key::Escape)) => {
return
} | random_line_split |
delete.rs | use bit_set::BitSet;
use directory::WritePtr;
use std::io::Write;
use std::io;
use directory::ReadOnlySource;
use DocId;
use common::HasLen;
/// Write a delete `BitSet`
///
/// where `delete_bitset` is the set of deleted `DocId`.
pub fn write_delete_bitset(delete_bitset: &BitSet, writer: &mut WritePtr) -> io::Result<(... |
}
if max_doc % 8 > 0 {
writer.write_all(&[byte])?;
}
writer.flush()
}
/// Set of deleted `DocId`s.
#[derive(Clone)]
pub struct DeleteBitSet {
data: ReadOnlySource,
len: usize,
}
impl DeleteBitSet {
/// Opens a delete bitset given its data source.
pub fn open(data: ReadOnlySou... | {
shift += 1;
} | conditional_block |
delete.rs | use bit_set::BitSet;
use directory::WritePtr;
use std::io::Write;
use std::io;
use directory::ReadOnlySource;
use DocId;
use common::HasLen;
/// Write a delete `BitSet`
///
/// where `delete_bitset` is the set of deleted `DocId`.
pub fn write_delete_bitset(delete_bitset: &BitSet, writer: &mut WritePtr) -> io::Result<(... |
/// Returns an empty delete bit set.
pub fn empty() -> DeleteBitSet {
DeleteBitSet {
data: ReadOnlySource::empty(),
len: 0,
}
}
/// Returns true iff the segment has some deleted documents.
pub fn has_deletes(&self) -> bool {
self.len() > 0
}
... | {
let num_deleted: usize = data.as_slice()
.iter()
.map(|b| b.count_ones() as usize)
.sum();
DeleteBitSet {
data: data,
len: num_deleted,
}
} | identifier_body |
delete.rs | use bit_set::BitSet;
use directory::WritePtr;
use std::io::Write;
use std::io;
use directory::ReadOnlySource;
use DocId;
use common::HasLen;
/// Write a delete `BitSet`
///
/// where `delete_bitset` is the set of deleted `DocId`.
pub fn write_delete_bitset(delete_bitset: &BitSet, writer: &mut WritePtr) -> io::Result<(... | data: data,
len: num_deleted,
}
}
/// Returns an empty delete bit set.
pub fn empty() -> DeleteBitSet {
DeleteBitSet {
data: ReadOnlySource::empty(),
len: 0,
}
}
/// Returns true iff the segment has some deleted documents.
... | DeleteBitSet { | random_line_split |
delete.rs | use bit_set::BitSet;
use directory::WritePtr;
use std::io::Write;
use std::io;
use directory::ReadOnlySource;
use DocId;
use common::HasLen;
/// Write a delete `BitSet`
///
/// where `delete_bitset` is the set of deleted `DocId`.
pub fn write_delete_bitset(delete_bitset: &BitSet, writer: &mut WritePtr) -> io::Result<(... | (bitset: &BitSet) {
let test_path = PathBuf::from("test");
let mut directory = RAMDirectory::create();
{
let mut writer = directory.open_write(&*test_path).unwrap();
write_delete_bitset(bitset, &mut writer).unwrap();
}
{
let source = directory.... | test_delete_bitset_helper | identifier_name |
check_static_recursion.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 ... | (&mut self, it: &Item) {
if self.idstack.iter().any(|x| x == &(it.id)) {
self.sess.span_err(self.root_it.span, "recursive constant");
return;
}
self.idstack.push(it.id);
visit::walk_item(self, it);
self.idstack.pop();
}
fn visit_expr(&mut self, e:... | visit_item | identifier_name |
check_static_recursion.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 ... | use syntax::ast::{Crate, Expr, ExprPath, Item, ItemStatic, NodeId};
use syntax::{ast_util, ast_map};
use syntax::visit::Visitor;
use syntax::visit;
struct CheckCrateVisitor<'a, 'ast: 'a> {
sess: &'a Session,
def_map: &'a resolve::DefMap,
ast_map: &'a ast_map::Map<'ast>
}
impl<'v, 'a, 'ast> Visitor<'v> for... | use driver::session::Session;
use middle::resolve;
use middle::def::DefStatic;
| random_line_split |
htmlappletelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLAppletElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLAppletElementD... | (&mut self, _name: DOMString) -> ErrorResult {
Ok(())
}
pub fn Object(&self) -> DOMString {
~""
}
pub fn SetObject(&mut self, _object: DOMString) -> ErrorResult {
Ok(())
}
pub fn Vspace(&self) -> u32 {
0
}
pub fn SetVspace(&mut self, _vspace: u32) -> E... | SetName | identifier_name |
htmlappletelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLAppletElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLAppletElementD... |
pub fn SetCodeBase(&self, _code_base: DOMString) -> ErrorResult {
Ok(())
}
pub fn Height(&self) -> DOMString {
~""
}
pub fn SetHeight(&self, _height: DOMString) -> ErrorResult {
Ok(())
}
pub fn Hspace(&self) -> u32 {
0
}
pub fn SetHspace(&mut sel... | {
~""
} | identifier_body |
htmlappletelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLAppletElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLAppletElementD... | Ok(())
}
pub fn CodeBase(&self) -> DOMString {
~""
}
pub fn SetCodeBase(&self, _code_base: DOMString) -> ErrorResult {
Ok(())
}
pub fn Height(&self) -> DOMString {
~""
}
pub fn SetHeight(&self, _height: DOMString) -> ErrorResult {
Ok(())
}
... |
pub fn SetCode(&self, _code: DOMString) -> ErrorResult { | random_line_split |
macros.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/. */
//! Various macro helpers.
macro_rules! exclusive_value {
(($value:ident, $set:expr) => $ident:path) => {
... | }
#[cfg(feature = "gecko")]
macro_rules! impl_gecko_keyword_conversions {
($name:ident, $utype:ty) => {
impl From<$utype> for $name {
fn from(bits: $utype) -> $name {
$name::from_gecko_keyword(bits)
}
}
impl From<$name> for $utype {
fn fr... | }
}; | random_line_split |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
#[macro_use] extern crate contacts;
#[macro_use] extern crate error_chain;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate serde_derive;
extern crate postgres;
extern crate r2d2;
extern crate r2d2_postgres;
extern crate rocket;
extern crate... | (request: &'a Request<'r>) -> Outcome<Me, Self::Error> {
match get_me(request.cookies()) {
Ok(Some(me)) => Success(me),
Ok(None) => Forward(()),
Err(e) => Failure((Status::ServiceUnavailable, e)),
}
}
}
#[derive(Debug, FromForm)]
struct NewContactForm {
name... | from_request | identifier_name |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
#[macro_use] extern crate contacts;
#[macro_use] extern crate error_chain;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate serde_derive;
extern crate postgres;
extern crate r2d2;
extern crate r2d2_postgres;
extern crate rocket;
extern crate... | .get(0);
let cookie = Cookie::build("session", id.to_string())
//.domain(blah)
.path("/")
//.secure(true)
.http_only(true)
.finish();
cookies.add(cookie);
Ok(Redirect::to("/"))
}
#[derive(Debug)]
struct Me(Person);
fn get_me(cookies: &Cookies) -> Result<Optio... | WHERE login_key = $1
RETURNING session_id",
&key.into_inner())
.ok_or("failed to set session_id")? | random_line_split |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
#[macro_use] extern crate contacts;
#[macro_use] extern crate error_chain;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate serde_derive;
extern crate postgres;
extern crate r2d2;
extern crate r2d2_postgres;
extern crate rocket;
extern crate... | }
};
let login_key: Uuid = find!(db,
"INSERT INTO sessions (account) VALUES ($1) RETURNING login_key",
&me.id)
.ok_or("could not insert session")?
.get(0);
contacts::send_login(email, &login_key, new)?;
let mut context = HashMap::new();
context.insert... | {
let &Email { ref email } = form.get();
// if we start an auth flow, kill whatever session may exist
cookies.remove("session");
let res = find!(db,
"SELECT * FROM PEOPLE WHERE people.email = $1",
&email
).map(Person::from_row);
let (me, new) = match res {
Some(me) => ... | identifier_body |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
#[macro_use] extern crate contacts;
#[macro_use] extern crate error_chain;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate serde_derive;
extern crate postgres;
extern crate r2d2;
extern crate r2d2_postgres;
extern crate rocket;
extern crate... |
};
let login_key: Uuid = find!(db,
"INSERT INTO sessions (account) VALUES ($1) RETURNING login_key",
&me.id)
.ok_or("could not insert session")?
.get(0);
contacts::send_login(email, &login_key, new)?;
let mut context = HashMap::new();
context.insert("email",... | {
let me = find!(db,
"INSERT INTO PEOPLE (email) VALUES ($1) RETURNING *",
&email)
.map(Person::from_row)
.ok_or("could not create person")?;
(me, true)
} | conditional_block |
borrowck-scope-of-deref-issue-4666.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... | <'a>(&'a self) -> &'a uint {
&self.x
}
fn set(&mut self, x: uint) {
self.x = x;
}
}
fn fun1() {
// in the past, borrow checker behaved differently when
// init and decl of `v` were distinct
let v;
let mut a_box = Box {x: 0};
a_box.set(22);
v = *a_box.get();
a_box... | get | identifier_name |
borrowck-scope-of-deref-issue-4666.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... | pub fn main() {
fun1();
fun2();
} | assert_eq!(23, *a_box.get());
}
| random_line_split |
borrowck-scope-of-deref-issue-4666.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... |
pub fn main() {
fun1();
fun2();
}
| {
let mut a_box = Box {x: 0};
a_box.set(22);
let v = *a_box.get();
a_box.set(v+1);
assert_eq!(23, *a_box.get());
} | identifier_body |
frames.rs | /* Copyright (C) 2017-2021 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 add_event(&self, flow: *const Flow, dir: i32, event: u8) {
unsafe {
AppLayerFrameAddEventById(flow, dir, self.id, event);
};
}
} | }
| random_line_split |
frames.rs | /* Copyright (C) 2017-2021 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 new_ts(
flow: *const Flow, stream_slice: &StreamSlice, frame_start: &[u8], frame_len: i64,
frame_type: u8,
) -> Option<Self> {
Self::new(flow, stream_slice, frame_start, frame_len, 0, frame_type)
}
pub fn new_tc(
flow: *const Flow, stream_slice: &StreamSli... | {
None
} | conditional_block |
frames.rs | /* Copyright (C) 2017-2021 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... |
}
impl Frame {
pub fn new(
flow: *const Flow, stream_slice: &StreamSlice, frame_start: &[u8], frame_len: i64,
dir: i32, frame_type: u8,
) -> Option<Self> {
let offset = frame_start.as_ptr() as usize - stream_slice.as_slice().as_ptr() as usize;
SCLogDebug!("offset {} stream_slic... | {
write!(f, "frame: {}", self.id)
} | identifier_body |
frames.rs | /* Copyright (C) 2017-2021 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... | (
flow: *const Flow, stream_slice: &StreamSlice, frame_start: &[u8], frame_len: i64,
frame_type: u8,
) -> Option<Self> {
Self::new(flow, stream_slice, frame_start, frame_len, 0, frame_type)
}
pub fn new_tc(
flow: *const Flow, stream_slice: &StreamSlice, frame_start: &[u8], f... | new_ts | identifier_name |
cipher.rs | use std::sync::Arc;
use super::error::CipherResult;
use super::{Method, Mode};
use super::methods::BelongLib;
use super::crypto_lib::CryptoCipher;
#[cfg(feature = "openssl")]
use super::openssl_lib::OpensslCipher;
pub struct Cipher {
key: Arc<Vec<u8>>,
iv: Vec<u8>,
inner: Box<StreamCipher +'static>,
}
im... | (&self) -> usize {
self.key.len()
}
pub fn iv_len(&self) -> usize {
self.iv.len()
}
}
impl StreamCipher for Cipher {
fn update(&mut self, input: &[u8], output: &mut Vec<u8>) -> CipherResult<()> {
self.inner.update(input, output)
}
}
pub trait StreamCipher {
fn update(&... | key_len | identifier_name |
cipher.rs | use std::sync::Arc;
use super::error::CipherResult;
use super::{Method, Mode};
use super::methods::BelongLib;
use super::crypto_lib::CryptoCipher;
#[cfg(feature = "openssl")]
use super::openssl_lib::OpensslCipher;
pub struct Cipher {
key: Arc<Vec<u8>>,
iv: Vec<u8>,
inner: Box<StreamCipher +'static>,
}
im... | self.iv[..].copy_from_slice(iv);
}
pub fn key_len(&self) -> usize {
self.key.len()
}
pub fn iv_len(&self) -> usize {
self.iv.len()
}
}
impl StreamCipher for Cipher {
fn update(&mut self, input: &[u8], output: &mut Vec<u8>) -> CipherResult<()> {
self.inner.updat... | &self.iv
}
pub fn set_iv(&mut self, iv: &[u8]) { | random_line_split |
cipher.rs | use std::sync::Arc;
use super::error::CipherResult;
use super::{Method, Mode};
use super::methods::BelongLib;
use super::crypto_lib::CryptoCipher;
#[cfg(feature = "openssl")]
use super::openssl_lib::OpensslCipher;
pub struct Cipher {
key: Arc<Vec<u8>>,
iv: Vec<u8>,
inner: Box<StreamCipher +'static>,
}
im... |
}
impl StreamCipher for Cipher {
fn update(&mut self, input: &[u8], output: &mut Vec<u8>) -> CipherResult<()> {
self.inner.update(input, output)
}
}
pub trait StreamCipher {
fn update(&mut self, input: &[u8], output: &mut Vec<u8>) -> CipherResult<()>;
}
| {
self.iv.len()
} | identifier_body |
assign_node_ids.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 ... | {
let fold = NodeIdAssigner {
sess: sess,
};
fold.fold_crate(crate)
} | identifier_body | |
assign_node_ids.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 ... | (sess: Session, crate: ast::Crate) -> ast::Crate {
let fold = NodeIdAssigner {
sess: sess,
};
fold.fold_crate(crate)
}
| assign_node_ids | identifier_name |
assign_node_ids.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 ... | use syntax::fold::ast_fold;
struct NodeIdAssigner {
sess: Session,
}
impl ast_fold for NodeIdAssigner {
fn new_id(&self, old_id: ast::NodeId) -> ast::NodeId {
assert_eq!(old_id, ast::DUMMY_NODE_ID);
self.sess.next_node_id()
}
}
pub fn assign_node_ids(sess: Session, crate: ast::Crate) -> a... | // except according to those terms.
use driver::session::Session;
use syntax::ast; | random_line_split |
user_agent.rs | header! {
#[doc="`User-Agent` header, defined in"]
#[doc="[RFC7231](http://tools.ietf.org/html/rfc7231#section-5.5.3)"]
#[doc=""]
#[doc="The `User-Agent` header field contains information about the user"]
#[doc="agent originating the request, which is often used by servers to help"]
#[doc="ident... | #[doc="* The parser does not split the value"]
(UserAgent, "User-Agent") => [String]
test_user_agent {
// Testcase from RFC
test_header!(test1, vec![b"CERN-LineMode/2.15 libwww/2.17b3"]);
// Own testcase
test_header!(test2, vec![b"Bunnies"], Some(UserAgent("Bunnies".to_strin... | #[doc="# Example values"]
#[doc="* `CERN-LineMode/2.15 libwww/2.17b3`"]
#[doc="* `Bunnies`"]
#[doc=""]
#[doc="# Notes"] | random_line_split |
channel_mpsc.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 serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::io;
use std::io::{Error, ErrorKind};
use s... |
}
impl<'de, T> Deserialize<'de> for MsgSender<T> {
fn deserialize<D>(_: D) -> Result<MsgSender<T>, D::Error>
where D: Deserializer<'de> {
unreachable!();
}
}
| {
unreachable!();
} | identifier_body |
channel_mpsc.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 serde::{Deserialize, Deserializer, Serialize, Serializer}; | use std::io;
use std::io::{Error, ErrorKind};
use std::sync::mpsc;
///
/// Handles the channel implementation when in process channels are enabled.
///
pub type PayloadSender = MsgSender<Payload>;
pub type PayloadReceiver = MsgReceiver<Payload>;
impl PayloadSenderHelperMethods for PayloadSender {
fn send_payloa... | random_line_split | |
channel_mpsc.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 serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::io;
use std::io::{Error, ErrorKind};
use s... | () -> Result<(PayloadSender, PayloadReceiver), Error> {
let (tx, rx) = mpsc::channel();
Ok((PayloadSender { tx }, PayloadReceiver { rx }))
}
pub fn msg_channel<T>() -> Result<(MsgSender<T>, MsgReceiver<T>), Error> {
let (tx, rx) = mpsc::channel();
Ok((MsgSender { tx }, MsgReceiver { rx }))
}
///
/// T... | payload_channel | identifier_name |
error.rs | use rustc_serialize::json::DecoderError;
use rustc_serialize::base64::FromBase64Error; | pub enum VaultError {
/// If the vault is corrupted, we may not be able to read the base64 encoded data
Base64Error(FromBase64Error),
/// This happens when the data in the vault is valid, but does not match the vault type
VaultEntrySchemaError(DecoderError),
/// When the decrypted data is not valid ... | use self::VaultError::*;
/// Various errors for vault operations
#[derive(Debug)] | random_line_split |
error.rs | use rustc_serialize::json::DecoderError;
use rustc_serialize::base64::FromBase64Error;
use self::VaultError::*;
/// Various errors for vault operations
#[derive(Debug)]
pub enum VaultError {
/// If the vault is corrupted, we may not be able to read the base64 encoded data
Base64Error(FromBase64Error),
/// ... | (e: FromBase64Error) -> VaultError {
Base64Error(e)
}
}
| from | identifier_name |
version.rs | //! HTTP Versions enum
//!
//! Instead of relying on typo-prone Strings, use expected HTTP versions as
//! the `HttpVersion` enum.
use std::fmt;
use std::str::FromStr;
use error::Error;
use self::HttpVersion::{Http09, Http10, Http11, H2, H2c};
/// Represents a version of the HTTP spec.
#[derive(PartialEq, PartialOrd,... | Http11 => "HTTP/1.1",
H2 => "h2",
H2c => "h2c",
HttpVersion::__DontMatchMe => unreachable!(),
})
}
}
impl FromStr for HttpVersion {
type Err = Error;
fn from_str(s: &str) -> Result<HttpVersion, Error> {
Ok(match s {
"HTTP/0.9" => H... | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(match *self {
Http09 => "HTTP/0.9",
Http10 => "HTTP/1.0", | random_line_split |
version.rs | //! HTTP Versions enum
//!
//! Instead of relying on typo-prone Strings, use expected HTTP versions as
//! the `HttpVersion` enum.
use std::fmt;
use std::str::FromStr;
use error::Error;
use self::HttpVersion::{Http09, Http10, Http11, H2, H2c};
/// Represents a version of the HTTP spec.
#[derive(PartialEq, PartialOrd,... | (s: &str) -> Result<HttpVersion, Error> {
Ok(match s {
"HTTP/0.9" => Http09,
"HTTP/1.0" => Http10,
"HTTP/1.1" => Http11,
"h2" => H2,
"h2c" => H2c,
_ => return Err(Error::Version),
})
}
}
impl Default for HttpVersion {
fn de... | from_str | identifier_name |
version.rs | //! HTTP Versions enum
//!
//! Instead of relying on typo-prone Strings, use expected HTTP versions as
//! the `HttpVersion` enum.
use std::fmt;
use std::str::FromStr;
use error::Error;
use self::HttpVersion::{Http09, Http10, Http11, H2, H2c};
/// Represents a version of the HTTP spec.
#[derive(PartialEq, PartialOrd,... |
}
| {
match HttpVersion::from_str("foo") {
Err(Error::Version) => assert!(true),
Err(_) => assert!(false),
Ok(_) => assert!(false),
}
} | identifier_body |
pp.rs | algorithm decides to break
//! there anyways (because the functions themselves are long) you wind up with
//! extra blank lines. If you don't put hardbreaks you can wind up with the
//! "thing which should be on its own line" not getting its own line in the
//! rare case of "really small functions" or such. This re-oc... | (&mut self, t: Token) {
self.token[self.right] = t;
}
pub fn pretty_print(&mut self, token: Token) -> old_io::IoResult<()> {
debug!("pp ~[{},{}]", self.left, self.right);
match token {
Token::Eof => {
if!self.scan_stack_empty {
self.check_stack(0);
... | replace_last_token | identifier_name |
pp.rs | pending_indentation: 0
}
}
/// In case you do not have the paper, here is an explanation of what's going
/// on.
///
/// There is a stream of input tokens flowing through this printer.
///
/// The printer buffers up to 3N tokens inside itself, where N is linewidth.
/// Yes, linewidth is chars and tokens are... | }
pub fn hardbreak(p: &mut Printer) -> old_io::IoResult<()> {
spaces(p, SIZE_INFINITY as usize)
} | random_line_split | |
pp.rs | algorithm decides to break
//! there anyways (because the functions themselves are long) you wind up with
//! extra blank lines. If you don't put hardbreaks you can wind up with the
//! "thing which should be on its own line" not getting its own line in the
//! rare case of "really small functions" or such. This re-oc... |
// be very careful with this!
pub fn replace_last_token(&mut self, t: Token) {
self.token[self.right] = t;
}
pub fn pretty_print(&mut self, token: Token) -> old_io::IoResult<()> {
debug!("pp ~[{},{}]", self.left, self.right);
match token {
Token::Eof => {
i... | {
self.token[self.right].clone()
} | identifier_body |
pp.rs | algorithm decides to break
//! there anyways (because the functions themselves are long) you wind up with
//! extra blank lines. If you don't put hardbreaks you can wind up with the
//! "thing which should be on its own line" not getting its own line in the
//! rare case of "really small functions" or such. This re-oc... |
}
}
}
pub fn check_stream(&mut self) -> old_io::IoResult<()> {
debug!("check_stream ~[{}, {}] with left_total={}, right_total={}",
self.left, self.right, self.left_total, self.right_total);
if self.right_total - self.left_total > self.space {
debug!(... | {
debug!("pp String('{}')/buffer ~[{},{}]",
s, self.left, self.right);
self.advance_right();
self.token[self.right] = Token::String(s, len);
self.size[self.right] = len;
self.right_total += len;
self.c... | conditional_block |
ty.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
pub fn borrowed_explicit_self<'r>() -> Option<Option<PtrTy<'r>>> {
Some(Some(borrowed_ptrty()))
}
pub fn borrowed_self<'r>() -> Ty<'r> {
borrowed(box Self)
}
pub fn nil_ty<'r>() -> Ty<'r> {
Tuple(Vec::new())
}
fn mk_lifetime(cx: &ExtCtxt, span: Span, lt: &Option<&str>) -> Option<ast::Lifetime> {
m... | pub fn borrowed<'r>(ty: Box<Ty<'r>>) -> Ty<'r> {
Ptr(ty, borrowed_ptrty()) | random_line_split |
ty.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn nil_ty<'r>() -> Ty<'r> {
Tuple(Vec::new())
}
fn mk_lifetime(cx: &ExtCtxt, span: Span, lt: &Option<&str>) -> Option<ast::Lifetime> {
match *lt {
Some(ref s) => Some(cx.lifetime(span, cx.ident_of(*s).name)),
None => None
}
}
fn mk_lifetimes(cx: &ExtCtxt, span: Span, lt: &Option<&str... | {
borrowed(box Self)
} | identifier_body |
ty.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 ... |
Tuple(..) => { cx.span_bug(span, "tuple in a path in generic `deriving`") }
}
}
}
fn mk_ty_param(cx: &ExtCtxt, span: Span, name: &str,
bounds: &[Path], unbound: Option<ast::TraitRef>,
self_ident: Ident, self_generics: &Generics) -> ast::TyParam {
let bounds =... | { cx.span_bug(span, "pointer in a path in generic `deriving`") } | conditional_block |
ty.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 ... | <'r>() -> Ty<'r> {
Tuple(Vec::new())
}
fn mk_lifetime(cx: &ExtCtxt, span: Span, lt: &Option<&str>) -> Option<ast::Lifetime> {
match *lt {
Some(ref s) => Some(cx.lifetime(span, cx.ident_of(*s).name)),
None => None
}
}
fn mk_lifetimes(cx: &ExtCtxt, span: Span, lt: &Option<&str>) -> Vec<ast::... | nil_ty | identifier_name |
utils.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | FlightData {
flight_descriptor: None,
app_metadata: vec![],
data_header: schema.ipc_message,
data_body: vec![],
}
}
/// Try convert `FlightData` into an Arrow Schema
///
/// Returns an error if the `FlightData` header is not a valid IPC schema
impl TryFrom<&FlightData> for Schem... | ) -> FlightData {
let schema = writer::schema_to_bytes(schema, &options); | random_line_split |
utils.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
}
/// Convert a `RecordBatch` to `FlightData` by converting the header and body to bytes
pub fn flight_data_from_arrow_batch(
batch: &RecordBatch,
options: &IpcWriteOptions,
) -> FlightData {
let data = writer::record_batch_to_bytes(batch, &options);
FlightData {
flight_descriptor: None,
... | {
let options = IpcWriteOptions::default();
flight_data_from_arrow_batch(batch, &options)
} | identifier_body |
utils.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | (data: &FlightData) -> Result<Self> {
convert::schema_from_bytes(&data.data_header[..]).ok_or_else(|| {
ArrowError::ParseError(
"Unable to convert flight data to Arrow schema".to_string(),
)
})
}
}
/// Try convert `SchemaResult` into an Arrow Schema
///
/// R... | try_from | identifier_name |
mat.rs | use num::Float;
use std::fmt;
use std::ops::{Add, Sub, Mul};
use numvec::Vec3f;
/// The type of matrix elements.
pub type Scalar = f32;
/// A 4x4 matrix type stored in column-major order for interoperability with
/// OpenGL.
///
/// Supports the creation of isometries and projections in homogenous
/// coordinates. ... |
/// Returns the transpose of the matrix (columns swapped with rows).
pub fn transposed(&self) -> Mat4 {
let m = &self.data;
// m is in column-major order, so calling with new in row-order will
// transpose it.
Mat4::new(m[0], m[1], m[2], m[3],
m[4], m[5], m[6]... | {
Mat4::new(1.0, 0.0, 0.0, by.x,
0.0, 1.0, 0.0, by.y,
0.0, 0.0, 1.0, by.z,
0.0, 0.0, 0.0, 1.0)
} | identifier_body |
mat.rs | use num::Float;
use std::fmt;
use std::ops::{Add, Sub, Mul};
use numvec::Vec3f;
/// The type of matrix elements.
pub type Scalar = f32;
/// A 4x4 matrix type stored in column-major order for interoperability with
/// OpenGL.
///
/// Supports the creation of isometries and projections in homogenous
/// coordinates. ... | l[12] - r[12], l[13] - r[13], l[14] - r[14], l[15] - r[15]],
}
}
}
impl Mul<Mat4> for Mat4 {
type Output = Mat4;
fn mul(self, rhs: Mat4) -> Mat4 { &self * &rhs }
}
impl Add<Mat4> for Mat4 {
type Output = Mat4;
fn add(self, rhs: Mat4) -> Mat4 { &self + &rhs }
}
impl Su... | Mat4 {
data: [l[0] - r[0], l[1] - r[1], l[2] - r[2], l[3] - r[3],
l[4] - r[4], l[5] - r[5], l[6] - r[6], l[7] - r[7],
l[8] - r[8], l[9] - r[9], l[10] - r[10], l[11] - r[11], | random_line_split |
mat.rs | use num::Float;
use std::fmt;
use std::ops::{Add, Sub, Mul};
use numvec::Vec3f;
/// The type of matrix elements.
pub type Scalar = f32;
/// A 4x4 matrix type stored in column-major order for interoperability with
/// OpenGL.
///
/// Supports the creation of isometries and projections in homogenous
/// coordinates. ... | (axis: &Vec3f, angle_radians: Scalar) -> Mat4 {
let ca = angle_radians.cos();
let sa = angle_radians.sin();
let nca = 1.0 - ca;
let u = axis;
Mat4::new(
ca + u.x*u.x*nca, u.x*u.y*nca - u.z*sa, u.x*u.z*nca + u.y*sa, 0.0,
u.y*u.x*nca + u.z*sa, ca + u.y*u.y*n... | new_axis_rotation | identifier_name |
pager.rs | // SPDX-License-Identifier: Unlicense
//! Interface for paging functions.
use crate::pager::{
Attributes, FixedOffset, FrameAllocator, PhysAddr, PhysAddrRange, Translate, VirtAddr,
VirtAddrRange,
};
use crate::util::locked::Locked;
use crate::Result;
use core::any::Any;
/// Each architecture must supply the... | () -> impl PageDirectory {
super::arch::new_page_directory()
}
| new_page_directory | identifier_name |
pager.rs | // SPDX-License-Identifier: Unlicense
//! Interface for paging functions.
use crate::pager::{
Attributes, FixedOffset, FrameAllocator, PhysAddr, PhysAddrRange, Translate, VirtAddr,
VirtAddrRange, | use crate::Result;
use core::any::Any;
/// Each architecture must supply the following entry points for paging..
pub trait PagerTrait {
/// Physical address range of ram
fn ram_range() -> PhysAddrRange;
/// Base virtual address of kernel address space
fn kernel_base() -> VirtAddr;
/// Kernel offs... | };
use crate::util::locked::Locked; | random_line_split |
pager.rs | // SPDX-License-Identifier: Unlicense
//! Interface for paging functions.
use crate::pager::{
Attributes, FixedOffset, FrameAllocator, PhysAddr, PhysAddrRange, Translate, VirtAddr,
VirtAddrRange,
};
use crate::util::locked::Locked;
use crate::Result;
use core::any::Any;
/// Each architecture must supply the... | {
super::arch::new_page_directory()
} | identifier_body | |
variant_ref.rs | use vtable::VTable;
use std::any::{Any, TypeId};
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
pub struct VariantRef<'a> {
pub data: &'a (),
pub vtable: &'a VTable,
}
impl<'a> VariantRef<'a> {
pub fn new<T: Any>(value: &'a T, vtable: &'a VTable) -> Self {
VariantRef {
data: un... | <T: Any>(&self) -> &T {
debug_assert!(self.is::<T>());
&*(self.data as *const _ as *const T)
}
}
impl<'a> Display for VariantRef<'a> {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
(self.vtable.display)(self, f)
}
}
impl<'a> Debug for VariantRef<'a> {
fn fmt(&self, f: &mut ... | downcast_ref_unchecked | identifier_name |
variant_ref.rs | use vtable::VTable;
use std::any::{Any, TypeId};
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
pub struct VariantRef<'a> {
pub data: &'a (),
pub vtable: &'a VTable,
}
impl<'a> VariantRef<'a> {
pub fn new<T: Any>(value: &'a T, vtable: &'a VTable) -> Self {
VariantRef {
data: un... |
}
| {
(self.vtable.debug)(self, f)
} | identifier_body |
variant_ref.rs | use vtable::VTable;
use std::any::{Any, TypeId};
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
pub struct VariantRef<'a> {
pub data: &'a (),
pub vtable: &'a VTable,
}
impl<'a> VariantRef<'a> {
pub fn new<T: Any>(value: &'a T, vtable: &'a VTable) -> Self {
VariantRef {
data: un... | else {
None
}
}
#[inline]
pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
debug_assert!(self.is::<T>());
&*(self.data as *const _ as *const T)
}
}
impl<'a> Display for VariantRef<'a> {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
(self.vtable... | {
unsafe { Some(&*(self.data as *const _ as *const T)) }
} | conditional_block |
variant_ref.rs | use vtable::VTable;
use std::any::{Any, TypeId};
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
pub struct VariantRef<'a> {
pub data: &'a (),
pub vtable: &'a VTable,
}
impl<'a> VariantRef<'a> {
pub fn new<T: Any>(value: &'a T, vtable: &'a VTable) -> Self {
VariantRef {
data: un... | &*(self.data as *const _ as *const T)
}
}
impl<'a> Display for VariantRef<'a> {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
(self.vtable.display)(self, f)
}
}
impl<'a> Debug for VariantRef<'a> {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
(self.vtable.debug)... | pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
debug_assert!(self.is::<T>());
| random_line_split |
save.rs | use std::io;
use std::io::prelude::*;
use std::path::Path;
use std::fs::{self, File};
use gb_emu::cart::SaveFile;
pub struct LocalSaveWrapper<'a> {
pub path: &'a Path,
}
impl<'a> SaveFile for LocalSaveWrapper<'a> {
fn load(&mut self, data: &mut [u8]) {
if let Ok(_) = File::open(&self.path).map(|mut f... | (&mut self, data: &[u8]) {
// First create a temporary file and write to that, to ensure that if an error occurs, the
// old file is not lost.
let tmp_path = self.path.with_extension("sav.tmp");
if let Err(e) = File::create(&tmp_path).map(|mut f| f.write_all(data)) {
println!... | save | identifier_name |
save.rs | use std::io;
use std::io::prelude::*;
use std::path::Path;
use std::fs::{self, File};
use gb_emu::cart::SaveFile;
pub struct LocalSaveWrapper<'a> {
pub path: &'a Path,
}
impl<'a> SaveFile for LocalSaveWrapper<'a> {
fn load(&mut self, data: &mut [u8]) {
if let Ok(_) = File::open(&self.path).map(|mut f... | match fs::remove_file(&self.path) {
Ok(_) => {},
Err(ref e) if e.kind() == io::ErrorKind::NotFound => {},
Err(e) => {
println!("Error removing old save file ({}), current save has been written to: {}",
e, tmp_path.display());
... |
// At this stage the new save file has been successfully written, so we can safely remove
// the old file if it exists. | random_line_split |
simple_test.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::query::Equality;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
use rustorm::table::{IsTable, Table};
#[derive(Debug, Clone)]
pub struct Product {
... | fn table() -> Table {
Table {
schema: "bazaar".to_string(),
name: "product".to_string(),
parent_table: None,
sub_table: vec![],
comment: None,
columns: vec![],
is_view: false,
}
}
}
#[test]
fn test_simple_query(... | dao
}
}
impl IsTable for Product{ | random_line_split |
simple_test.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::query::Equality;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
use rustorm::table::{IsTable, Table};
#[derive(Debug, Clone)]
pub struct Product {
... | {
let url = "postgres://postgres:p0stgr3s@localhost/bazaar_v6";
let pool = ManagedPool::init(&url, 1).unwrap();
let db = pool.connect().unwrap();
let prod: Product = Query::select_all()
.from_table("bazaar.product")
.filter("name", Equality::EQ, &... | identifier_body | |
simple_test.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::query::Equality;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
use rustorm::table::{IsTable, Table};
#[derive(Debug, Clone)]
pub struct Product {
... | () -> Table {
Table {
schema: "bazaar".to_string(),
name: "product".to_string(),
parent_table: None,
sub_table: vec![],
comment: None,
columns: vec![],
is_view: false,
}
}
}
#[test]
fn test_simple_query() {
let ... | table | identifier_name |
merkle_tree.rs | use std;
extern crate bit_vec;
use super::{UInt256};
use ::serialize::{self, Serializable};
fn reverse_u8(x:u8) -> u8 {
let x:u8 = ((x & 0x55) << 1) | ((x & 0xAA) >> 1);
let x:u8 = ((x & 0x33) << 2) | ((x & 0xCC) >> 2);
let x:u8 = (x << 4) | (x >> 4);
x
}
#[derive(Debug,Default,Clone)]
pub struct PartialM... | impl std::fmt::Display for PartialMerkleTree {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "PartialMerkleTree(n={}, bits={:?}, hash={:?})", self.n_transactions, self.bits, self.hashes)
}
}
impl Serializable for PartialMerkleTree {
fn get_serialize_size(&self, _ser:&seriali... | random_line_split | |
merkle_tree.rs | use std;
extern crate bit_vec;
use super::{UInt256};
use ::serialize::{self, Serializable};
fn reverse_u8(x:u8) -> u8 {
let x:u8 = ((x & 0x55) << 1) | ((x & 0xAA) >> 1);
let x:u8 = ((x & 0x33) << 2) | ((x & 0xCC) >> 2);
let x:u8 = (x << 4) | (x >> 4);
x
}
#[derive(Debug,Default,Clone)]
pub struct PartialM... | (&self, io:&mut std::io::Write, ser:&serialize::SerializeParam) -> serialize::Result {
let mut r:usize = 0;
r += try!(self.n_transactions.serialize(io, ser));
{
let mut bytes = self.bits.to_bytes();
for byte in &mut bytes {
*byte = reverse_u8(*byte);
}
r... | serialize | identifier_name |
hofstadter_q.rs | // Implements an iterable version of http://rosettacode.org/wiki/Hofstadter_Q_sequence
// Define a struct which stores the state for the iterator.
struct HofstadterQ {
next: usize,
memoize_vec: Vec<usize>
}
impl HofstadterQ {
// Define a constructor for the struct.
fn new() -> HofstadterQ {
Hofs... | () {
// Set up the iterable.
let hof: HofstadterQ = HofstadterQ::new();
// Create the iterator.
let mut it = hof.take(10);
// Test that the first ten values are as expected
// The first two values are hardcoded, so no need to test those.
let hofstadter_q_expected = vec![2,3,3,4,5,5,6,6];
... | test_first_ten | identifier_name |
hofstadter_q.rs | // Implements an iterable version of http://rosettacode.org/wiki/Hofstadter_Q_sequence
// Define a struct which stores the state for the iterator.
struct HofstadterQ {
next: usize,
memoize_vec: Vec<usize>
}
impl HofstadterQ {
// Define a constructor for the struct.
fn new() -> HofstadterQ {
Hofs... |
}
#[cfg(not(test))]
fn main() {
// Set up the iterable.
let hof: HofstadterQ = HofstadterQ::new();
// The number of terms we want from the iterator.
let upto: usize = 1000;
// Create the iterator.
let mut it = hof.take(upto - 2);
// Print the base values.
println!("H(1) = 1");
prin... | {
// Cache the current value.
self.memoize_vec.push(self.next);
// And then calculate the 'next'.
// First, make the four recursive calls.
let current: usize = self.memoize_vec.len();
let rec_call_1: usize = self.memoize_vec[current - 1];
let rec_call_2: usize = s... | identifier_body |
hofstadter_q.rs | // Implements an iterable version of http://rosettacode.org/wiki/Hofstadter_Q_sequence
// Define a struct which stores the state for the iterator.
struct HofstadterQ {
next: usize,
memoize_vec: Vec<usize>
}
impl HofstadterQ {
// Define a constructor for the struct.
fn new() -> HofstadterQ {
Hofs... | // The number of terms we want from the iterator.
let upto: usize = 1000;
// Create the iterator.
let mut it = hof.take(upto - 2);
// Print the base values.
println!("H(1) = 1");
println!("H(2) = 1");
// Print the rest of the sequence.
for i in (3..1+upto) {
println!("H({}) =... | random_line_split | |
ike.rs | /* Copyright (C) 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 WARR... |
static mut ALPROTO_IKE : AppProto = ALPROTO_UNKNOWN;
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_get_tx_iterator(
_ipproto: u8, _alproto: AppProto, state: *mut std::os::raw::c_void, min_tx_id: u64,
_max_tx_id: u64, istate: &mut u64,
) -> applayer::AppLayerGetTxIterTuple {
let state = cast_pointer!... | {
let tx = cast_pointer!(tx, IKETransaction);
return tx.events;
} | identifier_body |
ike.rs | /* Copyright (C) 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 WARR... | isakmp_header.exch_type);
return false;
}
if isakmp_header.length as usize!= input.len() {
SCLogDebug!("ipsec_probe: could be ipsec, but length does not match");
return false;
}
... | random_line_split | |
ike.rs | /* Copyright (C) 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 WARR... | () {
let default_port = CString::new("500").unwrap();
let parser = RustParser {
name : PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
default_port : default_port.as_ptr(),
ipproto : core::IPPROTO_UDP,
probe_ts : Some(rs_ike_probing_p... | rs_ike_register_parser | identifier_name |
panic.rs | //! Panic runtime for Miri.
//!
//! The core pieces of the runtime are:
//! - An implementation of `__rust_maybe_catch_panic` that pushes the invoked stack frame with
//! some extra metadata derived from the panic-catching arguments of `__rust_maybe_catch_panic`.
//! - A hack in `libpanic_unwind` that calls the `miri... | this.machine.panic_payload.is_none(),
"the panic runtime should avoid double-panics"
);
this.machine.panic_payload = Some(scalar);
// Jump to the unwind block to begin unwinding.
this.unwind_to_block(unwind);
return Ok(());
}
fn handle_catch_pani... | // Get the raw pointer stored in arg[0] (the panic payload).
let scalar = this.read_immediate(args[0])?;
assert!( | random_line_split |
panic.rs | //! Panic runtime for Miri.
//!
//! The core pieces of the runtime are:
//! - An implementation of `__rust_maybe_catch_panic` that pushes the invoked stack frame with
//! some extra metadata derived from the panic-catching arguments of `__rust_maybe_catch_panic`.
//! - A hack in `libpanic_unwind` that calls the `miri... | (
&mut self,
args: &[OpTy<'tcx, Tag>],
dest: PlaceTy<'tcx, Tag>,
ret: mir::BasicBlock,
) -> InterpResult<'tcx> {
let this = self.eval_context_mut();
let tcx = &{ this.tcx.tcx };
// fn __rust_maybe_catch_panic(
// f: fn(*mut u8),
// dat... | handle_catch_panic | identifier_name |
rom_nist384_32.rs | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this f... | pub const SIGN_OF_X: SignOfX = SignOfX::NOT;
pub const HASH_TYPE: usize = 48;
pub const AESKEY: usize = 24; | random_line_split | |
pkgid.rs | use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_wd};
#[derive(RustcDecodable)]
struct Options {
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
flag_manifest_path: Option<String>,
arg_spec: Option<String>,
}... | {
try!(config.shell().set_verbosity(options.flag_verbose, options.flag_quiet));
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_wd(options.flag_manifest_path.clone(), config.cwd()));
let spec = options.arg_spec.as_ref().map(|s| ... | identifier_body | |
pkgid.rs | use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_wd};
#[derive(RustcDecodable)]
struct Options {
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>, | arg_spec: Option<String>,
}
pub const USAGE: &'static str = "
Print a fully qualified package specification
Usage:
cargo pkgid [options] [<spec>]
Options:
-h, --help Print this message
--manifest-path PATH Path to the manifest to the package to clean
-v, --verbose Use... | flag_manifest_path: Option<String>, | random_line_split |
pkgid.rs | use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_wd};
#[derive(RustcDecodable)]
struct | {
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
flag_manifest_path: Option<String>,
arg_spec: Option<String>,
}
pub const USAGE: &'static str = "
Print a fully qualified package specification
Usage:
cargo pkgid [options] [<spec>]
Options:
-h, --help Prin... | Options | identifier_name |
main.ng.rs | //! Multivariate linear regression using gradient descent
//!
//! Model:
//!
//! ```
//! y = x * theta + e
//!
//! y Dependent variable (scalar)
//! x Independent variables (1-by-n matrix)
//! theta Parameters to estimate (n-by-1 matrix)
//! e Error (scalar)
//! ```
//!
//! Solver:... | <P>(path: P) -> io::Result<Transposed<Mat<f64>>> where P: AsRef<Path> {
fn load(path: &Path) -> io::Result<Transposed<Mat<f64>>> {
let mut lines = Lines::from(BufReader::new(try!(File::open(path))));
let mut v = vec![];
let ncols = {
let mut ncols = 0;
for number i... | load | identifier_name |
main.ng.rs | //! Multivariate linear regression using gradient descent
//!
//! Model:
//!
//! ```
//! y = x * theta + e
//!
//! y Dependent variable (scalar)
//! x Independent variables (1-by-n matrix)
//! theta Parameters to estimate (n-by-1 matrix)
//! e Error (scalar)
//! ```
//!
//! Solver:... | for number in line.split_whitespace() {
v.push(number.parse().unwrap());
}
nrows += 1;
}
unsafe {
Ok(Mat::from_raw_parts(v.into_boxed_slice(), (ncols, nrows)).t())
}
}
load(path.as_ref())
}
| {
let mut lines = Lines::from(BufReader::new(try!(File::open(path))));
let mut v = vec![];
let ncols = {
let mut ncols = 0;
for number in try!(lines.next().unwrap()).split_whitespace() {
ncols += 1;
v.push(number.parse().unwrap());
... | identifier_body |
main.ng.rs | //! Multivariate linear regression using gradient descent
//!
//! Model:
//!
//! ```
//! y = x * theta + e
//!
//! y Dependent variable (scalar)
//! x Independent variables (1-by-n matrix)
//! theta Parameters to estimate (n-by-1 matrix)
//! e Error (scalar)
//! ```
//!
//! Solver:... | #![feature(plugin)]
#![plugin(linalg_macros)]
extern crate cast;
extern crate env_logger;
extern crate linalg;
extern crate lines;
extern crate time;
#[macro_use]
extern crate log;
use std::fs::File;
use std::io::{BufReader, self};
use std::path::Path;
use cast::From as _0;
use linalg::prelude::*;
use linalg::Tran... | //! ```
#![allow(non_snake_case)]
#![deny(warnings)] | random_line_split |
parsing_utils.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 std::ascii::AsciiExt;
use cssparser::ast::{ComponentValue, Ident, Comma, SkipWhitespaceIterable, SkipWhitespa... |
#[inline]
pub fn is_eof(&mut self) -> bool {
match self.next() {
Some(value) => {
self.push_back(value);
false
}
None => true
}
}
#[inline]
pub fn next_as_result(&mut self) -> Result<E, ()> {
match self.ne... | {
assert!(self.buffer.is_none());
self.buffer = Some(value);
} | identifier_body |
parsing_utils.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 std::ascii::AsciiExt;
use cssparser::ast::{ComponentValue, Ident, Comma, SkipWhitespaceIterable, SkipWhitespa... | }
}
pub type ParserIter<'a, 'b> = &'a mut BufferedIter<&'b ComponentValue, SkipWhitespaceIterator<'b>>;
#[inline]
pub fn parse_slice_comma_separated<T>(input: &[ComponentValue],
parse_one: |ParserIter| -> Result<T, ()>)
-> Result<Vec<T>,... | random_line_split | |
parsing_utils.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 std::ascii::AsciiExt;
use cssparser::ast::{ComponentValue, Ident, Comma, SkipWhitespaceIterable, SkipWhitespa... | (&mut self) -> Result<E, ()> {
match self.next() {
Some(value) => Ok(value),
None => Err(()),
}
}
}
impl<E, I: Iterator<E>> Iterator<E> for BufferedIter<E, I> {
#[inline]
fn next(&mut self) -> Option<E> {
if self.buffer.is_some() {
self.buffer.tak... | next_as_result | identifier_name |
parse.rs | #[macro_use]
extern crate criterion;
extern crate rand;
extern crate rs_poker;
use criterion::Criterion;
use rs_poker::holdem::RangeParser;
fn parse_ako(c: &mut Criterion) {
c.bench_function("Parse AKo", |b| {
b.iter(|| RangeParser::parse_one("AKo"));
});
}
fn | (c: &mut Criterion) {
c.bench_function("Parse pairs (22+)", |b| {
b.iter(|| RangeParser::parse_one("22+"));
});
}
fn parse_connectors(c: &mut Criterion) {
c.bench_function("Parse connectors (32+)", |b| {
b.iter(|| RangeParser::parse_one("32+"));
});
}
fn parse_plus(c: &mut Criterion) {... | parse_pairs | identifier_name |
parse.rs | #[macro_use]
extern crate criterion;
extern crate rand;
extern crate rs_poker;
use criterion::Criterion;
use rs_poker::holdem::RangeParser;
fn parse_ako(c: &mut Criterion) {
c.bench_function("Parse AKo", |b| {
b.iter(|| RangeParser::parse_one("AKo"));
});
}
fn parse_pairs(c: &mut Criterion) {
c.b... | criterion_main!(benches); | random_line_split | |
parse.rs | #[macro_use]
extern crate criterion;
extern crate rand;
extern crate rs_poker;
use criterion::Criterion;
use rs_poker::holdem::RangeParser;
fn parse_ako(c: &mut Criterion) {
c.bench_function("Parse AKo", |b| {
b.iter(|| RangeParser::parse_one("AKo"));
});
}
fn parse_pairs(c: &mut Criterion) |
fn parse_connectors(c: &mut Criterion) {
c.bench_function("Parse connectors (32+)", |b| {
b.iter(|| RangeParser::parse_one("32+"));
});
}
fn parse_plus(c: &mut Criterion) {
c.bench_function("Parse plus (A2+)", |b| {
b.iter(|| RangeParser::parse_one("A2+"));
});
}
criterion_group!(
... | {
c.bench_function("Parse pairs (22+)", |b| {
b.iter(|| RangeParser::parse_one("22+"));
});
} | identifier_body |
rpc.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 app_units::Au; | use servo_arc::Arc;
use style::properties::ComputedValues;
use style::properties::longhands::overflow_x;
use webrender_api::ExternalScrollId;
/// Synchronous messages that script can send to layout.
///
/// In general, you should use messages to talk to Layout. Use the RPC interface
/// if and only if the work is
///
... | use euclid::{Point2D, Rect};
use script_traits::UntrustedNodeAddress; | random_line_split |
rpc.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 app_units::Au;
use euclid::{Point2D, Rect};
use script_traits::UntrustedNodeAddress;
use servo_arc::Arc;
use s... | (pub Option<Arc<ComputedValues>>);
#[derive(Clone)]
pub struct TextIndexResponse(pub Option<usize>);
| StyleResponse | identifier_name |
combine.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 stack to get this right.
try!(match dir {
BiTo => self.bivariate().relate(&a_ty, &b_ty),
EqTo => self.equate().relate(&a_ty, &b_ty),
SubtypeOf => self.sub().relate(&a_ty, &b_ty),
SupertypeOf => self.sub().relate_with_variance... | //
// FIXME(#16847): This code is non-ideal because all these subtype
// relations wind up attributed to the same spans. We need
// to associate causes/spans with each of the relations in | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.