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
load_distr_uniform.rs
extern crate rand; use self::rand::distributions::{IndependentSample, Range}; #[derive(Clone, Debug)] pub struct LoadDistrUniform < T > { _buf: Vec< T >, } impl < T > Default for LoadDistrUniform < T > { fn default() -> Self { Self { _buf: vec![], } } } impl < T > LoadDistrUn...
self._buf.clear(); Ok( () ) } }
{ let between = Range::new( 0, self._buf.len() ); let mut rng = rand::thread_rng(); let i = between.ind_sample( & mut rng ); f( & self._buf[ i ] ); }
conditional_block
load_distr_uniform.rs
extern crate rand; use self::rand::distributions::{IndependentSample, Range}; #[derive(Clone, Debug)] pub struct LoadDistrUniform < T > { _buf: Vec< T >, } impl < T > Default for LoadDistrUniform < T > { fn
() -> Self { Self { _buf: vec![], } } } impl < T > LoadDistrUniform < T > { pub fn load( & mut self, t: T ) -> Result< (), &'static str > { self._buf.push( t ); Ok( () ) } pub fn apply< F >( & mut self, mut f: F ) -> Result< (), &'static str > where...
default
identifier_name
physics.rs
use cgmath::{Aabb3, Point, Vector, Vector3}; use octree::Octree; use common::entity::EntityId; use std::collections::HashMap; pub struct Physics { pub terrain_octree: Octree<EntityId>, pub misc_octree: Octree<EntityId>, pub bounds: HashMap<EntityId, Aabb3<f32>>, } impl Physics { pub fn new(world_bounds: Aabb3...
pub fn remove_terrain(&mut self, id: EntityId) { match self.bounds.get(&id) { None => {}, Some(bounds) => { self.terrain_octree.remove(bounds, id); }, } } pub fn remove_misc(&mut self, id: EntityId) { match self.bounds.get(&id) { None => {}, Some(bounds) => { ...
{ self.misc_octree.insert(bounds.clone(), id); self.bounds.insert(id, bounds); }
identifier_body
physics.rs
use cgmath::{Aabb3, Point, Vector, Vector3}; use octree::Octree; use common::entity::EntityId; use std::collections::HashMap; pub struct Physics { pub terrain_octree: Octree<EntityId>, pub misc_octree: Octree<EntityId>, pub bounds: HashMap<EntityId, Aabb3<f32>>, } impl Physics { pub fn new(world_bounds: Aabb3...
, } } pub fn remove_misc(&mut self, id: EntityId) { match self.bounds.get(&id) { None => {}, Some(bounds) => { self.misc_octree.remove(bounds, id); }, } } pub fn get_bounds(&self, id: EntityId) -> Option<&Aabb3<f32>> { self.bounds.get(&id) } pub fn reinsert( ...
{ self.terrain_octree.remove(bounds, id); }
conditional_block
physics.rs
use cgmath::{Aabb3, Point, Vector, Vector3}; use octree::Octree; use common::entity::EntityId; use std::collections::HashMap; pub struct Physics { pub terrain_octree: Octree<EntityId>, pub misc_octree: Octree<EntityId>, pub bounds: HashMap<EntityId, Aabb3<f32>>, } impl Physics { pub fn new(world_bounds: Aabb3...
(&mut self, id: EntityId) { match self.bounds.get(&id) { None => {}, Some(bounds) => { self.terrain_octree.remove(bounds, id); }, } } pub fn remove_misc(&mut self, id: EntityId) { match self.bounds.get(&id) { None => {}, Some(bounds) => { self.misc_octree.r...
remove_terrain
identifier_name
physics.rs
use cgmath::{Aabb3, Point, Vector, Vector3}; use octree::Octree; use common::entity::EntityId; use std::collections::HashMap; pub struct Physics { pub terrain_octree: Octree<EntityId>, pub misc_octree: Octree<EntityId>, pub bounds: HashMap<EntityId, Aabb3<f32>>, } impl Physics { pub fn new(world_bounds: Aabb3...
} pub fn get_bounds(&self, id: EntityId) -> Option<&Aabb3<f32>> { self.bounds.get(&id) } pub fn reinsert( octree: &mut Octree<EntityId>, id: EntityId, bounds: &mut Aabb3<f32>, new_bounds: Aabb3<f32>, ) -> Option<(Aabb3<f32>, EntityId)> { match octree.intersect(&new_bounds, Some(id)) ...
Some(bounds) => { self.misc_octree.remove(bounds, id); }, }
random_line_split
main.rs
#[derive(Debug, Copy, Clone)] enum IncExc { Inc(f32), Exc(f32), } use IncExc::{Exc, Inc}; fn parse_f32_range(s: &str, mn: IncExc, mx: IncExc) -> Result<f32, Error> { let x = s.parse()?; let in_range = match (mn, mx) { (Inc(mn), Inc(mx)) => mn <= x && x <= mx, (Exc(mn), Inc(mx)) => mn...
{ let n = s.parse()?; if n > 0 { Ok(n) } else { Err(err_msg("number shouldn't be zero")) } }
identifier_body
main.rs
else { Err(err_msg("number shouldn't be zero")) } } #[derive(Debug, Copy, Clone)] enum IncExc { Inc(f32), Exc(f32), } use IncExc::{Exc, Inc}; fn parse_f32_range(s: &str, mn: IncExc, mx: IncExc) -> Result<f32, Error> { let x = s.parse()?; let in_range = match (mn, mx) { (Inc(mn), ...
{ Ok(n) }
conditional_block
main.rs
'", num ) })?; }; if let Some(num) = ms.opt_str("t") { parms.thread_count = parse_non_zero_u32(&num).with_context(|_| { format!( "Thread count in -t should be positive non-zero integer, not '{}'", num ) ...
perf_present_start
identifier_name
main.rs
} else { Err(err_msg("number shouldn't be zero")) } } #[derive(Debug, Copy, Clone)] enum IncExc { Inc(f32), Exc(f32), } use IncExc::{Exc, Inc}; fn parse_f32_range(s: &str, mn: IncExc, mx: IncExc) -> Result<f32, Error> { let x = s.parse()?; let in_range = match (mn, mx) { (Inc(...
fn parse_non_zero_u32(s: &str) -> Result<u32, Error> { let n = s.parse()?; if n > 0 { Ok(n)
random_line_split
integrator.rs
use core::camera::Camera; use core::color::Color; use core::image::Image; use core::interaction::Intersectable; use core::ray::Ray; use core::scene::Scene; use core::spectrum::Spectrum; // ------------------------ // Integrator // ------------------------ pub trait Integrator { // TODO: Should return a Film? ...
(ray: &Ray, scene: &Scene) -> Spectrum { match scene.intersect(ray) { Some(x) => { // let y = x / 8.0; let y = 1.0; Spectrum::new(&Color::new(y, y, y, y)) }, // No intersection, return background radiance. None => s...
li
identifier_name
integrator.rs
use core::camera::Camera; use core::color::Color; use core::image::Image; use core::interaction::Intersectable; use core::ray::Ray; use core::scene::Scene; use core::spectrum::Spectrum; // ------------------------ // Integrator // ------------------------ pub trait Integrator { // TODO: Should return a Film? ...
img } }
random_line_split
integrator.rs
use core::camera::Camera; use core::color::Color; use core::image::Image; use core::interaction::Intersectable; use core::ray::Ray; use core::scene::Scene; use core::spectrum::Spectrum; // ------------------------ // Integrator // ------------------------ pub trait Integrator { // TODO: Should return a Film? ...
fn li(ray: &Ray, scene: &Scene) -> Spectrum { match scene.intersect(ray) { Some(x) => { // let y = x / 8.0; let y = 1.0; Spectrum::new(&Color::new(y, y, y, y)) }, // No intersection, return background radiance. ...
{ SamplerIntegrator {} }
identifier_body
packed-struct-generic-size.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 ...
() { assert_eq!(mem::size_of::<S<u8, u8>>(), 3); assert_eq!(mem::size_of::<S<u64, u16>>(), 11); }
main
identifier_name
packed-struct-generic-size.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 ...
{ assert_eq!(mem::size_of::<S<u8, u8>>(), 3); assert_eq!(mem::size_of::<S<u64, u16>>(), 11); }
identifier_body
packed-struct-generic-size.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 ...
assert_eq!(mem::size_of::<S<u64, u16>>(), 11); }
c: S } pub fn main() { assert_eq!(mem::size_of::<S<u8, u8>>(), 3);
random_line_split
debug.rs
/* * Rust BareBones OS * - By John Hodge (Mutabah/thePowersGang) * * arch/x86/debug.rs * - Debug output channel * * Writes debug to the standard PC serial port (0x3F8.. 0x3FF) * * == LICENCE == * This code has been put into the public domain, there are no restrictions on * its use, and the author takes no ...
{ for b in s.bytes() { putb(b); } } /// Write a single byte to the output channel /// /// This method is unsafe because it does port accesses without synchronisation pub unsafe fn putb(b: u8) { // Wait for the serial port's fifo to not be empty while (::arch::x86_io::inb(0x3F8+5) & 0x20) == 0 { // Do nothing...
/// Write a string to the output channel /// /// This method is unsafe because it does port accesses without synchronisation pub unsafe fn puts(s: &str)
random_line_split
debug.rs
/* * Rust BareBones OS * - By John Hodge (Mutabah/thePowersGang) * * arch/x86/debug.rs * - Debug output channel * * Writes debug to the standard PC serial port (0x3F8.. 0x3FF) * * == LICENCE == * This code has been put into the public domain, there are no restrictions on * its use, and the author takes no ...
(s: &str) { for b in s.bytes() { putb(b); } } /// Write a single byte to the output channel /// /// This method is unsafe because it does port accesses without synchronisation pub unsafe fn putb(b: u8) { // Wait for the serial port's fifo to not be empty while (::arch::x86_io::inb(0x3F8+5) & 0x20) == 0 { // ...
puts
identifier_name
debug.rs
/* * Rust BareBones OS * - By John Hodge (Mutabah/thePowersGang) * * arch/x86/debug.rs * - Debug output channel * * Writes debug to the standard PC serial port (0x3F8.. 0x3FF) * * == LICENCE == * This code has been put into the public domain, there are no restrictions on * its use, and the author takes no ...
/// Write a single byte to the output channel /// /// This method is unsafe because it does port accesses without synchronisation pub unsafe fn putb(b: u8) { // Wait for the serial port's fifo to not be empty while (::arch::x86_io::inb(0x3F8+5) & 0x20) == 0 { // Do nothing } // Send the byte out the serial por...
{ for b in s.bytes() { putb(b); } }
identifier_body
error.rs
use std; use std::fmt; use std::ops::Deref; /// Error type #[derive(Debug)] pub struct Error { // Description what: String,
// Cause cause: Option<Box<std::error::Error + Sized>>, } impl Error { /// Construct `Error` with message only pub fn new<S>(what: S) -> Self where S: Into<String> { Error { what: what.into(), cause: None, } } /// Consumes self and constructs `Error` with message and cause pub fn because<E>(self, ...
random_line_split
error.rs
use std; use std::fmt; use std::ops::Deref; /// Error type #[derive(Debug)] pub struct
{ // Description what: String, // Cause cause: Option<Box<std::error::Error + Sized>>, } impl Error { /// Construct `Error` with message only pub fn new<S>(what: S) -> Self where S: Into<String> { Error { what: what.into(), cause: None, } } /// Consumes self and constructs `Error` with message a...
Error
identifier_name
thread.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: *mut libc::c_void) -> thread::rust_thread_return { unsafe { stack::record_os_managed_stack_bounds(0, uint::MAX); let handler = stack_overflow::Handler::new(); let f: Box<Thunk> = mem::transmute(main); f.invoke(()); drop(handler); mem::transmute(0 as thread::rus...
start_thread
identifier_name
thread.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 ...
f.invoke(()); drop(handler); mem::transmute(0 as thread::rust_thread_return) } }
unsafe { stack::record_os_managed_stack_bounds(0, uint::MAX); let handler = stack_overflow::Handler::new(); let f: Box<Thunk> = mem::transmute(main);
random_line_split
thread.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 ...
{ unsafe { stack::record_os_managed_stack_bounds(0, uint::MAX); let handler = stack_overflow::Handler::new(); let f: Box<Thunk> = mem::transmute(main); f.invoke(()); drop(handler); mem::transmute(0 as thread::rust_thread_return) } }
identifier_body
main.rs
extern crate toml; use std::{env, process}; use std::io::prelude::*; use std::io::{BufReader, ErrorKind}; use std::collections::BTreeMap; use std::fs::File; use toml::Value; static OVERRIDES_PATH : &'static str = ".multirust/overrides"; static SETTINGS_PATH : &'static str = ".rustup/settings.toml"; static OLD_SETTIN...
println!("{}", clean_toolchain_name(toolchain)); return; } if!cwd.pop() { break; } } println!("default"); } fn main() { let home = env::home_dir().expect("Impossible to get your home dir!"); let mut overrides_path = home.clone(); overrid...
if let Some(toolchain) = database.get(&path) {
random_line_split
main.rs
extern crate toml; use std::{env, process}; use std::io::prelude::*; use std::io::{BufReader, ErrorKind}; use std::collections::BTreeMap; use std::fs::File; use toml::Value; static OVERRIDES_PATH : &'static str = ".multirust/overrides"; static SETTINGS_PATH : &'static str = ".rustup/settings.toml"; static OLD_SETTIN...
(&self, key: &str) -> Option<&str> { use OverridesDatabase::*; match *self { Plain(ref db) => db.get(key).map(|s| &s[..]), Toml(ref db) => { db.get(key).map(|v| v.as_str().expect("Expected value is not a string.")) } } } } fn with_date<'a...
get
identifier_name
main.rs
extern crate toml; use std::{env, process}; use std::io::prelude::*; use std::io::{BufReader, ErrorKind}; use std::collections::BTreeMap; use std::fs::File; use toml::Value; static OVERRIDES_PATH : &'static str = ".multirust/overrides"; static SETTINGS_PATH : &'static str = ".rustup/settings.toml"; static OLD_SETTIN...
fn clean_toolchain_name(toolchain: &str) -> &str { static SHORTNAMES : &'static [&'static str] = &["stable", "nightly", "beta"]; for short in SHORTNAMES { if toolchain.starts_with(short) { return match with_date(short, toolchain) { Some(s) => s, None => sho...
{ let date_start = short.len() + 1; let date_end = short.len() + 3 + 4 + 2 + 2; let char_range = toolchain.chars() .skip(date_start) .take(4) .all(char::is_numeric); if toolchain.len() > date_start && char_range { Some(&toolchain[0..date_end]) } else { None...
identifier_body
htmlfontelement.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 cssparser::RGBA; use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLFontElementBinding; use d...
// https://html.spec.whatwg.org/multipage/#dom-font-face make_atomic_setter!(SetFace, "face"); // https://html.spec.whatwg.org/multipage/#dom-font-size make_getter!(Size, "size"); // https://html.spec.whatwg.org/multipage/#dom-font-size fn SetSize(&self, value: DOMString) { let element...
make_getter!(Face, "face");
random_line_split
htmlfontelement.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 cssparser::RGBA; use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLFontElementBinding; use d...
{ htmlelement: HTMLElement, } impl HTMLFontElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLFontElement { HTMLFontElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), } } #[allow(unrooted_must_ro...
HTMLFontElement
identifier_name
htmlfontelement.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 cssparser::RGBA; use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLFontElementBinding; use d...
} /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size pub fn parse_legacy_font_size(mut input: &str) -> Option<&'static str> { // Steps 1 & 2 are not relevant // Step 3 input = input.trim_matches(HTML_SPACE_CHARACTERS); enum ParseMode { RelativePlus, Rela...
{ unsafe { (*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &atom!("size")) .and_then(AttrValue::as_length) .cloned() } }
identifier_body
more.rs
#![crate_name = "uu_more"] /* * This file is part of the uutils coreutils package. * * (c) Martin Kysel <code@martinkysel.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucor...
; match mode { Mode::More => more(matches), Mode::Help => help(&usage), Mode::Version => version(), } 0 } fn version() { println!("{} {}", NAME, VERSION); } fn help(usage: &str) { let msg = format!("{0} {1}\n\n\ Usage: {0} TARGET\n \ ...
{ Mode::More }
conditional_block
more.rs
#![crate_name = "uu_more"] /* * This file is part of the uutils coreutils package. * * (c) Martin Kysel <code@martinkysel.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucor...
#[cfg(windows)] fn setup_term() -> usize { 0 } #[cfg(unix)] fn reset_term(term: &mut termios::Termios) { term.c_lflag.insert(termios::ICANON); term.c_lflag.insert(termios::ECHO); termios::tcsetattr(0, termios::TCSADRAIN, &term).unwrap(); } #[cfg(windows)] fn reset_term(_: &mut usize) { } fn more(ma...
{ let mut term = termios::tcgetattr(0).unwrap(); // Unset canonical mode, so we get characters immediately term.c_lflag.remove(termios::ICANON); // Disable local echo term.c_lflag.remove(termios::ECHO); termios::tcsetattr(0, termios::TCSADRAIN, &term).unwrap(); term }
identifier_body
more.rs
#![crate_name = "uu_more"] /* * This file is part of the uutils coreutils package. * * (c) Martin Kysel <code@martinkysel.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucor...
{ More, Help, Version, } static NAME: &'static str = "more"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("v", "version", "output versio...
Mode
identifier_name
more.rs
#![crate_name = "uu_more"] /* * This file is part of the uutils coreutils package. * * (c) Martin Kysel <code@martinkysel.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucor...
Mode::Version => version(), } 0 } fn version() { println!("{} {}", NAME, VERSION); } fn help(usage: &str) { let msg = format!("{0} {1}\n\n\ Usage: {0} TARGET\n \ \n\ {2}", NAME, VERSION, usage); println!("{}", msg); } ...
match mode { Mode::More => more(matches), Mode::Help => help(&usage),
random_line_split
q_timer_quit.rs
use cpp_core::NullPtr; use qt_core::{QCoreApplication, QTimer, SlotNoArgs}; use std::cell::RefCell; use std::rc::Rc; #[test] fn timer_quit()
{ QCoreApplication::init(|app| unsafe { let value = Rc::new(RefCell::new(Some(42))); let value2 = Rc::clone(&value); let slot1 = SlotNoArgs::new(NullPtr, move || { assert_eq!(value2.borrow_mut().take(), Some(42)); }); let c = app.about_to_quit().connect(&slot1); ...
identifier_body
q_timer_quit.rs
use cpp_core::NullPtr; use qt_core::{QCoreApplication, QTimer, SlotNoArgs}; use std::cell::RefCell; use std::rc::Rc; #[test] fn
() { QCoreApplication::init(|app| unsafe { let value = Rc::new(RefCell::new(Some(42))); let value2 = Rc::clone(&value); let slot1 = SlotNoArgs::new(NullPtr, move || { assert_eq!(value2.borrow_mut().take(), Some(42)); }); let c = app.about_to_quit().connect(&slot1)...
timer_quit
identifier_name
q_timer_quit.rs
use cpp_core::NullPtr; use qt_core::{QCoreApplication, QTimer, SlotNoArgs}; use std::cell::RefCell; use std::rc::Rc; #[test] fn timer_quit() { QCoreApplication::init(|app| unsafe { let value = Rc::new(RefCell::new(Some(42))); let value2 = Rc::clone(&value); let slot1 = SlotNoArgs::new(NullP...
assert_eq!(value2.borrow_mut().take(), Some(42)); }); let c = app.about_to_quit().connect(&slot1); assert!(c.is_valid()); let timer = QTimer::new_0a(); let c = timer.timeout().connect(app.slot_quit()); assert!(c.is_valid()); timer.start_1a(1000); ...
random_line_split
structfields.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} // @has structfields/struct.Baz.html //pre "pub struct Baz { /* fields omitted */ }" pub struct Baz { x: u8, #[doc(hidden)] pub y: u8, } // @has structfields/struct.Quux.html //pre "pub struct Quux {}" pub struct Quux {}
// @has - //pre "c: usize" c: usize, // @has - //pre "// some fields omitted" },
random_line_split
structfields.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ x: u8, #[doc(hidden)] pub y: u8, } // @has structfields/struct.Quux.html //pre "pub struct Quux {}" pub struct Quux {}
Baz
identifier_name
target.rs
use crate::associations::{HasTable, Identifiable}; use crate::dsl::Find; use crate::query_dsl::methods::FindDsl; use crate::query_source::Table; #[doc(hidden)] #[derive(Debug)] pub struct UpdateTarget<Table, WhereClause> { pub table: Table, pub where_clause: WhereClause, } /// A type which can be passed to [`...
}
{ T::table().find(self.id()).into_update_target() }
identifier_body
target.rs
use crate::associations::{HasTable, Identifiable}; use crate::dsl::Find; use crate::query_dsl::methods::FindDsl; use crate::query_source::Table; #[doc(hidden)] #[derive(Debug)] pub struct UpdateTarget<Table, WhereClause> { pub table: Table, pub where_clause: WhereClause, } /// A type which can be passed to [`...
(self) -> UpdateTarget<Self::Table, Self::WhereClause> { T::table().find(self.id()).into_update_target() } }
into_update_target
identifier_name
target.rs
use crate::associations::{HasTable, Identifiable}; use crate::dsl::Find; use crate::query_dsl::methods::FindDsl; use crate::query_source::Table; #[doc(hidden)] #[derive(Debug)]
pub where_clause: WhereClause, } /// A type which can be passed to [`update`] or [`delete`]. /// /// Apps will never need to implement this type directly. There are three kinds /// which implement this trait. Tables, queries which have only had `filter` /// called on them, and types which implement `Identifiable`....
pub struct UpdateTarget<Table, WhereClause> { pub table: Table,
random_line_split
websocket_loader.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 crate::connector::create_ssl_connector_builder; use crate::cookie::Cookie; use crate::fetch::methods::should_b...
(&mut self, shake: Handshake) -> WebSocketResult<()> { let mut headers = HeaderMap::new(); for &(ref name, ref value) in shake.response.headers().iter() { let name = HeaderName::from_bytes(name.as_bytes()).unwrap(); let value = HeaderValue::from_bytes(&value).unwrap(); ...
on_open
identifier_name
websocket_loader.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 crate::connector::create_ssl_connector_builder; use crate::cookie::Cookie; use crate::fetch::methods::should_b...
return; } let host = replace_host(req_init.url.host_str().unwrap()); let mut net_url = req_init.url.clone().into_url(); net_url.set_host(Some(&host)).unwrap(); let host = Host::from( format!( "{}{}", ...
{ thread::Builder::new() .name(format!("WebSocket connection to {}", req_init.url)) .spawn(move || { let protocols = match req_init.mode { RequestMode::WebSocket { protocols } => protocols.clone(), _ => panic!("Received a RequestInit with a non-websocket m...
identifier_body
websocket_loader.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 crate::connector::create_ssl_connector_builder; use crate::cookie::Cookie; use crate::fetch::methods::should_b...
fn connection_made(&mut self, _: Sender) -> Self::Handler { self.clone() } fn connection_lost(&mut self, _: Self::Handler) { let _ = self.event_sender.send(WebSocketNetworkEvent::Fail); } } impl<'a> Handler for Client<'a> { fn build_request(&mut self, url: &Url) -> WebSocketResult<...
impl<'a> Factory for Client<'a> { type Handler = Self;
random_line_split
websocket_loader.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 crate::connector::create_ssl_connector_builder; use crate::cookie::Cookie; use crate::fetch::methods::should_b...
, } } }); if let Err(e) = ws.run() { debug!("Failed to run WebSocket: {:?}", e); let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail); }; }) .expect("Thread spawning failed"); }
{ if !initiated_close.fetch_or(true, Ordering::SeqCst) { match code { Some(code) => ws_sender .close_with_reason( code.into(), ...
conditional_block
host.rs
//! The Host request header, defined in RFC 2616, Section 14.23. use std::io::Reader; /// A simple little thing for the host of a request #[deriving(Clone, Eq)] pub struct Host { /// The name of the host that was requested name: ~str, /// If unspecified, assume the default port was used (80 for HTTP, 44...
None => None, }, }) } fn http_value(&self) -> ~str { self.to_str() } }
name: hi.next().unwrap().to_owned(), port: match hi.next() { Some(name) => from_str::<u16>(name),
random_line_split
host.rs
//! The Host request header, defined in RFC 2616, Section 14.23. use std::io::Reader; /// A simple little thing for the host of a request #[deriving(Clone, Eq)] pub struct
{ /// The name of the host that was requested name: ~str, /// If unspecified, assume the default port was used (80 for HTTP, 443 for HTTPS). /// In that case, you shouldn't need to worry about it in URLs that you build, provided you /// include the scheme. port: Option<u16>, } impl ToStr for ...
Host
identifier_name
host.rs
//! The Host request header, defined in RFC 2616, Section 14.23. use std::io::Reader; /// A simple little thing for the host of a request #[deriving(Clone, Eq)] pub struct Host { /// The name of the host that was requested name: ~str, /// If unspecified, assume the default port was used (80 for HTTP, 44...
}
{ self.to_str() }
identifier_body
lib.rs
//! Weave deltas, inspired by SCCS. //! //! The [SCCS](https://en.wikipedia.org/wiki/Source_Code_Control_System) revision control system is //! one of the oldest source code management systems (1973). Although many of its concepts are //! quite dated in these days of git, the underlying "weave" delta format it used tu...
(naming: &dyn NamingConvention) -> Result<usize> { let header = read_header(naming)?; Ok(header .deltas .iter() .map(|x| x.number) .max() .expect("at least one delta in weave file")) }
get_last_delta
identifier_name
lib.rs
//! Weave deltas, inspired by SCCS. //! //! The [SCCS](https://en.wikipedia.org/wiki/Source_Code_Control_System) revision control system is //! one of the oldest source code management systems (1973). Although many of its concepts are //! quite dated in these days of git, the underlying "weave" delta format it used tu...
{ let header = read_header(naming)?; Ok(header .deltas .iter() .map(|x| x.number) .max() .expect("at least one delta in weave file")) }
identifier_body
lib.rs
//! Weave deltas, inspired by SCCS. //! //! The [SCCS](https://en.wikipedia.org/wiki/Source_Code_Control_System) revision control system is //! one of the oldest source code management systems (1973). Although many of its concepts are //! quite dated in these days of git, the underlying "weave" delta format it used tu...
.map(|x| x.number) .max() .expect("at least one delta in weave file")) }
random_line_split
foo.rs
#![crate_type = "cdylib"] extern "C" { fn observe(ptr: *const u8, len: usize); } macro_rules! s { ( $( $f:ident -> $t:ty );* $(;)* ) => { $( extern "C" { fn $f() -> $t; } let s = $f().to_string(); observe(s.as_ptr(), s.len()); )* ...
get_i32 -> i32; get_u64 -> u64; get_i64 -> i64; get_usize -> usize; get_isize -> isize; } }
get_i8 -> i8; get_u16 -> u16; get_i16 -> i16; get_u32 -> u32;
random_line_split
foo.rs
#![crate_type = "cdylib"] extern "C" { fn observe(ptr: *const u8, len: usize); } macro_rules! s { ( $( $f:ident -> $t:ty );* $(;)* ) => { $( extern "C" { fn $f() -> $t; } let s = $f().to_string(); observe(s.as_ptr(), s.len()); )* ...
() { s! { get_u8 -> u8; get_i8 -> i8; get_u16 -> u16; get_i16 -> i16; get_u32 -> u32; get_i32 -> i32; get_u64 -> u64; get_i64 -> i64; get_usize -> usize; get_isize -> isize; } }
foo
identifier_name
foo.rs
#![crate_type = "cdylib"] extern "C" { fn observe(ptr: *const u8, len: usize); } macro_rules! s { ( $( $f:ident -> $t:ty );* $(;)* ) => { $( extern "C" { fn $f() -> $t; } let s = $f().to_string(); observe(s.as_ptr(), s.len()); )* ...
{ s! { get_u8 -> u8; get_i8 -> i8; get_u16 -> u16; get_i16 -> i16; get_u32 -> u32; get_i32 -> i32; get_u64 -> u64; get_i64 -> i64; get_usize -> usize; get_isize -> isize; } }
identifier_body
p129.rs
//! [Problem 129](https://projecteuler.net/problem=129) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(step_by)] #[macro_use(problem)] extern crate common; extern crate num; use num::Integer; fn a(n: u64) -> u64 { ...
#[cfg(test)] mod tests { use num::Integer; mod naive { use num::{One, Zero, Integer, BigUint, FromPrimitive}; pub fn r(k: u64) -> BigUint { let mut r: BigUint = Zero::zero(); let ten: BigUint = FromPrimitive::from_u64(10).unwrap(); let one: BigUint = One::on...
} problem!("1000023", solve);
random_line_split
p129.rs
//! [Problem 129](https://projecteuler.net/problem=129) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(step_by)] #[macro_use(problem)] extern crate common; extern crate num; use num::Integer; fn a(n: u64) -> u64 { ...
assert_eq!(naive::a(n), super::a(n)); } } #[test] fn a() { assert_eq!(6, super::a(7)); assert_eq!(5, super::a(41)); } }
{ continue; }
conditional_block
p129.rs
//! [Problem 129](https://projecteuler.net/problem=129) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(step_by)] #[macro_use(problem)] extern crate common; extern crate num; use num::Integer; fn a(n: u64) -> u64 { ...
}
{ assert_eq!(6, super::a(7)); assert_eq!(5, super::a(41)); }
identifier_body
p129.rs
//! [Problem 129](https://projecteuler.net/problem=129) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(step_by)] #[macro_use(problem)] extern crate common; extern crate num; use num::Integer; fn a(n: u64) -> u64 { ...
() -> String { let limit = 1000001; (limit..).step_by(2) .filter(|&n|!n.is_multiple_of(&5)) .find(|&n| a(n) >= limit) .unwrap() .to_string() } problem!("1000023", solve); #[cfg(test)] mod tests { use num::Integer; mod naive { use num::{One, Zero, Integer, BigUint,...
solve
identifier_name
app_uart.rs
#![feature(phase)] #![crate_type="staticlib"] #![no_std] extern crate core; extern crate zinc; #[phase(plugin)] extern crate macro_platformtree; platformtree!( lpc17xx@mcu { clock { source = "main-oscillator"; source_frequency = 12_000_000; pll { m = 50; n = 3; divisor ...
{ use zinc::drivers::chario::CharIO; use zinc::hal::timer::Timer; use zinc::hal::pin::GPIO; args.uart.puts("Hello, world\n"); let mut i = 0; loop { args.txled.set_high(); args.uart.puts("Waiting for "); args.uart.puti(i); args.uart.puts(" seconds...\n"); i += 1; args.txled.set_low...
identifier_body
app_uart.rs
#![feature(phase)] #![crate_type="staticlib"] #![no_std] extern crate core; extern crate zinc; #[phase(plugin)] extern crate macro_platformtree; platformtree!( lpc17xx@mcu { clock { source = "main-oscillator"; source_frequency = 12_000_000; pll { m = 50; n = 3; divisor ...
(args: &pt::run_args) { use zinc::drivers::chario::CharIO; use zinc::hal::timer::Timer; use zinc::hal::pin::GPIO; args.uart.puts("Hello, world\n"); let mut i = 0; loop { args.txled.set_high(); args.uart.puts("Waiting for "); args.uart.puti(i); args.uart.puts(" seconds...\n"); i += 1; ...
run
identifier_name
app_uart.rs
#![feature(phase)] #![crate_type="staticlib"] #![no_std] extern crate core; extern crate zinc;
platformtree!( lpc17xx@mcu { clock { source = "main-oscillator"; source_frequency = 12_000_000; pll { m = 50; n = 3; divisor = 4; } } timer { timer@1 { counter = 25; divisor = 4; } } uart { uart@0 { baud_r...
#[phase(plugin)] extern crate macro_platformtree;
random_line_split
client.rs
// // Copyright 2022 The Project Oak Authors // // 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 o...
( uri: &str, expected_tee_measurement: &[u8], server_verifier: ServerIdentityVerifier, ) -> anyhow::Result<Self> { let mut channel = GrpcChannel::create(uri) .await .context("Couldn't create gRPC client")?; let encryptor = Self::set_up_tunnel...
create
identifier_name
client.rs
// // Copyright 2022 The Project Oak Authors // // 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 o...
async fn receive(&mut self) -> anyhow::Result<Option<StreamingResponse>> { self.response_stream .message() .await .context("Couldn't receive response") } } /// gRPC Attestation Service client implementation. pub struct AttestationClient { channel: GrpcChannel, e...
.context("Couldn't send request") }
random_line_split
client.rs
// // Copyright 2022 The Project Oak Authors // // 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 o...
let outgoing_message = handshaker .next_step(&incoming_message.body) .context("Couldn't process handshake message")?; if let Some(outgoing_message) = outgoing_message { channel .send(StreamingRequest { body:...
{ let mut handshaker = ClientHandshaker::new( AttestationBehavior::create_peer_attestation(expected_tee_measurement), server_verifier, ); let client_hello = handshaker .create_client_hello() .context("Couldn't create client hello message")?; ...
identifier_body
client.rs
// // Copyright 2022 The Project Oak Authors // // 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 o...
} let encryptor = handshaker .get_encryptor() .context("Couldn't get encryptor")?; Ok(encryptor) } /// Sends data encrypted by the [`Encryptor`] to the server and decrypts the server responses. /// Returns `Ok(None)` to indicate that the corresponding gRPC str...
{ channel .send(StreamingRequest { body: outgoing_message, }) .await .context("Couldn't send handshake message")?; }
conditional_block
get_outgoing.rs
use chrono::{UTC, Date, Datelike}; use std::str::FromStr; // Use of #from_str. use api::client::{TellerClient, ApiServiceResult, Transaction}; use api::client::parse_utc_date_from_transaction; use api::inform::Money; pub trait GetOutgoing { fn get_outgoing(&self, account_id: &str, for_month: &Date<UTC>) -> ApiSe...
}
}
random_line_split
get_outgoing.rs
use chrono::{UTC, Date, Datelike}; use std::str::FromStr; // Use of #from_str. use api::client::{TellerClient, ApiServiceResult, Transaction}; use api::client::parse_utc_date_from_transaction; use api::inform::Money; pub trait GetOutgoing { fn get_outgoing(&self, account_id: &str, for_month: &Date<UTC>) -> ApiSe...
let from_float_string_to_cent_integer = |t: &Transaction| { (f64::from_str(&t.amount).unwrap() * 100f64).round() as i64 }; let from_cent_integer_to_float_string = |amount: i64| format!("{:.2}", amount as f64 / 100f64); let outgoing = transactions.iter() ...
{ let account = try!(self.get_account(&account_id)); let currency = account.currency; let from = for_month.with_day(1).unwrap(); let to = if from.month() < 12 { from.with_month(from.month() + 1).unwrap() } else { from.with_year(from.year() + 1).unwrap().w...
identifier_body
get_outgoing.rs
use chrono::{UTC, Date, Datelike}; use std::str::FromStr; // Use of #from_str. use api::client::{TellerClient, ApiServiceResult, Transaction}; use api::client::parse_utc_date_from_transaction; use api::inform::Money; pub trait GetOutgoing { fn get_outgoing(&self, account_id: &str, for_month: &Date<UTC>) -> ApiSe...
(&self, account_id: &str, for_month: &Date<UTC>) -> ApiServiceResult<Money> { let account = try!(self.get_account(&account_id)); let currency = account.currency; let from = for_month.with_day(1).unwrap(); let to = if from.month() < 12 { from.with_month(from.month() + 1).unwr...
get_outgoing
identifier_name
get_outgoing.rs
use chrono::{UTC, Date, Datelike}; use std::str::FromStr; // Use of #from_str. use api::client::{TellerClient, ApiServiceResult, Transaction}; use api::client::parse_utc_date_from_transaction; use api::inform::Money; pub trait GetOutgoing { fn get_outgoing(&self, account_id: &str, for_month: &Date<UTC>) -> ApiSe...
; let transactions: Vec<Transaction> = self.raw_transactions(&account_id, 250, 1) .unwrap_or(vec![]) .into_iter() .filter(|t| { ...
{ from.with_year(from.year() + 1).unwrap().with_month(1).unwrap() }
conditional_block
obligations.rs
// Copyright 2012-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...
.push_sub_region_constraint(origin, region, unique_bound); return; } // Fallback to verifying after the fact that there exists a // declared bound, or that all the components appearing in the // projection outlive; in some cases, this may add insufficient ...
"projection_must_outlive: unique trait bound = {:?}", unique_bound ); debug!("projection_must_outlive: unique declared bound appears in trait ref"); self.delegate
random_line_split
obligations.rs
// Copyright 2012-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...
// If we found a unique bound `'b` from the trait, and we // found nothing else from the environment, then the best // action is to require that `'b: 'r`, so do that. // // This is best no matter what rule we use: // // - OutlivesProjectionEnv: these would trans...
{ debug!("projection_must_outlive: no declared bounds"); for component_ty in projection_ty.substs.types() { self.type_must_outlive(origin.clone(), component_ty, region); } for r in projection_ty.substs.regions() { self.delegate ...
conditional_block
obligations.rs
// Copyright 2012-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...
pub fn register_region_obligation_with_cause( &self, sup_type: Ty<'tcx>, sub_region: Region<'tcx>, cause: &ObligationCause<'tcx>, ) { let origin = SubregionOrigin::from_obligation_cause(cause, || { infer::RelateParamBound(cause.span, sup_type) }); ...
{ debug!( "register_region_obligation(body_id={:?}, obligation={:?})", body_id, obligation ); self.region_obligations .borrow_mut() .push((body_id, obligation)); }
identifier_body
obligations.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
( &self, body_id: ast::NodeId, obligation: RegionObligation<'tcx>, ) { debug!( "register_region_obligation(body_id={:?}, obligation={:?})", body_id, obligation ); self.region_obligations .borrow_mut() .push((body_id, obli...
register_region_obligation
identifier_name
registers.rs
= 0, Usb11FullSpeed = 1 ], UlpiDdrSelect OFFSET(7) NUMBITS(1) [ SingleDataRate8bit = 0, DoubleDataRate4bit = 1 ], SrpCapable OFFSET(8) NUMBITS(1) [], HnpCapable OFF...
bitor
identifier_name
registers.rs
OFFSET(10) NUMBITS(4) [] // Bit 14 reserved // Bits 15+ not used by SW; not included because they won't be tested ], pub Reset [ // OTG Databook, Table 5-11 AhbMasterIdle OFFSET(31) NUMBITS(1) [], DmaRequestSignal OFFSET(30) NUMBITS(1...
random_line_split
lib.rs
#![feature(core_intrinsics, lang_items)] #![no_std] mod gpio; mod watchdog; use core::intrinsics::{volatile_store, volatile_load}; const GPFSEL2: u32 = 0x3F20_0008; const GPSET0: u32 = 0x3F20_001C; const GPCLR0: u32 = 0x3F20_0028; const GPIO20: u32 = 1 << 20; const GPIO21: u32 = 1 << 21; const GPIO22: u32 = 1 << ...
() { let state_counter = unsafe { volatile_load::<u32>(&STATE_COUNTER as *const u32 as *mut u32) }; if state_counter & 0x1 == 0 { gpio::write_register(GPSET0, GPIO20); gpio::write_register(GPCLR0, GPIO21); } else { gpio::write_register(GPCLR0, GPIO20); gpio::write_register(G...
rust_irq_handler
identifier_name
lib.rs
#![feature(core_intrinsics, lang_items)] #![no_std] mod gpio; mod watchdog; use core::intrinsics::{volatile_store, volatile_load}; const GPFSEL2: u32 = 0x3F20_0008; const GPSET0: u32 = 0x3F20_001C; const GPCLR0: u32 = 0x3F20_0028; const GPIO20: u32 = 1 << 20; const GPIO21: u32 = 1 << 21; const GPIO22: u32 = 1 << ...
#[no_mangle] pub extern fn rust_main() { gpio::write_register(ARM_TIMER_LOD, SHORT_TIMEOUT - 1); gpio::write_register(ARM_TIMER_RLD, SHORT_TIMEOUT - 1); // // Set the timer pre-divider to 0xF9. System clock freq (~250MHz) / 0xF9 = ~1 million ticks/sec gpio::write_register(ARM_TIMER_DIV, 0x0000_00F9); ...
}
random_line_split
lib.rs
#![feature(core_intrinsics, lang_items)] #![no_std] mod gpio; mod watchdog; use core::intrinsics::{volatile_store, volatile_load}; const GPFSEL2: u32 = 0x3F20_0008; const GPSET0: u32 = 0x3F20_001C; const GPCLR0: u32 = 0x3F20_0028; const GPIO20: u32 = 1 << 20; const GPIO21: u32 = 1 << 21; const GPIO22: u32 = 1 << ...
} loop {} } #[no_mangle] pub extern fn rust_irq_handler() { let state_counter = unsafe { volatile_load::<u32>(&STATE_COUNTER as *const u32 as *mut u32) }; if state_counter & 0x1 == 0 { gpio::write_register(GPSET0, GPIO20); gpio::write_register(GPCLR0, GPIO21); } else { gp...
{ gpio::write_register(GPSET0, GPIO22); break; }
conditional_block
lib.rs
#![feature(core_intrinsics, lang_items)] #![no_std] mod gpio; mod watchdog; use core::intrinsics::{volatile_store, volatile_load}; const GPFSEL2: u32 = 0x3F20_0008; const GPSET0: u32 = 0x3F20_001C; const GPCLR0: u32 = 0x3F20_0028; const GPIO20: u32 = 1 << 20; const GPIO21: u32 = 1 << 21; const GPIO22: u32 = 1 << ...
} } loop {} } #[no_mangle] pub extern fn rust_irq_handler() { let state_counter = unsafe { volatile_load::<u32>(&STATE_COUNTER as *const u32 as *mut u32) }; if state_counter & 0x1 == 0 { gpio::write_register(GPSET0, GPIO20); gpio::write_register(GPCLR0, GPIO21); } else { ...
{ gpio::write_register(ARM_TIMER_LOD, SHORT_TIMEOUT - 1); gpio::write_register(ARM_TIMER_RLD, SHORT_TIMEOUT - 1); // // Set the timer pre-divider to 0xF9. System clock freq (~250MHz) / 0xF9 = ~1 million ticks/sec gpio::write_register(ARM_TIMER_DIV, 0x0000_00F9); gpio::write_register(ARM_TIMER_CLI, 0...
identifier_body
env.rs
// Copyright (C) 2018 Pietro Albini // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distrib...
let mut env = TestingEnv::new().unwrap(); let result = f(&mut env); env.cleanup().unwrap(); result.unwrap(); }
} } pub fn testing_env<F: Fn(&mut TestingEnv) -> Result<()>>(f: F) {
random_line_split
env.rs
// Copyright (C) 2018 Pietro Albini // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distrib...
{ let mut env = TestingEnv::new().unwrap(); let result = f(&mut env); env.cleanup().unwrap(); result.unwrap(); }
identifier_body
env.rs
// Copyright (C) 2018 Pietro Albini // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distrib...
(&self) -> Result<PathBuf> { let dir = TempDir::new("fisher-integration")?.into_path(); self.tempdirs.borrow_mut().push(dir.clone()); Ok(dir) } pub fn create_script(&self, name: &str, content: &[&str]) -> Result<()> { let path = self.scripts_dir.join(name); let mut file ...
tempdir
identifier_name
main.rs
#[macro_use] extern crate serde_derive; extern crate clap; extern crate hyper; extern crate reqwest; extern crate serde_json; mod json_response; use crate::json_response::{BringResponse, ErrorConsignmentSet, Eventset, Packageset}; use clap::{App, AppSettings, Arg}; use reqwest::Error; #[tokio::main] async fn main() ...
match deserialized { Ok(deserialized) => { eprintln!( "Error: {}, Code:{}", deserialized.error.message, deserialized.error.code ); } Err(e) => eprintln!( "Error while deserializing, please check if your tracking number is va...
let deserialized: Result<ErrorConsignmentSet, serde_json::Error> = serde_json::from_str(&buf);
random_line_split
main.rs
#[macro_use] extern crate serde_derive; extern crate clap; extern crate hyper; extern crate reqwest; extern crate serde_json; mod json_response; use crate::json_response::{BringResponse, ErrorConsignmentSet, Eventset, Packageset}; use clap::{App, AppSettings, Arg}; use reqwest::Error; #[tokio::main] async fn main() ...
(buf: &String) { let deserialized: Result<ErrorConsignmentSet, serde_json::Error> = serde_json::from_str(&buf); match deserialized { Ok(deserialized) => { eprintln!( "Error: {}, Code:{}", deserialized.error.message, deserialized.error.code ); ...
deserialize_err
identifier_name
main.rs
#[macro_use] extern crate serde_derive; extern crate clap; extern crate hyper; extern crate reqwest; extern crate serde_json; mod json_response; use crate::json_response::{BringResponse, ErrorConsignmentSet, Eventset, Packageset}; use clap::{App, AppSettings, Arg}; use reqwest::Error; #[tokio::main] async fn main() ...
} async fn deserialize(buf: String) { let deserialized: Result<BringResponse, serde_json::Error> = serde_json::from_str(buf.trim()); match deserialized { Ok(deserialized) => { let sets = deserialized.consignment_set; for i in 0..sets.len() { let consignment_set...
{ let matches = App::new("Rosten") .version("0.1.1") .author("Stian Eklund. <stian.eklund@gmail.com>") .about("Get shipment status of your Bring & Posten packages") .setting(AppSettings::ArgRequiredElseHelp) .arg( Arg::with_name("track") .short("t"...
identifier_body
mercurial.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::io::Write; use anyhow::Result; use manifest::{Entry, Manifest}; use mercurial_types::blobs::HgBlobManifest; use unicode_truncate:...
ty, )?; } Ok(()) }
{ let entries = manifest .list() .map(|(name, entry)| (String::from_utf8_lossy(name.as_ref()).into_owned(), entry)) .collect::<Vec<_>>(); let max_width = entries .iter() .map(|(name, _)| name.width()) .max() .unwrap_or(0); for (name, entry) in entries ...
identifier_body
mercurial.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::io::Write; use anyhow::Result; use manifest::{Entry, Manifest}; use mercurial_types::blobs::HgBlobManifest; use unicode_truncate:...
(mut w: impl Write, manifest: &HgBlobManifest) -> Result<()> { let entries = manifest .list() .map(|(name, entry)| (String::from_utf8_lossy(name.as_ref()).into_owned(), entry)) .collect::<Vec<_>>(); let max_width = entries .iter() .map(|(name, _)| name.width()) .max() ...
display_hg_manifest
identifier_name
mercurial.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::io::Write; use anyhow::Result; use manifest::{Entry, Manifest}; use mercurial_types::blobs::HgBlobManifest; use unicode_truncate:...
.list() .map(|(name, entry)| (String::from_utf8_lossy(name.as_ref()).into_owned(), entry)) .collect::<Vec<_>>(); let max_width = entries .iter() .map(|(name, _)| name.width()) .max() .unwrap_or(0); for (name, entry) in entries { let (ty, id) = match entry...
use unicode_width::UnicodeWidthStr; /// Displays a Mercurial manifest, one entry per line. pub fn display_hg_manifest(mut w: impl Write, manifest: &HgBlobManifest) -> Result<()> { let entries = manifest
random_line_split
fixed-point-bind-unique.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 ...
else { n * f(n - 1) }; } pub fn main() { let fact = fix(fact_); assert_eq!(fact(5), 120); assert_eq!(fact(2), 2); }
{ 1 }
conditional_block
fixed-point-bind-unique.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 ...
fn fact_(f: @fn(v: int) -> int, n: int) -> int { // fun fact 0 = 1 return if n == 0 { 1 } else { n * f(n - 1) }; } pub fn main() { let fact = fix(fact_); assert_eq!(fact(5), 120); assert_eq!(fact(2), 2); }
{ return |a| fix_help(f, a); }
identifier_body
fixed-point-bind-unique.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 ...
<A:'static,B:Send>(f: extern fn(@fn(A) -> B, A) -> B) -> @fn(A) -> B { return |a| fix_help(f, a); } fn fact_(f: @fn(v: int) -> int, n: int) -> int { // fun fact 0 = 1 return if n == 0 { 1 } else { n * f(n - 1) }; } pub fn main() { let fact = fix(fact_); assert_eq!(fact(5), 120); assert_eq!(fac...
fix
identifier_name
fixed-point-bind-unique.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 fact = fix(fact_); assert_eq!(fact(5), 120); assert_eq!(fact(2), 2); }
random_line_split
issue-15167.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 ...
() -> (){ for n in 0..1 { println!("{}", f!()); //~ ERROR unresolved name `n` } }
main
identifier_name
issue-15167.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 ...
{ for n in 0..1 { println!("{}", f!()); //~ ERROR unresolved name `n` } }
identifier_body
issue-15167.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 ...
// // Ignored because `for` loops are not hygienic yet; they will require special // handling since they introduce a new pattern binding position. // ignore-test macro_rules! f { () => (n) } fn main() -> (){ for n in 0..1 { println!("{}", f!()); //~ ERROR unresolved name `n` } }
// except according to those terms. // macro f should not be able to inject a reference to 'n'.
random_line_split
reminder.rs
use typemap_rev::TypeMapKey; use crate::database::reminders::{Reminder, RemindersRepository}; use crate::util::now; use serenity::model::id::{ChannelId, GuildId}; use serenity::model::user::User; use std::time::Duration; use tracing::error; impl TypeMapKey for ReminderService { type Value = ReminderService; } pu...
}
{ let _ = self .repository .invalidate_reminder(id) .await .map_err(|err| { error!("failed to invalidate reminder {:?}", err); err }); }
identifier_body
reminder.rs
use typemap_rev::TypeMapKey; use crate::database::reminders::{Reminder, RemindersRepository}; use crate::util::now; use serenity::model::id::{ChannelId, GuildId}; use serenity::model::user::User; use std::time::Duration; use tracing::error; impl TypeMapKey for ReminderService { type Value = ReminderService; } pu...
pub async fn create_reminder( &self, guild_id: GuildId, channel_id: ChannelId, user: &User, duration: Option<Duration>, message: String, ) -> Result<(), CreateReminderFailure> { let now = now(); let remind_time = duration .map(|duration|...
random_line_split
reminder.rs
use typemap_rev::TypeMapKey; use crate::database::reminders::{Reminder, RemindersRepository}; use crate::util::now; use serenity::model::id::{ChannelId, GuildId}; use serenity::model::user::User; use std::time::Duration; use tracing::error; impl TypeMapKey for ReminderService { type Value = ReminderService; } pu...
{ pub repository: RemindersRepository, } pub enum CreateReminderFailure { Unknown, } impl ReminderService { pub async fn fetch_expired_reminders(&self) -> Vec<Reminder> { self.repository .fetch_expired_reminders() .await .map_err(|err| { error!("fa...
ReminderService
identifier_name
util.rs
use std::collections::HashSet; use std::fmt; use std::net::IpAddr; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use futures::{Async, Future, Poll}; use ifaces; use url::Url; use pb::HostPortPb; use timestamp::DateTime; use DataType; use Error; use Row; pub fn time_to_us(time: SystemTime) -> i64 { // TODO: ...
} pub fn fmt_hex<T>(f: &mut fmt::Formatter, bytes: &[T]) -> fmt::Result where T: fmt::LowerHex, { write!(f, "0x")?; for b in bytes { write!(f, "{:02x}", b)?; } Ok(()) } fn fmt_timestamp(timestamp: SystemTime) -> impl fmt::Display { DateTime::from(timestamp) } pub fn fmt_cell(f: &mut ...
{ UNIX_EPOCH + Duration::new(s, ns) }
conditional_block