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
syscall_tests.rs
// TODO: Write a bunch more syscall-y tests to test that each syscall for each file/directory type // acts as we expect. use super::mount; use super::tests::digest_to_filepath; use crate::tests::make_dirs; use libc; use std::ffi::CString; use std::path::Path; use store::Store; use testutil::data::TestData; #[test] fn...
assert_eq!(test_bytes.string(), String::from_utf8(buf).unwrap()); } fn path_to_cstring(path: &Path) -> CString { CString::new(path.to_string_lossy().as_bytes().to_owned()).unwrap() } fn make_buffer(size: usize) -> Vec<u8> { let mut buf: Vec<u8> = Vec::new(); buf.resize(size, 0); buf }
assert!(fd > 0, "Bad fd {}", fd); let read_bytes = libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()); assert_eq!(test_bytes.len() as isize, read_bytes); assert_eq!(0, libc::close(fd)); }
random_line_split
hcx.rs
use crate::ich; use crate::middle::cstore::CrateStore; use crate::ty::{fast_reject, TyCtxt}; use rustc_ast as ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::Lrc; use rustc_hir as hir; use rustc_hir::def_...
} #[inline] pub fn with_node_id_hashing_mode<F: FnOnce(&mut Self)>( &mut self, mode: NodeIdHashingMode, f: F, ) { let prev = self.node_id_hashing_mode; self.node_id_hashing_mode = mode; f(self); self.node_id_hashing_mode = prev; } #[inlin...
let prev_hash_spans = self.hash_spans; self.hash_spans = hash_spans; f(self); self.hash_spans = prev_hash_spans;
random_line_split
hcx.rs
use crate::ich; use crate::middle::cstore::CrateStore; use crate::ty::{fast_reject, TyCtxt}; use rustc_ast as ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::Lrc; use rustc_hir as hir; use rustc_hir::def_...
() -> FxHashSet<Symbol> { debug_assert!(!ich::IGNORED_ATTRIBUTES.is_empty()); ich::IGNORED_ATTRIBUTES.iter().copied().collect() } /// This is the context state available during incr. comp. hashing. It contains /// enough information to transform `DefId`s and `HirId`s into stable `DefPath`s (i.e., /// a referen...
compute_ignored_attr_names
identifier_name
hcx.rs
use crate::ich; use crate::middle::cstore::CrateStore; use crate::ty::{fast_reject, TyCtxt}; use rustc_ast as ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::Lrc; use rustc_hir as hir; use rustc_hir::def_...
else { self.cstore.def_path_hash(def_id) } } #[inline] pub fn local_def_path_hash(&self, def_id: LocalDefId) -> DefPathHash { self.definitions.def_path_hash(def_id) } #[inline] pub fn hash_bodies(&self) -> bool { self.hash_bodies } #[inline] pu...
{ self.local_def_path_hash(def_id) }
conditional_block
control.rs
use std::sync::mpsc; use cgmath::{Rad}; use specs; use world as w; pub enum Event { EvThrust(f32), EvTurn(f32), } pub struct System { input: mpsc::Receiver<Event>, thrust: f32, turn: f32, } impl System { pub fn new(chan: mpsc::Receiver<Event>) -> System
fn check_input(&mut self) { loop { match self.input.try_recv() { Ok(Event::EvThrust(v)) => self.thrust = v, Ok(Event::EvTurn(v)) => self.turn = v, Err(_) => return, } } } } impl specs::System<super::Delta> for System { ...
{ System { input: chan, thrust: 0.0, turn: 0.0, } }
identifier_body
control.rs
use std::sync::mpsc; use cgmath::{Rad}; use specs; use world as w; pub enum Event { EvThrust(f32), EvTurn(f32), } pub struct System { input: mpsc::Receiver<Event>, thrust: f32, turn: f32, } impl System { pub fn new(chan: mpsc::Receiver<Event>) -> System { System { input: c...
self.check_input(); let (mut inertia, space, control) = arg.fetch(|w| (w.write::<w::Inertial>(), w.read::<w::Spatial>(), w.read::<w::Control>()) ); for (i, s, c) in (&mut inertia, &space, &control).iter() { let rotate = c.turn_speed * self.turn; i.angu...
fn run(&mut self, arg: specs::RunArg, time: super::Delta) { use specs::Join;
random_line_split
control.rs
use std::sync::mpsc; use cgmath::{Rad}; use specs; use world as w; pub enum Event { EvThrust(f32), EvTurn(f32), } pub struct
{ input: mpsc::Receiver<Event>, thrust: f32, turn: f32, } impl System { pub fn new(chan: mpsc::Receiver<Event>) -> System { System { input: chan, thrust: 0.0, turn: 0.0, } } fn check_input(&mut self) { loop { match self.i...
System
identifier_name
lib.rs
#![feature(rustc_private, plugin_registrar)] #![warn(missing_docs)] //! rebind_plugins //! ============== //! //! A compiler plugin which complements the `rebind` crate by providing the //! `#[derive(Action)]` //! annotation. //! //! Example //! ------- //! //! ``` //! #![feature(plugin)] //! #![plugin(rebind_macros)]...
use rustc::plugin::Registry; use syntax::parse::token::intern; use syntax::ext::base::SyntaxExtension; use derive_action::expand_derive_action_annotation; #[plugin_registrar] #[doc(hidden)] pub fn plugin_registrar(registry: &mut Registry) { registry.register_syntax_extension(intern("derive_Action"), ...
mod derive_action;
random_line_split
lib.rs
#![feature(rustc_private, plugin_registrar)] #![warn(missing_docs)] //! rebind_plugins //! ============== //! //! A compiler plugin which complements the `rebind` crate by providing the //! `#[derive(Action)]` //! annotation. //! //! Example //! ------- //! //! ``` //! #![feature(plugin)] //! #![plugin(rebind_macros)]...
(registry: &mut Registry) { registry.register_syntax_extension(intern("derive_Action"), SyntaxExtension::MultiDecorator(Box::new(expand_derive_action_annotation))); }
plugin_registrar
identifier_name
lib.rs
#![feature(rustc_private, plugin_registrar)] #![warn(missing_docs)] //! rebind_plugins //! ============== //! //! A compiler plugin which complements the `rebind` crate by providing the //! `#[derive(Action)]` //! annotation. //! //! Example //! ------- //! //! ``` //! #![feature(plugin)] //! #![plugin(rebind_macros)]...
{ registry.register_syntax_extension(intern("derive_Action"), SyntaxExtension::MultiDecorator(Box::new(expand_derive_action_annotation))); }
identifier_body
history.rs
/// Represents a undo/redo history. pub struct History<T> { undo_hist: Vec<T>, current: T, redo_hist: Vec<T>, } impl<T: Clone> History<T> { /// Create a new `History` with the given `initial` value. pub fn new(initial: T) -> Self { History { undo_hist: vec![], curren...
(&mut self) { if let Some(last) = self.redo_hist.pop() { self.undo_hist.push(self.current.clone()); self.current = last; } } /// Add a new element to the `History`. /// The new element will become the current element, the redo history will be cleared. pub fn add(...
redo
identifier_name
history.rs
/// Represents a undo/redo history. pub struct History<T> { undo_hist: Vec<T>, current: T, redo_hist: Vec<T>, } impl<T: Clone> History<T> { /// Create a new `History` with the given `initial` value. pub fn new(initial: T) -> Self { History { undo_hist: vec![], curren...
/// Redo. Will do nothing if no redo history exists. pub fn redo(&mut self) { if let Some(last) = self.redo_hist.pop() { self.undo_hist.push(self.current.clone()); self.current = last; } } /// Add a new element to the `History`. /// The new element will bec...
{ if let Some(last) = self.undo_hist.pop() { self.redo_hist.push(self.current.clone()); self.current = last; } }
identifier_body
history.rs
/// Represents a undo/redo history. pub struct History<T> { undo_hist: Vec<T>, current: T, redo_hist: Vec<T>, } impl<T: Clone> History<T> { /// Create a new `History` with the given `initial` value. pub fn new(initial: T) -> Self { History { undo_hist: vec![], curren...
} /// Add a new element to the `History`. /// The new element will become the current element, the redo history will be cleared. pub fn add(&mut self, element: T) { self.undo_hist.push(self.current.clone()); self.current = element; self.redo_hist = vec![]; } /// Get th...
{ self.undo_hist.push(self.current.clone()); self.current = last; }
conditional_block
history.rs
/// Represents a undo/redo history. pub struct History<T> { undo_hist: Vec<T>, current: T, redo_hist: Vec<T>, }
History { undo_hist: vec![], current: initial, redo_hist: vec![], } } /// Undo. Will do nothing if no undo history exists. pub fn undo(&mut self) { if let Some(last) = self.undo_hist.pop() { self.redo_hist.push(self.current.clone()); ...
impl<T: Clone> History<T> { /// Create a new `History` with the given `initial` value. pub fn new(initial: T) -> Self {
random_line_split
mod.rs
pub use child_process_terminator::ChildProcessTerminator; use std::env; use std::process::Command; use std::thread::sleep; use std::time::Duration; mod child_process_terminator; fn rostopic_listing_succeeds() -> bool { return Command::new("rostopic") .arg("list") .output() .unwrap() .s...
fn run_roscore(port: u32) -> ChildProcessTerminator { env::set_var("ROS_MASTER_URI", format!("http://localhost:{}", port)); let roscore = ChildProcessTerminator::spawn( &mut Command::new("roscore").arg("-p").arg(format!("{}", port)), ); await_roscore(); roscore } pub fn run_roscore_for(fe...
{ while !rostopic_listing_succeeds() { sleep(Duration::from_millis(100)); } }
identifier_body
mod.rs
pub use child_process_terminator::ChildProcessTerminator; use std::env; use std::process::Command; use std::thread::sleep; use std::time::Duration; mod child_process_terminator; fn
() -> bool { return Command::new("rostopic") .arg("list") .output() .unwrap() .status .success(); } fn await_roscore() { while!rostopic_listing_succeeds() { sleep(Duration::from_millis(100)); } } fn run_roscore(port: u32) -> ChildProcessTerminator { env::set_...
rostopic_listing_succeeds
identifier_name
mod.rs
pub use child_process_terminator::ChildProcessTerminator; use std::env; use std::process::Command; use std::thread::sleep; use std::time::Duration; mod child_process_terminator; fn rostopic_listing_succeeds() -> bool { return Command::new("rostopic") .arg("list") .output() .unwrap() .s...
fn run_roscore(port: u32) -> ChildProcessTerminator { env::set_var("ROS_MASTER_URI", format!("http://localhost:{}", port)); let roscore = ChildProcessTerminator::spawn( &mut Command::new("roscore").arg("-p").arg(format!("{}", port)), ); await_roscore(); roscore } pub fn run_roscore_for(fea...
sleep(Duration::from_millis(100)); } }
random_line_split
test_sup.rs
// Copyright (c) 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 // // Unless required by applicable law or agreed to in writing, software // distributed ...
//
random_line_split
test_sup.rs
// Copyright (c) 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 // // Unless r...
/// The equivalent of performing `hab apply` with the given /// configuration. pub fn apply_config<T>(&mut self, toml_config: T) where T: ToString, { self.butterfly_client.apply(toml_config.to_string()) } } // We kill the Supervisor so you don't have to! We also free up the //...
{ let child = self.cmd.spawn().expect("Couldn't start the Supervisor!"); self.process = Some(child); }
identifier_body
test_sup.rs
// Copyright (c) 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 // // Unless r...
let bc = test_butterfly::Client::new(&pkg_name, &service_group, butterfly_port); TestSup { hab_root: fs_root.as_ref().to_path_buf(), origin_name: origin, package_name: pkg_name, service_group: service_group.to_string(), http_port: http_port,...
{ cmd.stdout(Stdio::null()); cmd.stderr(Stdio::null()); }
conditional_block
test_sup.rs
// Copyright (c) 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 // // Unless r...
(tries: u16) -> u16 { if tries == 0 { panic!("Couldn't find an unclaimed port for the test Supervisor!") } let p = random_port(); match TcpListener::bind(format!("127.0.0.1:{}", p)) { Ok(_listener) => { // The system hasn't bound it. Now we make sure none of // ou...
unclaimed_port
identifier_name
copy_propagation_arg.rs
// Check that DestinationPropagation does not propagate an assignment to a function argument // (doing so can break usages of the original argument value) // compile-flags: -Zunsound-mir-opts fn dummy(x: u8) -> u8 { x } // EMIT_MIR copy_propagation_arg.foo.DestinationPropagation.diff fn foo(mut x: u8)
// EMIT_MIR copy_propagation_arg.bar.DestinationPropagation.diff fn bar(mut x: u8) { dummy(x); x = 5; } // EMIT_MIR copy_propagation_arg.baz.DestinationPropagation.diff fn baz(mut x: i32) { // self-assignment to a function argument should be eliminated x = x; } // EMIT_MIR copy_propagation_arg.arg_s...
{ // calling `dummy` to make a use of `x` that copyprop cannot eliminate x = dummy(x); // this will assign a local to `x` }
identifier_body
copy_propagation_arg.rs
// Check that DestinationPropagation does not propagate an assignment to a function argument // (doing so can break usages of the original argument value) // compile-flags: -Zunsound-mir-opts fn dummy(x: u8) -> u8 { x } // EMIT_MIR copy_propagation_arg.foo.DestinationPropagation.diff fn
(mut x: u8) { // calling `dummy` to make a use of `x` that copyprop cannot eliminate x = dummy(x); // this will assign a local to `x` } // EMIT_MIR copy_propagation_arg.bar.DestinationPropagation.diff fn bar(mut x: u8) { dummy(x); x = 5; } // EMIT_MIR copy_propagation_arg.baz.DestinationPropagation.di...
foo
identifier_name
copy_propagation_arg.rs
// Check that DestinationPropagation does not propagate an assignment to a function argument // (doing so can break usages of the original argument value) // compile-flags: -Zunsound-mir-opts
// EMIT_MIR copy_propagation_arg.foo.DestinationPropagation.diff fn foo(mut x: u8) { // calling `dummy` to make a use of `x` that copyprop cannot eliminate x = dummy(x); // this will assign a local to `x` } // EMIT_MIR copy_propagation_arg.bar.DestinationPropagation.diff fn bar(mut x: u8) { dummy(x); x...
fn dummy(x: u8) -> u8 { x }
random_line_split
stubs.rs
// Copyright 2020 The Exonum Team // // 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 i...
/// Stub that creates unsigned transactions. /// /// # Examples /// /// ``` /// # use exonum_derive::*; /// use exonum::runtime::{AnyTx, InstanceId}; /// use exonum_rust_runtime::TxStub; /// /// #[exonum_interface] /// trait MyInterface<Ctx> { /// type Output; /// #[interface_method(id = 0)] /// fn publish_...
) -> Self::Output; }
random_line_split
stubs.rs
// Copyright 2020 The Exonum Team // // 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 i...
<'a> { /// Name of the interface. pub interface_name: &'a str, /// Numerical ID of the method. pub id: MethodId, } impl<'a> MethodDescriptor<'a> { /// Creates the descriptor based on provided properties. pub const fn new(interface_name: &'a str, id: MethodId) -> Self { Self { interface_...
MethodDescriptor
identifier_name
stubs.rs
// Copyright 2020 The Exonum Team // // 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 i...
// It's also possible to define new stubs (not necessarily in this crate). For example, // this stub outputs the size of the payload. struct PayloadSize; impl GenericCall<()> for PayloadSize { type Output = usize; fn generic_call( &self, _context: (), ...
{ const SERVICE_ID: InstanceId = 100; let keypair = KeyPair::random(); let tx: Verified<AnyTx> = keypair.create_wallet(SERVICE_ID, CreateWallet::default()); assert_eq!(tx.payload().call_info.method_id, 0); let other_tx = keypair.transfer(SERVICE_ID, Transfer::default()); ...
identifier_body
hex.rs
#![allow(deprecated)] use std::fs::File; use std::hash::{Hash, Hasher, SipHasher}; use std::io::Read; pub fn to_hex(num: u64) -> String { hex::encode(&[ (num >> 0) as u8, (num >> 8) as u8, (num >> 16) as u8, (num >> 24) as u8, (num >> 32) as u8, (num >> 40) as u8, ...
pub fn hash_u64_file(mut file: &File) -> std::io::Result<u64> { let mut hasher = SipHasher::new_with_keys(0, 0); let mut buf = [0; 64 * 1024]; loop { let n = file.read(&mut buf)?; if n == 0 { break; } hasher.write(&buf[..n]); } Ok(hasher.finish()) } pub...
{ let mut hasher = SipHasher::new(); hashable.hash(&mut hasher); hasher.finish() }
identifier_body
hex.rs
#![allow(deprecated)] use std::fs::File; use std::hash::{Hash, Hasher, SipHasher}; use std::io::Read; pub fn to_hex(num: u64) -> String { hex::encode(&[ (num >> 0) as u8, (num >> 8) as u8, (num >> 16) as u8, (num >> 24) as u8, (num >> 32) as u8, (num >> 40) as u8, ...
hasher.write(&buf[..n]); } Ok(hasher.finish()) } pub fn short_hash<H: Hash>(hashable: &H) -> String { to_hex(hash_u64(hashable)) }
{ break; }
conditional_block
hex.rs
#![allow(deprecated)] use std::fs::File; use std::hash::{Hash, Hasher, SipHasher}; use std::io::Read; pub fn to_hex(num: u64) -> String { hex::encode(&[ (num >> 0) as u8, (num >> 8) as u8, (num >> 16) as u8, (num >> 24) as u8, (num >> 32) as u8, (num >> 40) as u8, ...
hashable.hash(&mut hasher); hasher.finish() } pub fn hash_u64_file(mut file: &File) -> std::io::Result<u64> { let mut hasher = SipHasher::new_with_keys(0, 0); let mut buf = [0; 64 * 1024]; loop { let n = file.read(&mut buf)?; if n == 0 { break; } hasher.w...
} pub fn hash_u64<H: Hash>(hashable: H) -> u64 { let mut hasher = SipHasher::new();
random_line_split
hex.rs
#![allow(deprecated)] use std::fs::File; use std::hash::{Hash, Hasher, SipHasher}; use std::io::Read; pub fn to_hex(num: u64) -> String { hex::encode(&[ (num >> 0) as u8, (num >> 8) as u8, (num >> 16) as u8, (num >> 24) as u8, (num >> 32) as u8, (num >> 40) as u8, ...
<H: Hash>(hashable: &H) -> String { to_hex(hash_u64(hashable)) }
short_hash
identifier_name
htmlvideoelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLVideoElementBinding; use dom::bindings::codegen::InheritTypes::HTMLVideo...
}
prefix: Option<DOMString>, document: &Document) -> Root<HTMLVideoElement> { let element = HTMLVideoElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLVideoElementBinding::Wrap) }
random_line_split
htmlvideoelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLVideoElementBinding; use dom::bindings::codegen::InheritTypes::HTMLVideo...
(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLVideoElement> { let element = HTMLVideoElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLVideoElementBinding::Wrap) } }
new
identifier_name
htmlvideoelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLVideoElementBinding; use dom::bindings::codegen::InheritTypes::HTMLVideo...
} impl HTMLVideoElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLVideoElement { HTMLVideoElement { htmlmediaelement: HTMLMediaElement::new_inherited(HTMLMediaElementTypeId::HTMLVideoElement, localName, prefix, document) ...
{ *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLMediaElement( HTMLMediaElementTypeId::HTML...
identifier_body
mod.rs
/* Copyright (C) 2017 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...
(input: *const libc::uint8_t, len: libc::uint32_t) -> u16 { let buf = unsafe{std::slice::from_raw_parts(input, len as usize)}; match ftp_pasv_response(buf) { nom::IResult::Done(_, dport) => { return dport; } nom::IResult::Incomplete(_) => { let buf = unsafe{std::s...
rs_ftp_pasv_response
identifier_name
mod.rs
/* Copyright (C) 2017 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 buf = unsafe{std::slice::from_raw_parts(input, len as usize)}; match ftp_epsv_response(buf) { nom::IResult::Done(_, dport) => { return dport; }, nom::IResult::Incomplete(_) => { let buf = unsafe{std::slice::from_raw_parts(input, len as usize)}; S...
identifier_body
mod.rs
/* Copyright (C) 2017 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...
#[no_mangle] pub extern "C" fn rs_ftp_pasv_response(input: *const libc::uint8_t, len: libc::uint32_t) -> u16 { let buf = unsafe{std::slice::from_raw_parts(input, len as usize)}; match ftp_pasv_response(buf) { nom::IResult::Done(_, dport) => { return dport; } nom::IResult::I...
) );
random_line_split
regions-close-object-into-object-3.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 ...
() {}
main
identifier_name
regions-close-object-into-object-3.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 h<'a, T, U>(v: Box<A<U>+'static>) -> Box<X+'static> { box B(&*v) as Box<X> //~ ERROR `*v` does not live long enough } fn main() {}
trait X : PhantomFn<Self> {} impl<'a, T> X for B<'a, T> {}
random_line_split
regions-close-object-into-object-3.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 ...
{}
identifier_body
stars.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
pub fn tick_animation(&mut self) -> bool { if self.visible { self.anim += 1; } self.visible } } // ========================================================================= //
{ if self.visible { let mut canvas = canvas.subcanvas(self.rect); canvas.clear((0, 0, 0)); self.draw_layer(16, 8, 63, &mut canvas); self.draw_layer(32, 16, 127, &mut canvas); } }
identifier_body
stars.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
} pub fn tick_animation(&mut self) -> bool { if self.visible { self.anim += 1; } self.visible } } // ========================================================================= //
{ let mut canvas = canvas.subcanvas(self.rect); canvas.clear((0, 0, 0)); self.draw_layer(16, 8, 63, &mut canvas); self.draw_layer(32, 16, 127, &mut canvas); }
conditional_block
stars.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
let scroll = (self.anim * speed) % modulus; let mut yoff = 0; while yoff < modulus { let mut xoff = 0; while xoff < modulus { let x = ((xoff + scroll) % modulus) - spacing as i32 + MovingStars::rand(spacing, &mut seed); ...
let mut seed = (123456789, 987654321); let star_width = (speed / 2) as u32; let modulus = (self.rect.width() + spacing) as i32;
random_line_split
stars.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
(left: i32, top: i32, width: u32, height: u32) -> MovingStars { MovingStars { rect: Rect::new(left, top, width, height), anim: 0, visible: false, } } pub fn set_visible(&mut self, visible: bool) { self.visible = visible; } fn rand(range: u32,...
new
identifier_name
syntax-extension-source-utils.rs
// Copyright 2012-2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICEN...
} } macro_rules! indirect_line { () => ( line!() ) } pub fn main() { assert_eq!(line!(), 25); assert!((column!() == 4)); assert_eq!(indirect_line!(), 27); assert!((file!().ends_with("syntax-extension-source-utils.rs"))); assert_eq!(stringify!((2*3) + 5).to_string(), "( 2 * 3 ) + 5".to_string(...
{ (module_path!()).to_string() }
identifier_body
syntax-extension-source-utils.rs
// Copyright 2012-2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICEN...
assert!( include_bytes!("syntax-extension-source-utils-files/includeme.fragment") [1] == (42 as u8)); // '*' // The Windows tests are wrapped in an extra module for some reason assert!((m1::m2::where_am_i().ends_with("m1::m2"))); assert!(match (45, "( 2 * 3 ) + 5") { (line!(), s...
assert!( include_str!("syntax-extension-source-utils-files/includeme.\ fragment").to_string() .as_slice() .starts_with("/* this is for "));
random_line_split
syntax-extension-source-utils.rs
// Copyright 2012-2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICEN...
() { assert_eq!(line!(), 25); assert!((column!() == 4)); assert_eq!(indirect_line!(), 27); assert!((file!().ends_with("syntax-extension-source-utils.rs"))); assert_eq!(stringify!((2*3) + 5).to_string(), "( 2 * 3 ) + 5".to_string()); assert!(include!("syntax-extension-source-utils-files/includeme...
main
identifier_name
finder.rs
use error::*; #[cfg(windows)] use helper::has_executable_extension; use std::env; use std::ffi::OsStr; #[cfg(windows)] use std::ffi::OsString; use std::iter; use std::path::{Path, PathBuf}; pub trait Checker { fn is_valid(&self, path: &Path) -> bool; } trait PathExt { fn has_separator(&self) -> bool; fn ...
#[cfg(unix)] fn append_extension<P>(paths: P) -> impl IntoIterator<Item = PathBuf> where P: IntoIterator<Item = PathBuf>, { paths } #[cfg(windows)] fn append_extension<P>(paths: P) -> impl IntoIterator<Item = PathBuf> where P: IntoIterator<Item = PathBuf>, ...
{ let new_paths = paths.into_iter().map(move |p| p.join(binary_name.clone())); Self::append_extension(new_paths) }
identifier_body
finder.rs
use error::*; #[cfg(windows)] use helper::has_executable_extension; use std::env; use std::ffi::OsStr; #[cfg(windows)] use std::ffi::OsString; use std::iter; use std::path::{Path, PathBuf}; pub trait Checker { fn is_valid(&self, path: &Path) -> bool; } trait PathExt { fn has_separator(&self) -> bool; fn ...
} // can't find any binary Err(Error::CannotFindBinaryPath) } fn cwd_search_candidates<C>(binary_name: PathBuf, cwd: C) -> impl IntoIterator<Item = PathBuf> where C: AsRef<Path>, { let path = binary_name.to_absolute(cwd); Self::append_extension(iter::o...
{ return Ok(p); }
conditional_block
finder.rs
use error::*; #[cfg(windows)] use helper::has_executable_extension; use std::env; use std::ffi::OsStr; #[cfg(windows)] use std::ffi::OsString; use std::iter; use std::path::{Path, PathBuf}; pub trait Checker { fn is_valid(&self, path: &Path) -> bool; } trait PathExt { fn has_separator(&self) -> bool; fn ...
pub struct Finder; impl Finder { pub fn new() -> Finder { Finder } pub fn find<T, U, V>( &self, binary_name: T, paths: Option<U>, cwd: V, binary_checker: &dyn Checker, ) -> Result<PathBuf> where T: AsRef<OsStr>, U: AsRef<OsStr>, ...
new_path } } }
random_line_split
finder.rs
use error::*; #[cfg(windows)] use helper::has_executable_extension; use std::env; use std::ffi::OsStr; #[cfg(windows)] use std::ffi::OsString; use std::iter; use std::path::{Path, PathBuf}; pub trait Checker { fn is_valid(&self, path: &Path) -> bool; } trait PathExt { fn has_separator(&self) -> bool; fn ...
<P>(self, cwd: P) -> PathBuf where P: AsRef<Path>, { if self.is_absolute() { self } else { let mut new_path = PathBuf::from(cwd.as_ref()); new_path.push(self); new_path } } } pub struct Finder; impl Finder { pub fn new() -...
to_absolute
identifier_name
break.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 mut i = 0; while i < 20 { i += 1; if i == 10 { break; } } assert_eq!(i, 10); loop { i += 1; if i == 20 { break; } } assert_eq!(i, 20); let xs = [1, 2, 3, 4, 5, 6]; for x in &xs { if *x == 3 { break; } assert!((*x <= 3)); } i = 0; while i < 10 { i += 1; if i % 2 =...
main
identifier_name
break.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 ...
assert!((i % 2!= 0)); } i = 0; loop { i += 1; if i % 2 == 0 { continue; } assert!((i % 2!= 0)); if i >= 10 { break; } } let ys = vec![1, 2, 3, 4, 5, 6]; for x in &ys { if *x % 2 == 0 { continue; } assert!((*x % 2!= 0)); } }
{ continue; }
conditional_block
break.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 ...
assert!((*x % 2!= 0)); } }
{ let mut i = 0; while i < 20 { i += 1; if i == 10 { break; } } assert_eq!(i, 10); loop { i += 1; if i == 20 { break; } } assert_eq!(i, 20); let xs = [1, 2, 3, 4, 5, 6]; for x in &xs { if *x == 3 { break; } assert!((*x <= 3)); } i = 0; while i < 10 { i += 1; if i % 2 == 0...
identifier_body
issue-27282-mutate-before-diverging-arm-3.rs
// This is testing an attempt to corrupt the discriminant of the match // arm in a guard, followed by an attempt to continue matching on that // corrupted discriminant in the remaining match arms. // // Basically this is testing that our new NLL feature of emitting a // fake read on each match arm is catching cases lik...
Some(&_) if { // ForceFnOnce needed to exploit #27282 (|| { *x = &None; drop(force_fn_once); })(); //~^ ERROR cannot mutably borrow `x` in match guard [E0510] false } => {} Some(&a) if { // this binds to garbage if we've corrupted discriminant ...
None => panic!("unreachable"),
random_line_split
issue-27282-mutate-before-diverging-arm-3.rs
// This is testing an attempt to corrupt the discriminant of the match // arm in a guard, followed by an attempt to continue matching on that // corrupted discriminant in the remaining match arms. // // Basically this is testing that our new NLL feature of emitting a // fake read on each match arm is catching cases lik...
() { let mut x = &mut &Some(&2); let force_fn_once = ForceFnOnce; match **x { None => panic!("unreachable"), Some(&_) if { // ForceFnOnce needed to exploit #27282 (|| { *x = &None; drop(force_fn_once); })(); //~^ ERROR cannot mutably borrow `x` in match gu...
main
identifier_name
issue-27282-mutate-before-diverging-arm-3.rs
// This is testing an attempt to corrupt the discriminant of the match // arm in a guard, followed by an attempt to continue matching on that // corrupted discriminant in the remaining match arms. // // Basically this is testing that our new NLL feature of emitting a // fake read on each match arm is catching cases lik...
{ let mut x = &mut &Some(&2); let force_fn_once = ForceFnOnce; match **x { None => panic!("unreachable"), Some(&_) if { // ForceFnOnce needed to exploit #27282 (|| { *x = &None; drop(force_fn_once); })(); //~^ ERROR cannot mutably borrow `x` in match guard...
identifier_body
lexical-scope-in-for-loop.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { let range = [1i, 2, 3]; let x = 1000000i; // wan meeeljen doollaars! for &x in range.iter() { zzz(); // #break sentinel(); let x = -1i * x; zzz(); // #break sentinel(); } zzz(); // #break sentinel(); } fn zzz() {()} fn sentinel() {()}
main
identifier_name
lexical-scope-in-for-loop.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn sentinel() {()}
{()}
identifier_body
lexical-scope-in-for-loop.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
for &x in range.iter() { zzz(); // #break sentinel(); let x = -1i * x; zzz(); // #break sentinel(); } zzz(); // #break sentinel(); } fn zzz() {()} fn sentinel() {()}
let range = [1i, 2, 3]; let x = 1000000i; // wan meeeljen doollaars!
random_line_split
report.rs
use lalafell::{ commands::{ MentionOrId, prelude::*, }, error::*, }; use rand::{ Rng, thread_rng, distributions::Alphanumeric, }; use serenity::model::channel::{ChannelType, PermissionOverwrite, PermissionOverwriteType}; use serenity::model::permissions::Permissions; use unicase::UniCase; use std:...
} }
random_line_split
report.rs
use lalafell::{ commands::{ MentionOrId, prelude::*, }, error::*, }; use rand::{ Rng, thread_rng, distributions::Alphanumeric, }; use serenity::model::channel::{ChannelType, PermissionOverwrite, PermissionOverwriteType}; use serenity::model::permissions::Permissions; use unicase::UniCase; use std:...
(&self, ctx: &Context, msg: &Message, guild_id: GuildId, _: Arc<RwLock<GuildChannel>>, params: &[&str]) -> CommandResult<'a> { let member = guild_id.member(&ctx, &msg.author).chain_err(|| "could not get member")?; if!member.permissions(&ctx).chain_err(|| "could not get permissions")?.manage_roles() { retu...
run
identifier_name
main.rs
#[macro_use] extern crate lazy_static; use regex::Regex; use std::cmp::min; use std::env; use std::error::Error; use std::fs; lazy_static! { static ref LINE_REGEX: Regex = Regex::new(r"(?P<x1>[0-9]+),(?P<y1>[0-9]+) -> (?P<x2>[0-9]+),(?P<y2>[0-9]+)").unwrap(); } fn main() { run().unwrap(); } fn get_l...
} for _ in 0..new_fish_count { fishes.push(8); } } Ok(fishes.len()) } fn part2(lines: &Vec<String>) -> Result<u64, Box<dyn Error>> { let fishes: Vec<u32> = lines .get(0) .unwrap() .split(",") .map(|n| n.parse().unwrap()) .collect(); ...
{ *fish -= 1; }
conditional_block
main.rs
#[macro_use] extern crate lazy_static; use regex::Regex; use std::cmp::min; use std::env; use std::error::Error; use std::fs; lazy_static! { static ref LINE_REGEX: Regex = Regex::new(r"(?P<x1>[0-9]+),(?P<y1>[0-9]+) -> (?P<x2>[0-9]+),(?P<y2>[0-9]+)").unwrap(); } fn main() { run().unwrap(); } fn get_l...
fn part1(lines: &Vec<String>) -> Result<usize, Box<dyn Error>> { let mut fishes: Vec<u32> = lines .get(0) .unwrap() .split(",") .map(|n| n.parse().unwrap()) .collect(); for _ in 1..=80 { let mut new_fish_count = 0; for fish in fishes.iter_mut() { ...
{ let args: Vec<String> = env::args().collect(); let default_fname = "input.txt".into(); let fname = args.get(1).unwrap_or(&default_fname); let file_string = fs::read_to_string(fname).expect(&format!("Expected file named: {}", fname)); let lines: Vec<String> = file_string.trim().split("\n").map(|s| ...
identifier_body
main.rs
#[macro_use] extern crate lazy_static; use regex::Regex; use std::cmp::min; use std::env; use std::error::Error; use std::fs; lazy_static! { static ref LINE_REGEX: Regex = Regex::new(r"(?P<x1>[0-9]+),(?P<y1>[0-9]+) -> (?P<x2>[0-9]+),(?P<y2>[0-9]+)").unwrap(); } fn main() { run().unwrap(); } fn get_l...
(lines: &Vec<String>) -> Result<usize, Box<dyn Error>> { let mut fishes: Vec<u32> = lines .get(0) .unwrap() .split(",") .map(|n| n.parse().unwrap()) .collect(); for _ in 1..=80 { let mut new_fish_count = 0; for fish in fishes.iter_mut() { if *fish ...
part1
identifier_name
main.rs
#[macro_use] extern crate lazy_static; use regex::Regex; use std::cmp::min; use std::env; use std::error::Error; use std::fs; lazy_static! { static ref LINE_REGEX: Regex = Regex::new(r"(?P<x1>[0-9]+),(?P<y1>[0-9]+) -> (?P<x2>[0-9]+),(?P<y2>[0-9]+)").unwrap(); } fn main() { run().unwrap(); } fn get_l...
Ok(()) }
println!("Part 2: {}", part2(&lines)?);
random_line_split
iron_middleware.rs
extern crate iron; extern crate hornet; use std::sync::Mutex; use hornet::client::Client; use hornet::client::metric::*; use iron::prelude::*; use iron::middleware::BeforeMiddleware; use iron::method::Method; use iron::status; /* this examples demonstrates usage of CountVector metric embedded in Iron BeforeMi...
} Ok(()) } fn catch(&self, _: &mut Request, _: IronError) -> IronResult<()> { Ok(()) } } fn main() { let method_counter = MethodCounter::new(); let client = Client::new("localhost.methods").unwrap(); { let mut metric = method_counter.metric.lock().unwrap(); ...
{ let mut counter = self.metric.lock().unwrap(); counter.up(&method_str(&req.method)).unwrap().unwrap(); }
conditional_block
iron_middleware.rs
extern crate iron; extern crate hornet; use std::sync::Mutex; use hornet::client::Client; use hornet::client::metric::*; use iron::prelude::*; use iron::middleware::BeforeMiddleware; use iron::method::Method; use iron::status; /* this examples demonstrates usage of CountVector metric embedded in Iron BeforeMi...
{ let method_counter = MethodCounter::new(); let client = Client::new("localhost.methods").unwrap(); { let mut metric = method_counter.metric.lock().unwrap(); client.export(&mut [&mut *metric]).unwrap(); } let mut chain = Chain::new(|_: &mut Request| { Ok(Response::with((st...
identifier_body
iron_middleware.rs
extern crate iron; extern crate hornet; use std::sync::Mutex; use hornet::client::Client; use hornet::client::metric::*; use iron::prelude::*; use iron::middleware::BeforeMiddleware; use iron::method::Method; use iron::status; /* this examples demonstrates usage of CountVector metric embedded in Iron BeforeMi...
let mut metric = method_counter.metric.lock().unwrap(); client.export(&mut [&mut *metric]).unwrap(); } let mut chain = Chain::new(|_: &mut Request| { Ok(Response::with((status::Ok, "Hello World!"))) }); chain.link_before(method_counter); println!("Listening on http://{}", U...
fn main() { let method_counter = MethodCounter::new(); let client = Client::new("localhost.methods").unwrap(); {
random_line_split
iron_middleware.rs
extern crate iron; extern crate hornet; use std::sync::Mutex; use hornet::client::Client; use hornet::client::metric::*; use iron::prelude::*; use iron::middleware::BeforeMiddleware; use iron::method::Method; use iron::status; /* this examples demonstrates usage of CountVector metric embedded in Iron BeforeMi...
() { let method_counter = MethodCounter::new(); let client = Client::new("localhost.methods").unwrap(); { let mut metric = method_counter.metric.lock().unwrap(); client.export(&mut [&mut *metric]).unwrap(); } let mut chain = Chain::new(|_: &mut Request| { Ok(Response::with(...
main
identifier_name
planar_camera.rs
use crate::event::WindowEvent; use crate::resource::ShaderUniform; use crate::window::Canvas; use na::{Matrix3, Point2, Vector2}; /// Trait every 2D camera must implement. pub trait PlanarCamera { /* * Event handling. */ /// Handle a mouse event. fn handle_event(&mut self, canvas: &Canvas, event:...
/// Computes the 2D world-space coordiates corresponding to the given screen-space coordiates. fn unproject(&self, window_coord: &Point2<f32>, window_size: &Vector2<f32>) -> Point2<f32>; }
&self, proj: &mut ShaderUniform<Matrix3<f32>>, view: &mut ShaderUniform<Matrix3<f32>>, );
random_line_split
dispatch.rs
// Copyright 2015, 2016 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 la...
{ match payload { RpcConfirmationPayload::SendTransaction(request) => { ConfirmationPayload::SendTransaction(fill_optional_fields(request.into(), client, miner)) }, RpcConfirmationPayload::SignTransaction(request) => { ConfirmationPayload::SignTransaction(fill_optional_fields(request.into(), client, miner...
identifier_body
dispatch.rs
// Copyright 2015, 2016 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 la...
<C, M>(client: &C, miner: &M, signed_transaction: PendingTransaction) -> Result<H256, Error> where C: MiningBlockChainClient, M: MinerService { let hash = signed_transaction.transaction.hash(); miner.import_own_transaction(client, signed_transaction) .map_err(errors::from_transaction_error) .map(|_| hash) } pu...
dispatch_transaction
identifier_name
dispatch.rs
// Copyright 2015, 2016 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 la...
Password(String), Token(AccountToken), } #[derive(Debug)] pub enum WithToken<T: Debug> { No(T), Yes(T, AccountToken), } impl<T: Debug> Deref for WithToken<T> { type Target = T; fn deref(&self) -> &Self::Target { match *self { WithToken::No(ref v) => v, WithToken::Yes(ref v, _) => v, } } } impl<T: D...
pub enum SignWith { Nothing,
random_line_split
device.rs
use crate::cpu::CPU; use crate::keypad::KeypadKey; use crate::printer::GbPrinter; use crate::sound; use crate::StrResult; pub struct
{ cpu: CPU<'static>, } fn stdoutprinter(v: u8) -> Option<u8> { use std::io::Write; print!("{}", v as char); let _ = ::std::io::stdout().flush(); None } impl Device { pub fn new(romname: &str, skip_checksum: bool) -> StrResult<Device> { CPU::new(romname, None, skip_checksum).map(|cpu...
Device
identifier_name
device.rs
use crate::cpu::CPU; use crate::keypad::KeypadKey; use crate::printer::GbPrinter; use crate::sound; use crate::StrResult; pub struct Device { cpu: CPU<'static>, } fn stdoutprinter(v: u8) -> Option<u8> { use std::io::Write; print!("{}", v as char); let _ = ::std::io::stdout().flush(); None } imp...
pub fn romname(&self) -> String { self.cpu.mmu.mbc.romname() } }
{ self.cpu.mmu.keypad.keydown(key); }
identifier_body
device.rs
use crate::cpu::CPU; use crate::keypad::KeypadKey; use crate::printer::GbPrinter; use crate::sound; use crate::StrResult; pub struct Device { cpu: CPU<'static>, } fn stdoutprinter(v: u8) -> Option<u8> { use std::io::Write; print!("{}", v as char); let _ = ::std::io::stdout().flush(); None } imp...
else { self.cpu.mmu.serial.unset_callback(); } } pub fn attach_printer(&mut self) { let mut printer = GbPrinter::new(); let printfun = move |v: u8| -> Option<u8> { Some(printer.send(v)) }; self.cpu.mmu.serial.set_callback(Box::new(print...
{ self.cpu.mmu.serial.set_callback(Box::new(stdoutprinter)); }
conditional_block
device.rs
use crate::cpu::CPU; use crate::keypad::KeypadKey; use crate::printer::GbPrinter; use crate::sound; use crate::StrResult; pub struct Device { cpu: CPU<'static>, } fn stdoutprinter(v: u8) -> Option<u8> { use std::io::Write; print!("{}", v as char); let _ = ::std::io::stdout().flush(); None } imp...
Some(printer.send(v)) }; self.cpu.mmu.serial.set_callback(Box::new(printfun)); } pub fn check_and_reset_gpu_updated(&mut self) -> bool { let result = self.cpu.mmu.gpu.updated; self.cpu.mmu.gpu.updated = false; result } pub fn get_gpu_data(&self) -> ...
pub fn attach_printer(&mut self) { let mut printer = GbPrinter::new(); let printfun = move |v: u8| -> Option<u8> {
random_line_split
impls.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
impl AsRawSocket for TcpBuilder { fn as_raw_socket(&self) -> SOCKET { // TODO: this unwrap() is very bad self.as_inner().borrow().as_ref().unwrap().as_inner().raw() } } impl FromRawSocket for UdpBuilder { unsafe fn from_raw_socket(fd: SOCKET) -> UdpBuilder { let sock = sys::Socket:...
random_line_split
impls.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(fd: SOCKET) -> UdpBuilder { let sock = sys::Socket::from_inner(fd); UdpBuilder::from_inner(Socket::from_inner(sock)) } } impl AsRawSocket for UdpBuilder { fn as_raw_socket(&self) -> SOCKET { // TODO: this unwrap() is very bad self.as_inner().borrow().as_ref().unwrap().as_inner(...
from_raw_socket
identifier_name
impls.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
{ // TODO: this unwrap() is very bad self.as_inner().borrow().as_ref().unwrap().as_inner().raw() }
identifier_body
bsphere.rs
// Copyright Jeron A. Lau 2017-2018. // Copyright Douglas Lau 2017 // Dual-licensed under either the MIT License or the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // TODO: this thing. use std::fmt; use Vec3; /// Bounding spher...
(nvertex, pvertex) } }
nvertex.z += self.half_len; pvertex.z -= self.half_len; }
conditional_block
bsphere.rs
// Copyright Jeron A. Lau 2017-2018. // Copyright Douglas Lau 2017 // Dual-licensed under either the MIT License or the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // TODO: this thing. use std::fmt; use Vec3; /// Bounding spher...
pub fn contains(&self, p: Vec3) -> bool { let Vec3 { x, y, z } = self.center; let hl = self.half_len; (p.x >= x - hl) && (p.x < x + hl) && (p.y >= y - hl) && (p.y < y + hl) && (p.z >= z - hl) && (p.z < z + hl) } /// Get two opposite points that are the bounds of the BBox. pub fn to_point_pair(&s...
/// Check if `BBox` contains point `p`.
random_line_split
bsphere.rs
// Copyright Jeron A. Lau 2017-2018. // Copyright Douglas Lau 2017 // Dual-licensed under either the MIT License or the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // TODO: this thing. use std::fmt; use Vec3; /// Bounding spher...
/// Check if `BBox` contains point `p`. pub fn contains(&self, p: Vec3) -> bool { let Vec3 { x, y, z } = self.center; let hl = self.half_len; (p.x >= x - hl) && (p.x < x + hl) && (p.y >= y - hl) && (p.y < y + hl) && (p.z >= z - hl) && (p.z < z + hl) } /// Get two opposite points that are the bo...
let min_p = self.min_p(); if p.min_p() < min_p { return Vec3::new(min_p, min_p, min_p); } else { let max_p = self.max_p(); return Vec3::new(max_p, max_p, max_p); } }
identifier_body
bsphere.rs
// Copyright Jeron A. Lau 2017-2018. // Copyright Douglas Lau 2017 // Dual-licensed under either the MIT License or the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // TODO: this thing. use std::fmt; use Vec3; /// Bounding spher...
&self, p: Vec3) -> Vec3 { let min_p = self.min_p(); if p.min_p() < min_p { return Vec3::new(min_p, min_p, min_p); } else { let max_p = self.max_p(); return Vec3::new(max_p, max_p, max_p); } } /// Check if `BBox` contains point `p`. pub fn contains(&self, p: Vec3) -> bool { let Vec3 { x, y, z } = ...
ove_center(
identifier_name
test_semantic.rs
use jsonway;
const SECRET: &'static str = "2817b66a1d5829847196cf2f96ab2816"; const REDIS_URI: &'static str = "redis://127.0.0.1/"; #[test] fn test_semantic_search() { let session = RedisStorage::from_url(REDIS_URI); let client = WeChatClient::new(APPID, SECRET, session); let query = jsonway::object(|obj| { obj...
use wechat::WeChatClient; use wechat::session::RedisStorage; const APPID: &'static str = "wxd7aa56e2c7b1f4f1";
random_line_split
test_semantic.rs
use jsonway; use wechat::WeChatClient; use wechat::session::RedisStorage; const APPID: &'static str = "wxd7aa56e2c7b1f4f1"; const SECRET: &'static str = "2817b66a1d5829847196cf2f96ab2816"; const REDIS_URI: &'static str = "redis://127.0.0.1/"; #[test] fn test_semantic_search()
{ let session = RedisStorage::from_url(REDIS_URI); let client = WeChatClient::new(APPID, SECRET, session); let query = jsonway::object(|obj| { obj.set("query", "故宫门票多少钱".to_owned()); obj.set("category", "travel".to_owned()); obj.set("city", "北京".to_owned()); obj.set("appid", ...
identifier_body
test_semantic.rs
use jsonway; use wechat::WeChatClient; use wechat::session::RedisStorage; const APPID: &'static str = "wxd7aa56e2c7b1f4f1"; const SECRET: &'static str = "2817b66a1d5829847196cf2f96ab2816"; const REDIS_URI: &'static str = "redis://127.0.0.1/"; #[test] fn
() { let session = RedisStorage::from_url(REDIS_URI); let client = WeChatClient::new(APPID, SECRET, session); let query = jsonway::object(|obj| { obj.set("query", "故宫门票多少钱".to_owned()); obj.set("category", "travel".to_owned()); obj.set("city", "北京".to_owned()); obj.set("appid...
test_semantic_search
identifier_name
lib.rs
//! This crate provides native rust implementations of //! Image encoders and decoders and basic image manipulation //! functions. #![crate_name = "image"] #![crate_type = "rlib"] #![warn(missing_doc)] #![warn(unnecessary_qualification)] #![warn(unnecessary_typecast)] #![feature(macro_rules)] extern crate flate; p...
CatmullRom, Gaussian, Lanczos3 }; pub use image:: { PNG, JPEG, GIF, WEBP, PPM }; //Image Types pub use image::SubImage as SubImage; pub use image::ImageBuf as ImageBuf; pub use dynimage::DynamicImage as DynamicImage; //Traits pub use image::GenericImage as GenericImage; pub use image:...
pub use imageops:: { Triangle, Nearest,
random_line_split
message_blockdata.rs
// Rust Bitcoin Library // Written in 2014 by // Andrew Poelstra <apoelstra@wpsoftware.net> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warrant...
/// reply with its longest known chain, starting from a locator hash /// if possible and block 1 otherwise. pub locator_hashes: Vec<Sha256dHash>, /// References the header to stop at, or zero to just fetch the maximum 2000 headers pub stop_hash: Sha256dHash } /// An inventory object --- a reference...
#[derive(PartialEq, Eq, Clone, Debug)] pub struct GetHeadersMessage { /// The protocol version pub version: u32, /// Locator hashes --- ordered newest to oldest. The remote peer will
random_line_split
message_blockdata.rs
// Rust Bitcoin Library // Written in 2014 by // Andrew Poelstra <apoelstra@wpsoftware.net> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warrant...
(d: &mut D) -> Result<Inventory, D::Error> { let int_type: u32 = try!(ConsensusDecodable::consensus_decode(d)); Ok(Inventory { inv_type: match int_type { 0 => InvType::Error, 1 => InvType::Transaction, 2 => InvType::Block, // TO...
consensus_decode
identifier_name
sort.rs
/* Copyright 2013 10gen Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writi...
}
match client.disconnect() { Ok(_) => (), Err(e) => fail!("%s", e.to_str()), }
random_line_split
sort.rs
/* Copyright 2013 10gen Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writi...
() { // sort let client = @Client::new(); match client.connect(~"127.0.0.1", MONGO_DEFAULT_PORT) { Ok(_) => (), Err(e) => fail!("%s", e.to_str()), } let n = 105; let (coll, _, ins_docs) = fill_coll(~"rust", ~"test_sort", client, n); let mut cur = match coll.find(None, None,...
test_sort
identifier_name
sort.rs
/* Copyright 2013 10gen Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writi...
let mut i = 0; for cur.advance |doc| { debug!(fmt!("\n%?", doc)); assert!(*doc == ins_docs[n-i-1]); i += 1; } match client.disconnect() { Ok(_) => (), Err(e) => fail!("%s", e.to_str()), } }
{ // sort let client = @Client::new(); match client.connect(~"127.0.0.1", MONGO_DEFAULT_PORT) { Ok(_) => (), Err(e) => fail!("%s", e.to_str()), } let n = 105; let (coll, _, ins_docs) = fill_coll(~"rust", ~"test_sort", client, n); let mut cur = match coll.find(None, None, No...
identifier_body
transaction_condition.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity.
// Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along ...
// Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version.
random_line_split
transaction_condition.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...
(condition: ethcore::transaction::Condition) -> Self { match condition { ethcore::transaction::Condition::Number(n) => TransactionCondition::Number(n), ethcore::transaction::Condition::Timestamp(n) => TransactionCondition::Timestamp(n), } } } #[cfg(test)] mod tests { use ethcore; use super::*; use serde_...
from
identifier_name
transaction_condition.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
} impl From<ethcore::transaction::Condition> for TransactionCondition { fn from(condition: ethcore::transaction::Condition) -> Self { match condition { ethcore::transaction::Condition::Number(n) => TransactionCondition::Number(n), ethcore::transaction::Condition::Timestamp(n) => TransactionCondition::Timesta...
{ match self { TransactionCondition::Number(n) => ethcore::transaction::Condition::Number(n), TransactionCondition::Timestamp(n) => ethcore::transaction::Condition::Timestamp(n), } }
identifier_body
main.rs
const ASCII_A: u8 = b'A'; fn main() { let msg = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; let key = "VIGENERECIPHER"; let enc = vigenere(msg, key, true); let dec = vigenere(&enc, key, false); println!("msg: {}", msg); println!("key: {}", key); println!("e...
(m: u8, k: u8) -> u8 { ASCII_A + (m.wrapping_add(k).wrapping_sub(2 * (ASCII_A))) % 26 } fn dec_byte(c: u8, k: u8) -> u8 { ASCII_A + (c.wrapping_sub(k).wrapping_add(26)) % 26 } #[test] fn test_enc_dec() { let plaintext = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; let ke...
enc_byte
identifier_name
main.rs
const ASCII_A: u8 = b'A'; fn main() { let msg = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; let key = "VIGENERECIPHER"; let enc = vigenere(msg, key, true); let dec = vigenere(&enc, key, false); println!("msg: {}", msg); println!("key: {}", key); println!("e...
} output } fn to_sanitized_bytes(string: &str) -> Vec<u8> { string .chars() .filter(|&c| c.is_alphabetic()) .map(|c| c.to_ascii_uppercase() as u8) .collect::<Vec<u8>>() } fn enc_byte(m: u8, k: u8) -> u8 { ASCII_A + (m.wrapping_add(k).wrapping_sub(2 * (ASCII_A))) % 26 } fn ...
dec_byte(c, b) }; output.push(output_byte as char);
random_line_split
main.rs
const ASCII_A: u8 = b'A'; fn main() { let msg = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; let key = "VIGENERECIPHER"; let enc = vigenere(msg, key, true); let dec = vigenere(&enc, key, false); println!("msg: {}", msg); println!("key: {}", key); println!("e...
#[test] fn test_equal_len_key_and_plaintext() { let plaintext = "VIGENERECIPHER"; let key = "REHPICERENEGIV"; // to be sure nobody breaks this test assert_eq!(plaintext.len(), key.len()); let enc = vigenere(plaintext, key, true); assert_eq!("MMNTVGVVGVTNMM", enc); let dec = vigenere(&enc,...
{ let plaintext = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; let key = "VIGENERECIPHER"; let enc = vigenere(plaintext, key, true); assert_eq!( "WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY", enc ); let dec = vigenere(&enc, key, false)...
identifier_body