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
test.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 ...
(&mut self) { unsafe { llvm::LLVMDisposeExecutionEngine(self.ee) }; } } /// Returns last error from LLVM wrapper code. fn llvm_error() -> String { String::from_utf8_lossy( unsafe { CStr::from_ptr(llvm::LLVMRustGetLastError()).to_bytes() }) .into_owned() } fn build_exec_options(sysroot: ...
drop
identifier_name
test.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 Drop for ExecutionEngine { fn drop(&mut self) { unsafe { llvm::LLVMDisposeExecutionEngine(self.ee) }; } } /// Returns last error from LLVM wrapper code. fn llvm_error() -> String { String::from_utf8_lossy( unsafe { CStr::from_ptr(llvm::LLVMRustGetLastError()).to_byt...
{ panic!("Failed to load crate {:?}: {}", path.display(), llvm_error()); }
conditional_block
test.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 ...
/// Compiles input up to phase 4, translation to LLVM. /// /// Returns the LLVM `ModuleRef` and a series of paths to dynamic libraries /// for crates used in the given input. fn compile_program(input: &str, sysroot: PathBuf) -> Option<(llvm::ModuleRef, Vec<PathBuf>)> { let input = Input::Str(in...
{ let mut opts = basic_options(); // librustc derives sysroot from the executable name. // Since we are not rustc, we must specify it. opts.maybe_sysroot = Some(sysroot); // Prefer faster build time opts.optimize = config::No; // Don't require a `main` function opts.crate_types = vec!...
identifier_body
test.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 ...
for &m in &self.modules { let gv = unsafe { llvm::LLVMGetNamedGlobal(m, s.as_ptr()) }; if!gv.is_null() { let gp = unsafe { llvm::LLVMGetPointerToGlobal(self.ee, gv) }; assert!(!gp.is_null()); return Some(gp); } } ...
/// Returns a raw pointer to the named global item. pub fn get_global(&mut self, name: &str) -> Option<*const ()> { let s = CString::new(name.as_bytes()).unwrap();
random_line_split
lib.rs
extern crate fringe; extern crate tokio_core; #[macro_use(task_local)] extern crate futures; use futures::Async; use std::cell::{RefCell, UnsafeCell}; /// Convenient macro to suspend and retry async operation /// just as it was blocking operation #[macro_export] macro_rules! poll { ($e:expr) => {{ let re...
<'a>(y : &'a Yield) -> YielderRefStore { YielderRefStore ( UnsafeCell::new(std::mem::transmute(y)) ) } } unsafe impl Send for YielderRefStore {} // Wrapper over `fringe::Yielder` to make put it in `task_local` trait Yield { fn suspend(&self); } impl<I : Send, O : Send, E : Send> ...
new
identifier_name
lib.rs
extern crate fringe; extern crate tokio_core; #[macro_use(task_local)] extern crate futures; use futures::Async; use std::cell::{RefCell, UnsafeCell}; /// Convenient macro to suspend and retry async operation /// just as it was blocking operation #[macro_export] macro_rules! poll { ($e:expr) => {{ let re...
/// Block current fiber. It will be resumed and thus this function will return, /// when the event loop decides it might be ready. This includes: previously /// blocked IO becoming unblocked etc. pub fn yield_now() { let y = unsafe { yielder_tl_pop() }; y.suspend(); unsafe { yielder_tl_push(y) } } /// Bl...
///
random_line_split
lib.rs
extern crate fringe; extern crate tokio_core; #[macro_use(task_local)] extern crate futures; use futures::Async; use std::cell::{RefCell, UnsafeCell}; /// Convenient macro to suspend and retry async operation /// just as it was blocking operation #[macro_export] macro_rules! poll { ($e:expr) => {{ let re...
/// Block current fiber to wait for result of another future pub fn await<F: futures::Future>(mut f: F) -> Result<F::Item, F::Error> { loop { match f.poll() { Ok(Async::NotReady) => yield_now(), Ok(Async::Ready(val)) => return Ok(val), Err(e) => return Err(e), }...
{ let y = unsafe { yielder_tl_pop() }; y.suspend(); unsafe { yielder_tl_push(y) } }
identifier_body
lib.rs
// Copyright 2016 Alexander Reece // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according...
try!(writeln!(writer, "}}")); Ok(()) } } impl<'a> Class<'a> { pub fn name(&self) -> &str { &self.name } pub fn fields(&self) -> &[ClassField<'a>] { &self.fields } pub fn index(&self) -> &str { &self.index } pub fn methods(&self) -> &[ClassMeth...
try!(writeln!(writer, "response_codes: {},", codegen::format_to_map(response_codes.into_iter()))); try!(writeln!(writer, "version: {},", self.version().format_rust()));
random_line_split
lib.rs
// Copyright 2016 Alexander Reece // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according...
<W>(&self, name: &str, writer: &mut W) -> io::Result<()> where W: io::Write { let (ungrouped, frame_types, response_codes) = { let (mut ungrouped, mut frame_types, mut response_codes) = (vec![], vec![], vec![]); #[allow(match_same_arms)] for constant in self.const...
write_generated
identifier_name
enemy.rs
use utils::*; use constants::*; use structures::*; use nalgebra::*; use interlude::*; use rand; use rand::distributions::*; use super::bullet::*; use std::rc::*; use utils; use {GameTime, GameUpdateArgs}; fn store_quaternion(to: &mut CVector4, q: &Quaternion<f32>) { *to = [q.i, q.j, q.k, q.w]; } pub struct EnemyDat...
{ squads: EnemySquads::new(), engine: ManagerEngine::begin(executions) } } pub fn update<AppearFn>(&mut self, update_args: &mut GameUpdateArgs, mut appear: AppearFn) where AppearFn: FnMut(f32, f32, &Rc<spawn_group::EntityLivings>, usize) -> Option<u32> { self.engine.update(update_args, &mut self.squads);...
{ /* extern mgr: &mut EnemySquads; extern args: &GameUpdateArgs; loop { mgr.spawn_squad(spawn_group::strategies::RandomFall(0.1, 10)); yield WaitForAllSquads; yield Delay(2.5); } */ fn eternal_loop(mgr: &mut EnemySquads, _: &mut GameUpdateArgs) -> ManagerExecuteState { mgr.spawn_s...
identifier_body
enemy.rs
use utils::*; use constants::*; use structures::*; use nalgebra::*; use interlude::*; use rand; use rand::distributions::*; use super::bullet::*; use std::rc::*; use utils; use {GameTime, GameUpdateArgs}; fn store_quaternion(to: &mut CVector4, q: &Quaternion<f32>) { *to = [q.i, q.j, q.k, q.w]; } pub struct EnemyDat...
(None, Some(newpos)) } }, _ => (None, None) }; if let Some(gb) = gb_index { *self = Enemy::Garbage(gb); } np } pub fn is_garbage(&self) -> bool { match self { &Enemy::Garbage(_) => true, _ => false } } } /// Enemy Spawn Group pub mod spawn_group { use super::{GameTime, GameUpdateArg...
{ *next = n; }
conditional_block
enemy.rs
use utils::*; use constants::*; use structures::*; use nalgebra::*; use interlude::*; use rand; use rand::distributions::*; use super::bullet::*; use std::rc::*; use utils; use {GameTime, GameUpdateArgs}; fn store_quaternion(to: &mut CVector4, q: &Quaternion<f32>) { *to = [q.i, q.j, q.k, q.w]; } pub struct EnemyData...
self.1 = nc; } if let Term = self.1 { false } else { true } } } pub enum LivingState { Left, Dead } pub struct ClassifiedLivingStates { list: Vec<(u32, LivingState)>, lefts: usize } impl ClassifiedLivingStates { pub fn new() -> Self { ClassifiedLivingStates { list: Vec::new(), lefts: 0 } } pub fn n...
{ self.0 = 0.0;
random_line_split
enemy.rs
use utils::*; use constants::*; use structures::*; use nalgebra::*; use interlude::*; use rand; use rand::distributions::*; use super::bullet::*; use std::rc::*; use utils; use {GameTime, GameUpdateArgs}; fn store_quaternion(to: &mut CVector4, q: &Quaternion<f32>) { *to = [q.i, q.j, q.k, q.w]; } pub struct EnemyDat...
<Strategy: spawn_group::SpawnStrategy>(&mut self, strategy: Strategy) { if let Some(n) = self.freelist.allocate() { self.objects[n as usize] = Some(EnemyGroup::new(strategy)); } else { self.objects.push(Some(EnemyGroup::new(strategy))); } self.left += 1; } fn update_all(&mut self, update_args: &m...
spawn_squad
identifier_name
hello.rs
extern crate timely_communication; fn main() { // configure for two threads, just one process. let config = timely_communication::Configuration::Process(2); // initailizes communication, spawns workers let guards = timely_communication::initialize(config, |mut allocator| { println!("worker {} ...
}
{ println!("error in computation"); }
conditional_block
hello.rs
extern crate timely_communication; fn
() { // configure for two threads, just one process. let config = timely_communication::Configuration::Process(2); // initailizes communication, spawns workers let guards = timely_communication::initialize(config, |mut allocator| { println!("worker {} started", allocator.index()); // a...
main
identifier_name
hello.rs
extern crate timely_communication; fn main()
println!("worker {}: received: <{}>", allocator.index(), message); expecting -= 1; } } allocator.index() }); // computation runs until guards are joined or dropped. if let Ok(guards) = guards { for guard in guards.join() { pri...
{ // configure for two threads, just one process. let config = timely_communication::Configuration::Process(2); // initailizes communication, spawns workers let guards = timely_communication::initialize(config, |mut allocator| { println!("worker {} started", allocator.index()); // allo...
identifier_body
hello.rs
extern crate timely_communication; fn main() { // configure for two threads, just one process. let config = timely_communication::Configuration::Process(2); // initailizes communication, spawns workers let guards = timely_communication::initialize(config, |mut allocator| { println!("worker {} ...
// we have to count down ourselves. let mut expecting = 2; while expecting > 0 { if let Some(message) = receiver.recv() { println!("worker {}: received: <{}>", allocator.index(), message); expecting -= 1; } } allocator.inde...
// send typed data along each channel senders[0].send(format!("hello, {}", 0)); senders[1].send(format!("hello, {}", 1)); // no support for termination notification,
random_line_split
ckms_u32.rs
#![no_main] #[macro_use] extern crate libfuzzer_sys; extern crate quantiles; extern crate byteorder; use std::io::Cursor; use byteorder::{BigEndian, ReadBytesExt}; #[derive(Debug, Clone, Copy)] pub struct Xorshift { seed: u64, } impl Xorshift { pub fn new(seed: u64) -> Xorshift { Xorshift { seed: see...
(&mut self) -> u32 { // implementation inspired by // https://github.com/astocko/xorshift/blob/master/src/splitmix64.rs use std::num::Wrapping as w; let mut z = w(self.seed) + w(0x9E37_79B9_7F4A_7C15_u64); let nxt_seed = z.0; z = (z ^ (z >> 30)) * w(0xBF58_476D_1CE4_E5B9...
next_val
identifier_name
ckms_u32.rs
#![no_main] #[macro_use] extern crate libfuzzer_sys; extern crate quantiles; extern crate byteorder; use std::io::Cursor; use byteorder::{BigEndian, ReadBytesExt}; #[derive(Debug, Clone, Copy)] pub struct Xorshift { seed: u64, } impl Xorshift { pub fn new(seed: u64) -> Xorshift { Xorshift { seed: see...
z = (z ^ (z >> 27)) * w(0x94D0_49BB_1331_11EB_u64); self.seed = nxt_seed; u32::from((z ^ (z >> 31)).0 as u16) } } fuzz_target!(|data: &[u8]| { let mut cursor = Cursor::new(data); // unbounded, CKMS will adjust to within bounds let error: f64 = if let Ok(res) = cursor.read_f64:...
random_line_split
ckms_u32.rs
#![no_main] #[macro_use] extern crate libfuzzer_sys; extern crate quantiles; extern crate byteorder; use std::io::Cursor; use byteorder::{BigEndian, ReadBytesExt}; #[derive(Debug, Clone, Copy)] pub struct Xorshift { seed: u64, } impl Xorshift { pub fn new(seed: u64) -> Xorshift
pub fn next_val(&mut self) -> u32 { // implementation inspired by // https://github.com/astocko/xorshift/blob/master/src/splitmix64.rs use std::num::Wrapping as w; let mut z = w(self.seed) + w(0x9E37_79B9_7F4A_7C15_u64); let nxt_seed = z.0; z = (z ^ (z >> 30)) * w(...
{ Xorshift { seed: seed } }
identifier_body
imports.rs
// Imports. // Long import. use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl}; use exceedingly::looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong::import::path::{ItemA, ...
() { use Baz::*; use Qux; } // Simple imports use foo::bar::baz; use bar::quux as kaas; use foo; // With aliases. use foo::{self as bar, baz}; use foo as bar; use foo::qux as bar; use foo::{baz, qux as bar}; // With absolute paths use ::foo; use ::foo::Bar; use ::foo::{Bar, Baz}; use ::Foo; use ::{Bar, Baz};...
test
identifier_name
imports.rs
// Imports. // Long import. use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl}; use exceedingly::looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong::import::path::{ItemA, ...
// Simple imports use foo::bar::baz; use bar::quux as kaas; use foo; // With aliases. use foo::{self as bar, baz}; use foo as bar; use foo::qux as bar; use foo::{baz, qux as bar}; // With absolute paths use ::foo; use ::foo::Bar; use ::foo::{Bar, Baz}; use ::Foo; use ::{Bar, Baz};
{ use Baz::*; use Qux; }
identifier_body
imports.rs
// Imports. // Long import. use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl}; use exceedingly::looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong::import::path::{ItemA, ...
use Foo::{Bar, Baz}; pub use syntax::ast::{Expr_, Expr, ExprAssign, ExprCall, ExprMethodCall, ExprPath}; mod Foo { pub use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl}; mod Foo2 { pub use syntax::ast::{self, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStat...
use syntax; use {/* Pre-comment! */ Foo, Bar /* comment */};
random_line_split
static.rs
// Compiler: // // Run-time: // status: 0 // stdout: 10 // 14 // 1 // 12 // 12 // 1 #![feature(auto_traits, lang_items, no_core, start, intrinsics)] #![no_std] #![no_core] /* * Core */ // Because we don't have core yet. #[lang = "sized"] pub trait Sized {} #[lang = "copy"] trait Copy...
} struct WithRef { refe: &'static Test, } static mut CONSTANT: isize = 10; static mut TEST: Test = Test { field: 12, }; static mut TEST2: Test = Test { field: 14, }; static mut WITH_REF: WithRef = WithRef { refe: unsafe { &TEST }, }; #[start] fn main(mut argc: isize, _argv: *const *const u8) -> is...
field: isize,
random_line_split
static.rs
// Compiler: // // Run-time: // status: 0 // stdout: 10 // 14 // 1 // 12 // 12 // 1 #![feature(auto_traits, lang_items, no_core, start, intrinsics)] #![no_std] #![no_core] /* * Core */ // Because we don't have core yet. #[lang = "sized"] pub trait Sized {} #[lang = "copy"] trait Copy...
{ unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, CONSTANT); libc::printf(b"%ld\n\0" as *const u8 as *const i8, TEST2.field); TEST2.field = argc; libc::printf(b"%ld\n\0" as *const u8 as *const i8, TEST2.field); libc::printf(b"%ld\n\0" as *const u8 as *const i8, WI...
identifier_body
static.rs
// Compiler: // // Run-time: // status: 0 // stdout: 10 // 14 // 1 // 12 // 12 // 1 #![feature(auto_traits, lang_items, no_core, start, intrinsics)] #![no_std] #![no_core] /* * Core */ // Because we don't have core yet. #[lang = "sized"] pub trait Sized {} #[lang = "copy"] trait Copy...
{ refe: &'static Test, } static mut CONSTANT: isize = 10; static mut TEST: Test = Test { field: 12, }; static mut TEST2: Test = Test { field: 14, }; static mut WITH_REF: WithRef = WithRef { refe: unsafe { &TEST }, }; #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { unsafe ...
WithRef
identifier_name
htmlbodyelement.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::Attr; use dom::bindings::codegen::Bindings::EventHandlerBinding::{EventHandler...
impl HTMLBodyElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLBodyElement { HTMLBodyElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), } } #[allow(unrooted_must_root)] pub fn...
pub struct HTMLBodyElement { htmlelement: HTMLElement, }
random_line_split
htmlbodyelement.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::Attr; use dom::bindings::codegen::Bindings::EventHandlerBinding::{EventHandler...
} _ => true, // HTMLElement::attribute_mutated will take care of this. } }, _ => true, }; if do_super_mutate { self.super_type().unwrap().attribute_mutated(attr, mutation); } } }
{ let do_super_mutate = match (attr.local_name(), mutation) { (name, AttributeMutation::Set(_)) if name.starts_with("on") => { let window = window_from_node(self); // https://html.spec.whatwg.org/multipage/ // #event-handlers-on-elements,-document-obje...
identifier_body
htmlbodyelement.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::Attr; use dom::bindings::codegen::Bindings::EventHandlerBinding::{EventHandler...
(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLBodyElement { HTMLBodyElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMStri...
new_inherited
identifier_name
xc.rs
pub struct Something { pub x: isize } pub trait A { fn f(&self) -> isize; fn g(&self) -> isize { 10 } fn h(&self) -> isize { 11 } fn lurr(x: &Self, y: &Self) -> isize { x.g() + y.h() } } impl A for isize { fn f(&self) -> isize { 10 } } impl A for Something { fn f(&self) -> isize { 10 } } pu...
}
impl TestEquality for isize { fn test_eq(&self, rhs: &isize) -> bool { *self == *rhs }
random_line_split
xc.rs
pub struct Something { pub x: isize } pub trait A { fn f(&self) -> isize; fn g(&self) -> isize { 10 } fn
(&self) -> isize { 11 } fn lurr(x: &Self, y: &Self) -> isize { x.g() + y.h() } } impl A for isize { fn f(&self) -> isize { 10 } } impl A for Something { fn f(&self) -> isize { 10 } } pub trait B<T> { fn thing<U>(&self, x: T, y: U) -> (T, U) { (x, y) } fn staticthing<U>(_z: &Self, x: T, y: U) -> ...
h
identifier_name
xc.rs
pub struct Something { pub x: isize } pub trait A { fn f(&self) -> isize; fn g(&self) -> isize { 10 } fn h(&self) -> isize { 11 } fn lurr(x: &Self, y: &Self) -> isize { x.g() + y.h() } } impl A for isize { fn f(&self) -> isize { 10 } } impl A for Something { fn f(&self) -> isize
} pub trait B<T> { fn thing<U>(&self, x: T, y: U) -> (T, U) { (x, y) } fn staticthing<U>(_z: &Self, x: T, y: U) -> (T, U) { (x, y) } } impl<T> B<T> for isize { } impl B<f64> for bool { } pub trait TestEquality { fn test_eq(&self, rhs: &Self) -> bool; fn test_neq(&self, rhs: &Self) -> bool { ...
{ 10 }
identifier_body
worker.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 https://mozilla.org/MPL/2.0/. */ use crate::compartments::enter_realm; use crate::dom::abstractworker::SimpleWorkerErrorHandler; use crate::dom::a...
}, )); Ok(()) } } impl WorkerMethods for Worker { /// https://html.spec.whatwg.org/multipage/#dom-worker-postmessage fn PostMessage( &self, cx: JSContext, message: HandleValue, transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>, ) -> ErrorRes...
random_line_split
worker.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 https://mozilla.org/MPL/2.0/. */ use crate::compartments::enter_realm; use crate::dom::abstractworker::SimpleWorkerErrorHandler; use crate::dom::a...
let worker_id = WorkerId(Uuid::new_v4()); if let Some(ref chan) = global.devtools_chan() { let pipeline_id = global.pipeline_id(); let title = format!("Worker for {}", worker_url); let page_info = DevtoolsPageInfo { title: title, url: w...
{ // Step 2-4. let worker_url = match global.api_base_url().join(&script_url) { Ok(url) => url, Err(_) => return Err(Error::Syntax), }; let (sender, receiver) = unbounded(); let closing = Arc::new(AtomicBool::new(false)); let worker = Worker::new(...
identifier_body
worker.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 https://mozilla.org/MPL/2.0/. */ use crate::compartments::enter_realm; use crate::dom::abstractworker::SimpleWorkerErrorHandler; use crate::dom::a...
( &self, cx: JSContext, message: HandleValue, transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>, ) -> ErrorResult { self.post_message_impl(cx, message, transfer) } /// https://html.spec.whatwg.org/multipage/#dom-worker-postmessage fn PostMessage_( &self...
PostMessage
identifier_name
worker.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 https://mozilla.org/MPL/2.0/. */ use crate::compartments::enter_realm; use crate::dom::abstractworker::SimpleWorkerErrorHandler; use crate::dom::a...
let global = worker.global(); let target = worker.upcast(); let _ac = enter_realm(target); rooted!(in(*global.get_cx()) let mut message = UndefinedValue()); if let Ok(ports) = structuredclone::read(&global, data, message.handle_mut()) { MessageEvent::dispatch_jsval(...
{ return; }
conditional_block
ex_7.rs
/* Copyright © 2013 Free Software Foundation, Inc See licensing in LICENSE file File: examples/ex_7.rs Author: Jesse 'Jeaye' Wilkerson Description: Basic input and attribute example, using the Unicode-aware get_wch functions. */ extern crate ncurses; use std::char; use ncurses::*; fn main(...
keypad(stdscr(), true); noecho(); /* Prompt for a character. */ printw("Enter a character within 2 seconds: "); /* Wait for input. */ let ch = wget_wch(stdscr()); match ch { Some(WchResult::KeyCode(KEY_MOUSE)) => { /* Enable attributes and output message. */ attron(A_BOLD() | A_BLINK());...
/* Enable mouse events. */ mousemask(ALL_MOUSE_EVENTS as mmask_t, None); /* Allow for extended keyboard (like F1). */
random_line_split
ex_7.rs
/* Copyright © 2013 Free Software Foundation, Inc See licensing in LICENSE file File: examples/ex_7.rs Author: Jesse 'Jeaye' Wilkerson Description: Basic input and attribute example, using the Unicode-aware get_wch functions. */ extern crate ncurses; use std::char; use ncurses::*; fn main(...
/* Wait for input. */ let ch = wget_wch(stdscr()); match ch { Some(WchResult::KeyCode(KEY_MOUSE)) => { /* Enable attributes and output message. */ attron(A_BOLD() | A_BLINK()); printw("\nMouse"); attroff(A_BOLD() | A_BLINK()); printw(" pressed"); } Some(WchResult::KeyCod...
let locale_conf = LcCategory::all; setlocale(locale_conf, "en_US.UTF-8"); /* Setup ncurses. */ initscr(); raw(); /* Require input within 2 seconds. */ halfdelay(20); /* Enable mouse events. */ mousemask(ALL_MOUSE_EVENTS as mmask_t, None); /* Allow for extended keyboard (like F1). */ keypad(std...
identifier_body
ex_7.rs
/* Copyright © 2013 Free Software Foundation, Inc See licensing in LICENSE file File: examples/ex_7.rs Author: Jesse 'Jeaye' Wilkerson Description: Basic input and attribute example, using the Unicode-aware get_wch functions. */ extern crate ncurses; use std::char; use ncurses::*; fn m
) { let locale_conf = LcCategory::all; setlocale(locale_conf, "en_US.UTF-8"); /* Setup ncurses. */ initscr(); raw(); /* Require input within 2 seconds. */ halfdelay(20); /* Enable mouse events. */ mousemask(ALL_MOUSE_EVENTS as mmask_t, None); /* Allow for extended keyboard (like F1). */ keypad(...
ain(
identifier_name
ex_7.rs
/* Copyright © 2013 Free Software Foundation, Inc See licensing in LICENSE file File: examples/ex_7.rs Author: Jesse 'Jeaye' Wilkerson Description: Basic input and attribute example, using the Unicode-aware get_wch functions. */ extern crate ncurses; use std::char; use ncurses::*; fn main(...
None => { printw("\nYou didn't enter a character in time!"); } } /* Refresh, showing the previous message. */ refresh(); /* Wait for one more character before exiting. Disable the input timeout. */ nocbreak(); getch(); endwin(); }
/* Enable attributes and output message. */ printw("\nKey pressed: "); attron(A_BOLD() | A_BLINK()); printw(format!("{}\n", char::from_u32(c as u32).expect("Invalid char")).as_ref()); attroff(A_BOLD() | A_BLINK()); }
conditional_block
shootout-nbody.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "1000".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "1000".to_owned()) } else { args.move_iter().collect() }; let n: i32 = from_str::<i32>(*args.get(1)).unwrap...
identifier_body
shootout-nbody.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 ...
d[k] = bodies[i].x[k] - bodies[j].x[k]; } let dist = (d[0]*d[0] + d[1]*d[1] + d[2]*d[2]).sqrt(); e -= bodies[i].mass * bodies[j].mass / dist; } } e } fn offset_momentum(bodies: &mut [Planet,..N_BODIES]) { for i in range(0u, N_BODIES) { for...
random_line_split
shootout-nbody.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 ...
(bodies: &mut [Planet,..N_BODIES]) { for i in range(0u, N_BODIES) { for k in range(0u, 3) { bodies[0].v[k] -= bodies[i].v[k] * bodies[i].mass / SOLAR_MASS; } } } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(),...
offset_momentum
identifier_name
cmd_keymgmt.rs
//- // Copyright (c) 2017, 2021, Jason Lingle // // This file is part of Ensync. // // Ensync 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...
} Ok(()) } pub fn change_key( config: &Config, storage: &dyn Storage, old: &PassphraseConfig, new: &PassphraseConfig, root: &PassphraseConfig, name: Option<&str>, allow_change_via_other_passphrase: bool, ) -> Result<()> { let old_pass = old.read_passphrase("old passphrase", fal...
{ fn format_date(date: Option<&DateTime<Utc>>) -> String { if let Some(date) = date { super::format_date::format_date(date) } else { "never".to_owned() } } let keys = keymgmt::list_keys(storage)?; for key in keys { print!("{}:", key.name); ...
identifier_body
cmd_keymgmt.rs
//- // Copyright (c) 2017, 2021, Jason Lingle // // This file is part of Ensync. // // Ensync 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...
<IT: Iterator + Clone>( storage: &dyn Storage, key: &PassphraseConfig, root: &PassphraseConfig, names: IT, ) -> Result<()> where IT::Item: AsRef<str>, { let pass = key.read_passphrase("passphrase", false)?; keymgmt::create_group(storage, &pass, names, root_prompt!(root)) } pub fn assoc_gro...
create_group
identifier_name
cmd_keymgmt.rs
//- // Copyright (c) 2017, 2021, Jason Lingle // // This file is part of Ensync. // // Ensync 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...
will no longer be accessible. This cannot be undone. This means that if you \n\ have a write-protected directory with one of these groups, it will be \n\ impossible to remove it. If you have a read-protected directory with one of \n\ these groups, it and its contents WILL BE RENDERED UNRECOVERABLE FOREVER.\n\ \n\ If yo...
random_line_split
cmd_keymgmt.rs
//- // Copyright (c) 2017, 2021, Jason Lingle // // This file is part of Ensync. // // Ensync 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...
} let keys = keymgmt::list_keys(storage)?; for key in keys { print!("{}:", key.name); for group in &key.groups { print!(" {}", group); } println!(""); println!(" algorithm: {}", key.algorithm); println!(" created: {}", format_date(Some(...
{ "never".to_owned() }
conditional_block
attr.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::{DomRefCell, Ref}; use crate::dom::bindings::codegen::Bindings::AttrBinding::Attr...
// https://dom.spec.whatwg.org/#dom-attr-ownerelement fn GetOwnerElement(&self) -> Option<DomRoot<Element>> { self.owner() } // https://dom.spec.whatwg.org/#dom-attr-specified fn Specified(&self) -> bool { true // Always returns true } } impl Attr { pub fn set_value(&self...
{ // FIXME(ajeffrey): convert directly from LocalName to DOMString self.prefix().map(|p| DOMString::from(&**p)) }
identifier_body
attr.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::{DomRefCell, Ref}; use crate::dom::bindings::codegen::Bindings::AttrBinding::Attr...
(&self) -> &LocalName { &self.identifier.local_name } /// Sets the owner element. Should be called after the attribute is added /// or removed from its older parent. pub fn set_owner(&self, owner: Option<&Element>) { let ns = self.namespace(); match (self.owner(), owner) { ...
local_name
identifier_name
attr.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::{DomRefCell, Ref}; use crate::dom::bindings::codegen::Bindings::AttrBinding::Attr...
} impl Attr { fn new_inherited( document: &Document, local_name: LocalName, value: AttrValue, name: LocalName, namespace: Namespace, prefix: Option<Prefix>, owner: Option<&Element>, ) -> Attr { Attr { node_: Node::new_inherited(documen...
random_line_split
attr.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::{DomRefCell, Ref}; use crate::dom::bindings::codegen::Bindings::AttrBinding::Attr...
} // https://dom.spec.whatwg.org/#dom-attr-name fn Name(&self) -> DOMString { // FIXME(ajeffrey): convert directly from LocalName to DOMString DOMString::from(&**self.name()) } // https://dom.spec.whatwg.org/#dom-attr-namespaceuri fn GetNamespaceURI(&self) -> Option<DOMString>...
{ *self.value.borrow_mut() = AttrValue::String(value.into()); }
conditional_block
main.rs
use std::fmt; // Minimal implementation of single precision complex numbers #[repr(C)] #[derive(Clone, Copy)] struct Complex { re: f32, im: f32, } impl fmt::Debug for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0. { write!(f, "{}-{}i", self.re, -self....
} } // Foreign functions must be declared inside an extern block // annotated with a #[link] attribute containing the name // of the foreign library. // // this extern block links to the libm library #[link(name = "m")] extern { fn ccosf(z: Complex) -> Complex; } // safe wrapper for foreign function fn cos...
{ write!(f, "{}+{}i", self.re, self.im) }
conditional_block
main.rs
use std::fmt; // Minimal implementation of single precision complex numbers #[repr(C)] #[derive(Clone, Copy)] struct Complex { re: f32, im: f32, } impl fmt::Debug for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0. { write!(f, "{}-{}i", self.re, -self.i...
fn add(lhs: u32, rhs: u32) -> u32; } fn main() { // z = 0 + 1i let z = Complex { re: 0., im: 1. }; println!("cos({:?}) = {:?}", z, cos(z)); println!("1 + 2 = {:?}", unsafe { add(1, 2) }); }
} // the package's native dependency extern {
random_line_split
main.rs
use std::fmt; // Minimal implementation of single precision complex numbers #[repr(C)] #[derive(Clone, Copy)] struct Complex { re: f32, im: f32, } impl fmt::Debug for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0. { write!(f, "{}-{}i", self.re, -self....
() { // z = 0 + 1i let z = Complex { re: 0., im: 1. }; println!("cos({:?}) = {:?}", z, cos(z)); println!("1 + 2 = {:?}", unsafe { add(1, 2) }); }
main
identifier_name
table.rs
use std::collections::HashMap; use rustc_serialize::json::Json; #[derive(Debug)] pub enum TableError { TableDoesNotExist, TableAlreadyExists, KeyAlreadyPresent, KeyDoesNotExist, } pub struct Tables { data: HashMap<String, HashMap<String, Json>> } impl Tables { pub fn new() -> Tables { ...
fn get_mut_table(&mut self, table: &str) -> Result<&mut HashMap<String, Json>, TableError> { match self.data.get_mut(table) { Some(table) => Ok(table), None => Err(TableError::TableDoesNotExist), } } pub fn put(&mut self, table: &str, key: &str, data: Json) -> Result...
random_line_split
table.rs
use std::collections::HashMap; use rustc_serialize::json::Json; #[derive(Debug)] pub enum TableError { TableDoesNotExist, TableAlreadyExists, KeyAlreadyPresent, KeyDoesNotExist, } pub struct Tables { data: HashMap<String, HashMap<String, Json>> } impl Tables { pub fn new() -> Tables { ...
(&mut self, table: &str) -> Result<(), TableError> { match self.data.remove(table) { Some(_) => Ok(()), None => Err(TableError::TableDoesNotExist), } } }
delete_table
identifier_name
table.rs
use std::collections::HashMap; use rustc_serialize::json::Json; #[derive(Debug)] pub enum TableError { TableDoesNotExist, TableAlreadyExists, KeyAlreadyPresent, KeyDoesNotExist, } pub struct Tables { data: HashMap<String, HashMap<String, Json>> } impl Tables { pub fn new() -> Tables { ...
else { self.data.insert(table.to_string(), HashMap::new()); Ok(()) } } fn get_table(&self, table: &str) -> Result<&HashMap<String, Json>, TableError> { match self.data.get(table) { Some(table) => Ok(table), None => Err(TableError::TableDoesNotExi...
{ Err(TableError::TableAlreadyExists) }
conditional_block
task-comm-11.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...
(tx: &Sender<Sender<isize>>) { let (tx2, _rx) = channel(); tx.send(tx2).unwrap(); } pub fn main() { let (tx, rx) = channel(); let _child = thread::scoped(move|| { start(&tx) }); let _tx = rx.recv().unwrap(); }
start
identifier_name
task-comm-11.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 main() { let (tx, rx) = channel(); let _child = thread::scoped(move|| { start(&tx) }); let _tx = rx.recv().unwrap(); }
{ let (tx2, _rx) = channel(); tx.send(tx2).unwrap(); }
identifier_body
task-comm-11.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded ...
// 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. //
random_line_split
percentage.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/. */ //! Computed percentages. use std::fmt; use style_traits::{CssWriter, ToCss};
use values::animated::ToAnimatedValue; use values::generics::NonNegative; /// A computed percentage. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, Default, MallocSizeOf, PartialEq, PartialOrd, SpecifiedValueInfo, ToAnimate...
use values::{serialize_percentage, CSSFloat};
random_line_split
percentage.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/. */ //! Computed percentages. use std::fmt; use style_traits::{CssWriter, ToCss}; use values::{serialize_percentage, ...
(animated: Self::AnimatedValue) -> Self { NonNegative(animated.clamp_to_non_negative()) } }
from_animated_value
identifier_name
percentage.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/. */ //! Computed percentages. use std::fmt; use style_traits::{CssWriter, ToCss}; use values::{serialize_percentage, ...
#[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { NonNegative(animated.clamp_to_non_negative()) } }
{ self.0 }
identifier_body
ConsecutiveKPrimes.rs
fn n_prime(mut n: i32) -> i32 { let mut result = 0; for i in 2..((n as f64).sqrt() as i32) + 1 { while n%i == 0 { result += 1; n /= i; } } if n > 1 { result += 1; } result } fn consec_kprimes(k: i32, arr: Vec<i32>) -> i32 { let mut count ...
(k: i32, arr: Vec<i32>, exp: i32) -> () { assert_eq!(consec_kprimes(k, arr), exp) } fn main() { testing(2, vec![10081, 10071, 10077, 10065, 10060,10070, 10086, 10083, 10078, 10076, 10089, 10085, 10063, 10074, 10068, 10073, 10072, 10075], 2); testing(6, vec![10064], 0...
testing
identifier_name
ConsecutiveKPrimes.rs
fn n_prime(mut n: i32) -> i32 { let mut result = 0; for i in 2..((n as f64).sqrt() as i32) + 1 { while n%i == 0 { result += 1; n /= i; } } if n > 1 { result += 1; } result } fn consec_kprimes(k: i32, arr: Vec<i32>) -> i32
fn testing(k: i32, arr: Vec<i32>, exp: i32) -> () { assert_eq!(consec_kprimes(k, arr), exp) } fn main() { testing(2, vec![10081, 10071, 10077, 10065, 10060,10070, 10086, 10083, 10078, 10076, 10089, 10085, 10063, 10074, 10068, 10073, 10072, 10075], 2); testing(6, ve...
{ let mut count = 0; let mut was_prev = false; for num in arr { if n_prime(num) == k { if was_prev { count += 1; } was_prev = true; } else { was_prev = false; } } count }
identifier_body
ConsecutiveKPrimes.rs
fn n_prime(mut n: i32) -> i32 { let mut result = 0; for i in 2..((n as f64).sqrt() as i32) + 1 { while n%i == 0 { result += 1;
} } if n > 1 { result += 1; } result } fn consec_kprimes(k: i32, arr: Vec<i32>) -> i32 { let mut count = 0; let mut was_prev = false; for num in arr { if n_prime(num) == k { if was_prev { count += 1; } was_prev ...
n /= i;
random_line_split
ConsecutiveKPrimes.rs
fn n_prime(mut n: i32) -> i32 { let mut result = 0; for i in 2..((n as f64).sqrt() as i32) + 1 { while n%i == 0 { result += 1; n /= i; } } if n > 1
result } fn consec_kprimes(k: i32, arr: Vec<i32>) -> i32 { let mut count = 0; let mut was_prev = false; for num in arr { if n_prime(num) == k { if was_prev { count += 1; } was_prev = true; } else { was_prev = false; ...
{ result += 1; }
conditional_block
name.rs
use super::errors::{ErrorKind, Result}; use failchain::{bail, ensure}; use serde::de::{Deserialize, Deserializer, Error as SerdeDeError}; use std::borrow::Borrow; use std::fmt; use std::fmt::Debug; use std::fmt::Display; use std::ops::Deref; use std::result::Result as StdResult; use std::str::{self, FromStr}; #[derive...
(&self) -> &[u8; 8] { self.deref() } } impl AsRef<str> for WadName { fn as_ref(&self) -> &str { str::from_utf8(self.deref()).expect("wad name is not valid utf-8") } } impl<'de> Deserialize<'de> for WadName { fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error> where ...
borrow
identifier_name
name.rs
use super::errors::{ErrorKind, Result}; use failchain::{bail, ensure}; use serde::de::{Deserialize, Deserializer, Error as SerdeDeError}; use std::borrow::Borrow; use std::fmt; use std::fmt::Debug; use std::fmt::Display; use std::ops::Deref; use std::result::Result as StdResult; use std::str::{self, FromStr}; #[derive...
} impl<'de> Deserialize<'de> for WadName { fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error> where D: Deserializer<'de>, { WadName::from_bytes(&<[u8; 8]>::deserialize(deserializer)?).map_err(D::Error::custom) } } pub trait IntoWadName { fn into_wad_name(self) -> Resu...
{ str::from_utf8(self.deref()).expect("wad name is not valid utf-8") }
identifier_body
name.rs
use super::errors::{ErrorKind, Result}; use failchain::{bail, ensure}; use serde::de::{Deserialize, Deserializer, Error as SerdeDeError}; use std::borrow::Borrow; use std::fmt; use std::fmt::Debug; use std::fmt::Display; use std::ops::Deref; use std::result::Result as StdResult; use std::str::{self, FromStr}; #[derive...
} } impl PartialEq<[u8; 8]> for WadName { fn eq(&self, rhs: &[u8; 8]) -> bool { self.deref() == rhs } } impl Borrow<[u8; 8]> for WadName { fn borrow(&self) -> &[u8; 8] { self.deref() } } impl AsRef<str> for WadName { fn as_ref(&self) -> &str { str::from_utf8(self.deref...
write!( formatter, "WadName({:?})", str::from_utf8(&self[..]).unwrap() )
random_line_split
utils.rs
use crate::string_utils::{CaseOperations, WordIterator}; use itertools::Itertools; use std::path::PathBuf; #[test] fn join() { let a1 = vec!["a", "b", "c"]; assert_eq!(a1.join(""), "abc"); assert_eq!(a1.join("_"), "a_b_c"); let a2 = Vec::<String>::new(); assert_eq!(a2.join(""), ""); assert_eq!...
let s6 = "toBase64".to_string(); assert_eq!(s6.to_class_case(), "ToBase64"); assert_eq!(s6.to_snake_case(), "to_base64"); let s7 = "too_many__underscores".to_string(); assert_eq!(s7.to_class_case(), "TooManyUnderscores"); assert_eq!(s7.to_snake_case(), "too_many_underscores"); let s8 = "O...
{ let s1 = "first_second_last".to_string(); assert_eq!(s1.to_class_case(), "FirstSecondLast"); assert_eq!(s1.to_snake_case(), "first_second_last"); let s2 = "FirstSecondLast".to_string(); assert_eq!(s2.to_class_case(), "FirstSecondLast"); assert_eq!(s2.to_snake_case(), "first_second_last"); ...
identifier_body
utils.rs
use crate::string_utils::{CaseOperations, WordIterator}; use itertools::Itertools; use std::path::PathBuf; #[test] fn join() { let a1 = vec!["a", "b", "c"]; assert_eq!(a1.join(""), "abc"); assert_eq!(a1.join("_"), "a_b_c"); let a2 = Vec::<String>::new(); assert_eq!(a2.join(""), ""); assert_eq!...
() { let string = "RustIsAwesome".to_string(); let mut a1 = WordIterator::new(&string); assert_eq!(a1.next(), Some("Rust")); assert_eq!(a1.next(), Some("Is")); assert_eq!(a1.next(), Some("Awesome")); assert_eq!(a1.next(), None); } fn split_to_words(s: &'static str) -> Vec<&'static str> { Wo...
word_iterator2
identifier_name
utils.rs
use crate::string_utils::{CaseOperations, WordIterator}; use itertools::Itertools; use std::path::PathBuf; #[test] fn join() { let a1 = vec!["a", "b", "c"]; assert_eq!(a1.join(""), "abc"); assert_eq!(a1.join("_"), "a_b_c"); let a2 = Vec::<String>::new(); assert_eq!(a2.join(""), ""); assert_eq!...
assert_eq!(s1.to_snake_case(), "first_second_last"); let s2 = "FirstSecondLast".to_string(); assert_eq!(s2.to_class_case(), "FirstSecondLast"); assert_eq!(s2.to_snake_case(), "first_second_last"); let s3 = "First_Second_last".to_string(); assert_eq!(s3.to_class_case(), "FirstSecondLast"); ...
#[test] fn case_operations() { let s1 = "first_second_last".to_string(); assert_eq!(s1.to_class_case(), "FirstSecondLast");
random_line_split
waker_ref.rs
use super::arc_wake::{ArcWake}; use super::waker::waker_vtable; use alloc::sync::Arc; use core::mem::ManuallyDrop; use core::marker::PhantomData; use core::ops::Deref; use core::task::{Waker, RawWaker}; /// A [`Waker`] that is only valid for a given lifetime. /// /// Note: this type implements [`Deref<Target = Waker>`...
(&self) -> &Waker { &self.waker } } /// Creates a reference to a [`Waker`] from a reference to `Arc<impl ArcWake>`. /// /// The resulting [`Waker`] will call /// [`ArcWake.wake()`](ArcWake::wake) if awoken. #[inline] pub fn waker_ref<W>(wake: &Arc<W>) -> WakerRef<'_> where W: ArcWake { // simply co...
deref
identifier_name
waker_ref.rs
use super::arc_wake::{ArcWake}; use super::waker::waker_vtable; use alloc::sync::Arc; use core::mem::ManuallyDrop; use core::marker::PhantomData; use core::ops::Deref; use core::task::{Waker, RawWaker}; /// A [`Waker`] that is only valid for a given lifetime. /// /// Note: this type implements [`Deref<Target = Waker>`...
WakerRef::new_unowned(waker) }
random_line_split
waker_ref.rs
use super::arc_wake::{ArcWake}; use super::waker::waker_vtable; use alloc::sync::Arc; use core::mem::ManuallyDrop; use core::marker::PhantomData; use core::ops::Deref; use core::task::{Waker, RawWaker}; /// A [`Waker`] that is only valid for a given lifetime. /// /// Note: this type implements [`Deref<Target = Waker>`...
} /// Creates a reference to a [`Waker`] from a reference to `Arc<impl ArcWake>`. /// /// The resulting [`Waker`] will call /// [`ArcWake.wake()`](ArcWake::wake) if awoken. #[inline] pub fn waker_ref<W>(wake: &Arc<W>) -> WakerRef<'_> where W: ArcWake { // simply copy the pointer instead of using Arc::into_raw...
{ &self.waker }
identifier_body
test.rs
#[macro_use] extern crate smelter; #[derive(PartialEq, Debug, Builder, Default)] struct Point { x: u32, #[smelter(field_name="y_axis")] y: u32, } #[derive(PartialEq, Debug, Builder, Default)] struct Container<T> where T: PartialEq + Default { item: T, } #[test] fn can_generate_builder_methods()...
<T> where T: PartialEq + Default { item: T, #[smelter(field_name = "id")] item_id: u64, } #[test] fn can_generate_container_with_prefix() { let container: ContainerWith<u32> = ContainerWith::default() .with_item(1u32) ...
ContainerWith
identifier_name
test.rs
#[macro_use] extern crate smelter; #[derive(PartialEq, Debug, Builder, Default)] struct Point { x: u32, #[smelter(field_name="y_axis")] y: u32, } #[derive(PartialEq, Debug, Builder, Default)] struct Container<T> where T: PartialEq + Default { item: T, } #[test] fn can_generate_builder_methods()...
} #[derive(PartialEq, Builder, Default, Debug, Clone)] #[smelter(prefix="with_")] pub struct User { pub uid: u64, pub email: String, pub alias: String, pub friends: Vec<User>, } #[test] fn can_derive_collection() { let mut u1 = User::default(); let u2 = User::default() .with_ema...
assert_eq!(with_lifetime, expected);
random_line_split
rhel_release.rs
use regex::Regex; use std::fs::File; use std::io::Error; use std::io::prelude::*; use utils; pub struct RHELRelease { pub distro: Option<String>, pub version: Option<String> } fn read_file(filename: &str) -> Result<String, Error> { let mut file = File::open(filename)?; let mut contents = String::new()...
, None => None }; RHELRelease { distro: distro, version: version } }
{ match m.get(1) { Some(version) => { Some(version.as_str().to_owned()) }, None => None } }
conditional_block
rhel_release.rs
use regex::Regex; use std::fs::File; use std::io::Error; use std::io::prelude::*; use utils; pub struct RHELRelease { pub distro: Option<String>, pub version: Option<String> } fn read_file(filename: &str) -> Result<String, Error> { let mut file = File::open(filename)?; let mut contents = String::new()...
} } } pub fn parse(file: String) -> RHELRelease { let distrib_regex = Regex::new(r"(\w+) Linux release").unwrap(); let version_regex = Regex::new(r"release\s([\w\.]+)").unwrap(); let distro = match distrib_regex.captures_iter(&file).next() { Some(m) => { match m.get(1) { ...
None
random_line_split
rhel_release.rs
use regex::Regex; use std::fs::File; use std::io::Error; use std::io::prelude::*; use utils; pub struct RHELRelease { pub distro: Option<String>, pub version: Option<String> } fn read_file(filename: &str) -> Result<String, Error> { let mut file = File::open(filename)?; let mut contents = String::new()...
pub fn parse(file: String) -> RHELRelease { let distrib_regex = Regex::new(r"(\w+) Linux release").unwrap(); let version_regex = Regex::new(r"release\s([\w\.]+)").unwrap(); let distro = match distrib_regex.captures_iter(&file).next() { Some(m) => { match m.get(1) { Som...
{ if utils::file_exists("/etc/redhat-release") { if let Ok(release) = read_file("/etc/redhat-release") { Some(parse(release)) } else { None } } else { if let Ok(release) = read_file("/etc/centos-release") { Some(parse(release)) } else {...
identifier_body
rhel_release.rs
use regex::Regex; use std::fs::File; use std::io::Error; use std::io::prelude::*; use utils; pub struct RHELRelease { pub distro: Option<String>, pub version: Option<String> } fn read_file(filename: &str) -> Result<String, Error> { let mut file = File::open(filename)?; let mut contents = String::new()...
() -> Option<RHELRelease> { if utils::file_exists("/etc/redhat-release") { if let Ok(release) = read_file("/etc/redhat-release") { Some(parse(release)) } else { None } } else { if let Ok(release) = read_file("/etc/centos-release") { Some(parse(...
retrieve
identifier_name
constant-in-match-pattern.rs
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { match 1 { CONSTANT => {} _ => {} }; // if let 3 = CONSTANT {} match (Struct { a: 2, b: 2 }) { STRUCT => {} _ => {} }; // if let STRUCT = STRUCT {} match TupleStruct(3) { TUPLE_STRUCT => {} _ => {} }; // if let TupleStruct(4) ...
main
identifier_name
constant-in-match-pattern.rs
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
struct Struct { a: isize, b: usize, } const STRUCT: Struct = Struct { a: 1, b: 2 }; struct TupleStruct(u32); const TUPLE_STRUCT: TupleStruct = TupleStruct(4); enum Enum { Variant1(char), Variant2 { a: u8 }, Variant3 } const VARIANT1: Enum = Enum::Variant1('v'); const VARIANT2: Enum = Enum::Varian...
// debug locations to 'constant' patterns in match expressions. const CONSTANT: u64 = 3;
random_line_split
bounds.rs
use core::{usize, u8, u16, u32, u64}; use core::{isize, i8, i16, i32, i64}; use core::{f32, f64}; use core::num::Wrapping; /// Numbers which have upper and lower bounds pub trait Bounded { // FIXME (#5527): These should be associated constants /// returns the smallest finite number this type can represent ...
() { macro_rules! test_wrapping_bounded { ($($t:ty)+) => { $( assert_eq!(Wrapping::<$t>::min_value().0, <$t>::min_value()); assert_eq!(Wrapping::<$t>::max_value().0, <$t>::max_value()); )+ }; } test_wrapping_bounded!(usize u8 u16 u32 u...
wrapping_bounded
identifier_name
bounds.rs
use core::{usize, u8, u16, u32, u64}; use core::{isize, i8, i16, i32, i64}; use core::{f32, f64}; use core::num::Wrapping; /// Numbers which have upper and lower bounds pub trait Bounded { // FIXME (#5527): These should be associated constants /// returns the smallest finite number this type can represent ...
bounded_impl!(u32, u32::MIN, u32::MAX); bounded_impl!(u64, u64::MIN, u64::MAX); bounded_impl!(isize, isize::MIN, isize::MAX); bounded_impl!(i8, i8::MIN, i8::MAX); bounded_impl!(i16, i16::MIN, i16::MAX); bounded_impl!(i32, i32::MIN, i32::MAX); bounded_impl!(i64, i64::MIN, i64::MAX); impl<T: B...
random_line_split
bounds.rs
use core::{usize, u8, u16, u32, u64}; use core::{isize, i8, i16, i32, i64}; use core::{f32, f64}; use core::num::Wrapping; /// Numbers which have upper and lower bounds pub trait Bounded { // FIXME (#5527): These should be associated constants /// returns the smallest finite number this type can represent ...
fn max_value() -> Self { Wrapping(T::max_value()) } } bounded_impl!(f32, f32::MIN, f32::MAX); macro_rules! for_each_tuple_ { ( $m:ident!! ) => ( $m! { } ); ( $m:ident!! $h:ident, $($t:ident,)* ) => ( $m! { $h $($t)* } for_each_tuple_! { $m!! $($t,)* } ); } macro_rules! for...
{ Wrapping(T::min_value()) }
identifier_body
panic.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // macro_rules! panic { // () => ( // panic!("explicit panic") // ); // ($msg:expr) => ({ // static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!()); // ::core::pani...
#[test] #[should_panic] fn panic_test2() { panic!("Hello, World!"); // panicked at 'Hello, World!' } #[test] #[should_panic] fn panic_test3() { panic!("{}, {}!", "Hello", "World"); // panicked at 'Hello, World!' } #[test] #[should_panic] fn panic_test4() { let arg1: &'...
{ panic!(); // panicked at 'explicit panic' }
identifier_body
panic.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // macro_rules! panic { // () => ( // panic!("explicit panic") // ); // ($msg:expr) => ({ // static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!()); // ::core::pani...
() { let arg1: &'static str = "Hello"; let arg2: &'static str = "World"; panic!("{}, {}!", arg1, arg2); // panicked at 'Hello, World!' } #[test] #[should_panic] fn panic_test5() { let arg1: usize = 68; let arg2: usize = 500; panic!("arg1 = [{}], arg2 = [{}]", arg1, arg2); // panicked at 'arg1 =...
panic_test4
identifier_name
panic.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // macro_rules! panic { // () => ( // panic!("explicit panic") // ); // ($msg:expr) => ({ // static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!()); // ::core::pani...
// } #[test] #[should_panic] fn panic_test1() { panic!(); // panicked at 'explicit panic' } #[test] #[should_panic] fn panic_test2() { panic!("Hello, World!"); // panicked at 'Hello, World!' } #[test] #[should_panic] fn panic_test3() { panic!("{}, {}!", "Hello", "Wo...
random_line_split
worker.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{Arc, Mutex}; use futures_channel::oneshot::Sender; use futures_util::{FutureExt as _, SinkExt as _, TryFutureExt as _, TryStreamExt as _}; use grpc_proto::testing::control::{ ClientArgs, ClientStatus, CoreRequest, CoreResponse, Ser...
resp.set_cores(cpu_count as i32); ctx.spawn( sink.success(resp) .map_err(|e| error!("failed to report cpu count: {:?}", e)) .map(|_| ()), ) } fn quit_worker(&mut self, ctx: RpcContext, _: Void, sink: crate::grpc::UnarySink<Void>) { let n...
fn core_count(&mut self, ctx: RpcContext, _: CoreRequest, sink: UnarySink<CoreResponse>) { let cpu_count = util::cpu_num_cores(); let mut resp = CoreResponse::default();
random_line_split
worker.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{Arc, Mutex}; use futures_channel::oneshot::Sender; use futures_util::{FutureExt as _, SinkExt as _, TryFutureExt as _, TryStreamExt as _}; use grpc_proto::testing::control::{ ClientArgs, ClientStatus, CoreRequest, CoreResponse, Ser...
{ shutdown_notifier: Arc<Mutex<Option<Sender<()>>>>, } impl Worker { pub fn new(sender: Sender<()>) -> Worker { Worker { shutdown_notifier: Arc::new(Mutex::new(Some(sender))), } } } impl WorkerService for Worker { fn run_server( &mut self, ctx: RpcContext, ...
Worker
identifier_name
worker.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{Arc, Mutex}; use futures_channel::oneshot::Sender; use futures_util::{FutureExt as _, SinkExt as _, TryFutureExt as _, TryStreamExt as _}; use grpc_proto::testing::control::{ ClientArgs, ClientStatus, CoreRequest, CoreResponse, Ser...
fn quit_worker(&mut self, ctx: RpcContext, _: Void, sink: crate::grpc::UnarySink<Void>) { let notifier = self.shutdown_notifier.lock().unwrap().take(); if let Some(notifier) = notifier { let _ = notifier.send(()); } ctx.spawn( sink.success(Void::default()) ...
{ let cpu_count = util::cpu_num_cores(); let mut resp = CoreResponse::default(); resp.set_cores(cpu_count as i32); ctx.spawn( sink.success(resp) .map_err(|e| error!("failed to report cpu count: {:?}", e)) .map(|_| ()), ) }
identifier_body
worker.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{Arc, Mutex}; use futures_channel::oneshot::Sender; use futures_util::{FutureExt as _, SinkExt as _, TryFutureExt as _, TryStreamExt as _}; use grpc_proto::testing::control::{ ClientArgs, ClientStatus, CoreRequest, CoreResponse, Ser...
ctx.spawn( sink.success(Void::default()) .map_err(|e| error!("failed to report quick worker: {:?}", e)) .map(|_| ()), ); } }
{ let _ = notifier.send(()); }
conditional_block
main.rs
extern crate serial; use std::env; use std::io; use std::time::Duration; use std::process::exit; use std::thread::sleep; use std::io::prelude::*; use serial::prelude::*; fn
() { let args: Vec<String> = env::args().skip(1).collect(); if args.len()!= 1 { writeln!(io::stderr(), "Program takes exactly one argument. (The serial port)").unwrap(); exit(1); } let level = read_level(&mut io::stdin()); let mut port = serial::open(&args[0]).unwrap(); let mut...
main
identifier_name
main.rs
extern crate serial; use std::env; use std::io; use std::time::Duration; use std::process::exit; use std::thread::sleep; use std::io::prelude::*; use serial::prelude::*; fn main() { let args: Vec<String> = env::args().skip(1).collect(); if args.len()!= 1 { writeln!(io::stderr(), "Program takes exact...
else { println!("Failed."); } for b in port.bytes() { print!("{}", std::char::from_u32(b.unwrap() as u32).unwrap()); } } // Reads level and prepares it to be sent fn read_level(input: &mut Read) -> String { let mut buf = String::new(); input.read_to_string(&mut buf).unwrap(); ...
{ println!("Finished."); }
conditional_block
main.rs
extern crate serial; use std::env; use std::io; use std::time::Duration; use std::process::exit; use std::thread::sleep; use std::io::prelude::*; use serial::prelude::*; fn main()
} port.set_timeout(Duration::from_millis(10000)).unwrap(); println!("Level: {} {} {}", level.as_bytes()[0], level.as_bytes()[1], level.split_at(2).1); println!("Uploading..."); if send_level(&mut port, &level) { println!("Finished."); } else { println!("Failed."); } fo...
{ let args: Vec<String> = env::args().skip(1).collect(); if args.len() != 1 { writeln!(io::stderr(), "Program takes exactly one argument. (The serial port)").unwrap(); exit(1); } let level = read_level(&mut io::stdin()); let mut port = serial::open(&args[0]).unwrap(); let mut s...
identifier_body
main.rs
extern crate serial; use std::env; use std::io; use std::time::Duration; use std::process::exit;
use std::io::prelude::*; use serial::prelude::*; fn main() { let args: Vec<String> = env::args().skip(1).collect(); if args.len()!= 1 { writeln!(io::stderr(), "Program takes exactly one argument. (The serial port)").unwrap(); exit(1); } let level = read_level(&mut io::stdin()); l...
use std::thread::sleep;
random_line_split
ttf.rs
//! Module for creating text textures. use common::color::Color4; use gl; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use std::ffi::CString; use std::path::Path; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_came...
<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> { self.render(gl, txt, Color4::of_rgba(0xFF, 0x00, 0x00, 0xFF)) } /// dark black #333 #[allow(dead_code)] pub fn dark<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> { self.render(gl, txt, Color4::of_rgba(0x33, 0x33, 0x33, 0xFF)) } ...
red
identifier_name
ttf.rs
//! Module for creating text textures. use common::color::Color4; use gl; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use std::ffi::CString; use std::path::Path; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_came...
impl Font { #[allow(missing_docs)] pub fn new(font: &Path, point_size: u32) -> Font { ensure_init(); let c_path = CString::new(font.to_str().unwrap().as_bytes()).unwrap(); let ptr = c_path.as_ptr() as *const i8; let p = unsafe { ffi::TTF_OpenFont(ptr, point_size as ffi::c_int) }; assert!(!p....
{ unsafe { if ffi::TTF_WasInit() == 0 { assert_eq!(ffi::TTF_Init(), 0); } } }
identifier_body