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
trait-default-method-xc.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn eq<T: TestEquality>(lhs: &T, rhs: &T) -> bool { lhs.test_eq(rhs) } fn neq<T: TestEquality>(lhs: &T, rhs: &T) -> bool { lhs.test_neq(rhs) } impl TestEquality for stuff::thing { fn test_eq(&self, rhs: &stuff::thing) -> bool { //self.x.test_eq(&rhs.x) eq(&self.x, &rhs.x) } } pub fn m...
fn g<T, U, V: B<T>>(i: V, j: T, k: U) -> (T, U) { i.thing(j, k) }
random_line_split
trait-default-method-xc.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ pub x: int } } impl A for stuff::thing { fn f(&self) -> int { 10 } } fn g<T, U, V: B<T>>(i: V, j: T, k: U) -> (T, U) { i.thing(j, k) } fn eq<T: TestEquality>(lhs: &T, rhs: &T) -> bool { lhs.test_eq(rhs) } fn neq<T: TestEquality>(lhs: &T, rhs: &T) -> bool { lhs.test_neq(rhs) } impl TestEquality f...
thing
identifier_name
copy.rs
extern crate rimd; use rimd::{SMF,SMFError,SMFWriter}; use std::env::{args,Args}; use std::path::Path; fn
() { let mut args: Args = args(); args.next(); let pathstr = match args.next() { Some(s) => s, None => { panic!("Need a source path"); } }; let deststr = match args.next() { Some(s) => s, None => { panic!("Need a destination path") }, }; match SMF::from_file(&...
main
identifier_name
copy.rs
extern crate rimd; use rimd::{SMF,SMFError,SMFWriter}; use std::env::{args,Args}; use std::path::Path; fn main()
SMFError::MidiError(_) => {println!("Midi Error");} SMFError::MetaError(_) => {println!("Meta Error");} } } } }
{ let mut args: Args = args(); args.next(); let pathstr = match args.next() { Some(s) => s, None => { panic!("Need a source path"); } }; let deststr = match args.next() { Some(s) => s, None => { panic!("Need a destination path") }, }; match SMF::from_file(&Pat...
identifier_body
copy.rs
extern crate rimd; use rimd::{SMF,SMFError,SMFWriter}; use std::env::{args,Args}; use std::path::Path; fn main() { let mut args: Args = args(); args.next(); let pathstr = match args.next() { Some(s) => s, None => { panic!("Need a source path"); } }; let deststr = match args.next() ...
SMFError::Error(e) => {println!("io: {}",e);} SMFError::MidiError(_) => {println!("Midi Error");} SMFError::MetaError(_) => {println!("Meta Error");} } } } }
{println!("{}",s);}
conditional_block
copy.rs
use std::path::Path; fn main() { let mut args: Args = args(); args.next(); let pathstr = match args.next() { Some(s) => s, None => { panic!("Need a source path"); } }; let deststr = match args.next() { Some(s) => s, None => { panic!("Need a destination path") }, ...
extern crate rimd; use rimd::{SMF,SMFError,SMFWriter}; use std::env::{args,Args};
random_line_split
storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::Storag...
fn get_storage_task(&self) -> StorageTask { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.as_window().storage_task() } } impl<'a> StorageMethods for JSRef<'a, Storage> { fn Length(self) -> u32 { let (sender, receiver) = channel(); ...
{ let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.get_url() }
identifier_body
storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::Storag...
} fn NamedSetter(self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedCreator(self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn RemoveItem(self, name: DOMString) { let (sender, receiver) = channel(); self.ge...
{ self.broadcast_change_notification(Some(name), old_value, Some(value)); }
conditional_block
storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::Storag...
(self, index: u32) -> Option<DOMString> { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), self.storage_type, index)).unwrap(); receiver.recv().unwrap() } fn GetItem(self, name: DOMString) -> Option<DOMString> { let (s...
Key
identifier_name
storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::Storag...
impl StorageEventRunnable { fn new(storage: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>) -> StorageEventRunnable { StorageEventRunnable { element: storage, key: key, old_value: old_value, new_value: new_value } } } impl MainThreadRunna...
random_line_split
lib.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/. */ #![feature(box_syntax)] #![feature(fnbox)] #![feature(mpsc_select)] #![feature(plugin)] #![feature(plugin)] #![plu...
extern crate time; extern crate url; extern crate util; extern crate uuid; extern crate websocket; pub mod about_loader; pub mod cookie; pub mod cookie_storage; pub mod data_loader; pub mod file_loader; pub mod hsts; pub mod http_loader; pub mod image_cache_thread; pub mod mime_classifier; pub mod pub_domains; pub mod...
extern crate msg; extern crate net_traits; extern crate openssl; extern crate rustc_serialize;
random_line_split
eq-multidispatch.rs
// run-pass #[derive(PartialEq, Debug)] struct Bar; #[derive(Debug)] struct Baz; #[derive(Debug)] struct Foo; #[derive(Debug)] struct Fu; impl PartialEq for Baz { fn eq(&self, _: &Baz) -> bool { true } } impl PartialEq<Fu> for Foo { fn
(&self, _: &Fu) -> bool { true } } impl PartialEq<Foo> for Fu { fn eq(&self, _: &Foo) -> bool { true } } impl PartialEq<Bar> for Foo { fn eq(&self, _: &Bar) -> bool { false } } impl PartialEq<Foo> for Bar { fn eq(&self, _: &Foo) -> bool { false } } fn main() { assert!(Bar!= Foo); assert!(Foo!= Bar); asse...
eq
identifier_name
eq-multidispatch.rs
// run-pass #[derive(PartialEq, Debug)] struct Bar; #[derive(Debug)] struct Baz; #[derive(Debug)] struct Foo; #[derive(Debug)] struct Fu; impl PartialEq for Baz { fn eq(&self, _: &Baz) -> bool { true } } impl PartialEq<Fu> for Foo { fn eq(&self, _: &Fu) -> bool { true } } impl PartialEq<Foo> for Fu { fn eq(&self, _...
}
assert_eq!(Fu, Foo);
random_line_split
eq-multidispatch.rs
// run-pass #[derive(PartialEq, Debug)] struct Bar; #[derive(Debug)] struct Baz; #[derive(Debug)] struct Foo; #[derive(Debug)] struct Fu; impl PartialEq for Baz { fn eq(&self, _: &Baz) -> bool { true } } impl PartialEq<Fu> for Foo { fn eq(&self, _: &Fu) -> bool { true } } impl PartialEq<Foo> for Fu { fn eq(&self, _...
} impl PartialEq<Bar> for Foo { fn eq(&self, _: &Bar) -> bool { false } } impl PartialEq<Foo> for Bar { fn eq(&self, _: &Foo) -> bool { false } } fn main() { assert!(Bar!= Foo); assert!(Foo!= Bar); assert_eq!(Bar, Bar); assert_eq!(Baz, Baz); assert_eq!(Foo, Fu); assert_eq!(Fu, Foo); }
{ true }
identifier_body
main.rs
use std::fs::File; use std::io::Read; use std::env; /** * mindblow: A brainfuck interpreter written in Rust. * @author: Daniel Shaw (https://github.com/comp92) * * Desc: * My first project using the Rust language. * Brainfuck is a simple enough interpreted * langugae, so why not start learning Rus...
, ',' => { //http://stackoverflow.com/a/30679861 I am a noob mem[pointer] = std::io::stdin() .bytes().next().and_then(|result| result.ok()).map(|byte| byte as u8).unwrap(); }, _ => (), } } }
{ print!("{}",&(mem[pointer] as char)); }
conditional_block
main.rs
use std::fs::File; use std::io::Read; use std::env; /** * mindblow: A brainfuck interpreter written in Rust. * @author: Daniel Shaw (https://github.com/comp92) * * Desc: * My first project using the Rust language. * Brainfuck is a simple enough interpreted * langugae, so why not start learning Rus...
() { const MAX_SIZE:usize = 30000; let mut mem: [u8; MAX_SIZE] = [0; MAX_SIZE]; let mut pointer: usize = 0; let mut buffer = String::new(); //TODO: Handle no args given let mut script = File::open(env::args().nth(1).unwrap()).unwrap(); script.read_to_string(&mut buffer).unwrap(); ...
main
identifier_name
main.rs
use std::fs::File; use std::io::Read; use std::env; /** * mindblow: A brainfuck interpreter written in Rust. * @author: Daniel Shaw (https://github.com/comp92) * * Desc: * My first project using the Rust language. * Brainfuck is a simple enough interpreted * langugae, so why not start learning Rus...
}, '-' => { mem[pointer]-=1; }, '>' => { if pointer < MAX_SIZE { pointer+=1; } else { pointer=0; } }, '<' => { if po...
'+' => { mem[pointer]+=1;
random_line_split
main.rs
use std::fs::File; use std::io::Read; use std::env; /** * mindblow: A brainfuck interpreter written in Rust. * @author: Daniel Shaw (https://github.com/comp92) * * Desc: * My first project using the Rust language. * Brainfuck is a simple enough interpreted * langugae, so why not start learning Rus...
pointer=0; } }, '<' => { if pointer > 0 { pointer-=1; } else { pointer=MAX_SIZE; } }, '[' => { //TODO: Loops ...
{ const MAX_SIZE:usize = 30000; let mut mem: [u8; MAX_SIZE] = [0; MAX_SIZE]; let mut pointer: usize = 0; let mut buffer = String::new(); //TODO: Handle no args given let mut script = File::open(env::args().nth(1).unwrap()).unwrap(); script.read_to_string(&mut buffer).unwrap(); fo...
identifier_body
sqlite.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 anyhow::Result; use sql::rusqlite::{Connection as SqliteConnection, OpenFlags as SqliteOpenFlags}; use std::{fs::create_dir_all, path::...
<P: AsRef<Path>>(path: P, readonly: bool) -> Result<SqliteConnection> { let path = path.as_ref(); let con = { // Open a RW connection with create-on-open enabled, so that the Sqlite DB is initialized // even if we then re-open it with RO access. (You cannot open RO with create-on-open) /...
open_sqlite_path
identifier_name
sqlite.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 anyhow::Result; use sql::rusqlite::{Connection as SqliteConnection, OpenFlags as SqliteOpenFlags}; use std::{fs::create_dir_all, path::...
else { // NB no creation flag, as db should already exist at this point SqliteOpenFlags::SQLITE_OPEN_READ_WRITE }; let con = SqliteConnection::open_with_flags(path, flags)?; sqlite_setup_connection(&con); Ok(con) }
{ SqliteOpenFlags::SQLITE_OPEN_READ_ONLY }
conditional_block
sqlite.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 anyhow::Result; use sql::rusqlite::{Connection as SqliteConnection, OpenFlags as SqliteOpenFlags}; use std::{fs::create_dir_all, path::...
}; sqlite_setup_connection(&con); Ok(con) } /// Open a single sqlite connection. The Sqlite DB must already exist at path. pub fn open_existing_sqlite_path<P: AsRef<Path>>( path: P, readonly: bool, ) -> Result<SqliteConnection> { let path = path.as_ref(); let flags = if readonly { ...
{ let path = path.as_ref(); let con = { // Open a RW connection with create-on-open enabled, so that the Sqlite DB is initialized // even if we then re-open it with RO access. (You cannot open RO with create-on-open) // This is useful for tests that want to verify that nothing is written...
identifier_body
sqlite.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 anyhow::Result; use sql::rusqlite::{Connection as SqliteConnection, OpenFlags as SqliteOpenFlags}; use std::{fs::create_dir_all, path::...
let con = SqliteConnection::open_in_memory()?; sqlite_setup_connection(&con); Ok(con) } /// Open a single sqlite connection. The Sqlite DB will be created at path if necessary. pub fn open_sqlite_path<P: AsRef<Path>>(path: P, readonly: bool) -> Result<SqliteConnection> { let path = path.as_ref(); l...
random_line_split
video.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. #![cfg_attr(feature = "cargo-clippy", allow(clippy::transmute_ptr_to_ptr))] use std::rc::Rc; use std::result::Result; use cgm...
(width: u32, height: u32, palette: [u32; 16]) -> VideoBuffer { VideoBuffer { dim: (width as usize, height as usize), palette, pixels: vec![0; (width * height) as usize], } } pub fn get_pixel_data(&self) -> &[u8] { unsafe { let len = self.p...
new
identifier_name
video.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. #![cfg_attr(feature = "cargo-clippy", allow(clippy::transmute_ptr_to_ptr))] use std::rc::Rc; use std::result::Result; use cgm...
} } fn write(&mut self, index: usize, color: u8) { self.pixels[index] = self.palette[color as usize]; } } pub struct VideoRenderer { // Dependencies video_buffer: Shared<VideoBuffer>, // Resources batch: sprite::Batch, texture: Rc<gl::Texture>, } impl VideoRenderer { ...
fn reset(&mut self) { for pixel in self.pixels.iter_mut() { *pixel = 0x00;
random_line_split
video.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. #![cfg_attr(feature = "cargo-clippy", allow(clippy::transmute_ptr_to_ptr))] use std::rc::Rc; use std::result::Result; use cgm...
pub fn get_pixel_data(&self) -> &[u8] { unsafe { let len = self.pixels.len() * core::mem::size_of::<u32>(); core::slice::from_raw_parts(self.pixels.as_ptr() as *const u8, len) } } } impl VideoOutput for VideoBuffer { fn get_dimension(&self) -> (usize, usize) { ...
{ VideoBuffer { dim: (width as usize, height as usize), palette, pixels: vec![0; (width * height) as usize], } }
identifier_body
tests.rs
use std::fs; use std::path; use littletest; use adapter::{Adapter}; pub struct RunOptions<'o> { pub ignore_todo: bool, pub engine: Box<Adapter + 'o> } pub struct TestCase<'o> { pub input_path: path::PathBuf, pub expected_path: path::PathBuf, pub opts: &'o RunOptions<'o> } impl<'o> TestCase<'o> {...
} } pub fn load<'o>(spec_path: &path::Path, opts: &'o RunOptions) -> Vec<Box<littletest::Runnable + Sync + 'o>> { use glob::glob; let input_file = "input.scss"; let expected_file = "expected_output.css"; let mut pattern = spec_path.to_path_buf(); pattern.push("**"); pattern.push(input_fi...
if output != expected { return TestResult::Fail } TestResult::Pass
random_line_split
tests.rs
use std::fs; use std::path; use littletest; use adapter::{Adapter}; pub struct RunOptions<'o> { pub ignore_todo: bool, pub engine: Box<Adapter + 'o> } pub struct TestCase<'o> { pub input_path: path::PathBuf, pub expected_path: path::PathBuf, pub opts: &'o RunOptions<'o> } impl<'o> TestCase<'o> {...
<'o>(spec_path: &path::Path, opts: &'o RunOptions) -> Vec<Box<littletest::Runnable + Sync + 'o>> { use glob::glob; let input_file = "input.scss"; let expected_file = "expected_output.css"; let mut pattern = spec_path.to_path_buf(); pattern.push("**"); pattern.push(input_file); glob(patter...
load
identifier_name
tests.rs
use std::fs; use std::path; use littletest; use adapter::{Adapter}; pub struct RunOptions<'o> { pub ignore_todo: bool, pub engine: Box<Adapter + 'o> } pub struct TestCase<'o> { pub input_path: path::PathBuf, pub expected_path: path::PathBuf, pub opts: &'o RunOptions<'o> } impl<'o> TestCase<'o> {...
Err(why) => panic!("couldn't read {}: {}", expected_display, why), Ok(_) => clean_output(expected_buffer.as_ref()) } }; if output!= expected { return TestResult::Fail } TestResult::Pass } } pub fn load<'o>(spec_path: &path::...
{ use littletest::{TestResult}; use std::io::Read; if self.opts.ignore_todo && self.is_todo() { return TestResult::Skipped } let result = self.opts.engine.compile(&self.input_path); if result.is_err() { return TestResult::Fail } ...
identifier_body
chains.rs
// rustfmt-use_small_heuristics: Off // Test chain formatting. fn main() { let a = b.c.d.1.foo(|x| x + 1); bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc.ddddddddddddddddddddddddddd(); bbbbbbbbbbbbbbbbbbb .ccccccccccccccccccccccccccccccccccccc .ddddddddddddddddddddddddddd ...
} fn issue_2773() { let bar = Some(0); bar.or_else(|| { // do stuff None }) .or_else(|| { // do other stuff None }) .and_then(|val| { // do this stuff None }); } fn issue_3034() { disallowed_headers.iter().any(|header| *header == name) ...
{ foo(|a| { println!("a"); println!("b"); }) .bar(|c| { println!("a"); println!("b"); }) .baz(|c| { println!("a"); println!("b"); }) }
identifier_body
chains.rs
// rustfmt-use_small_heuristics: Off // Test chain formatting. fn main() { let a = b.c.d.1.foo(|x| x + 1); bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc.ddddddddddddddddddddddddddd(); bbbbbbbbbbbbbbbbbbb .ccccccccccccccccccccccccccccccccccccc .ddddddddddddddddddddddddddd ...
else { none(); } .bar() .baz(); Foo { x: val, } .baz(|| { force(); multiline(); }) .quux(); Foo { y: i_am_multi_line, z: ok, } .baz(|| { force(); multiline(); }) .quux(); a + match x { true => "...
{ some(); }
conditional_block
chains.rs
// rustfmt-use_small_heuristics: Off // Test chain formatting. fn main() { let a = b.c.d.1.foo(|x| x + 1); bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc.ddddddddddddddddddddddddddd(); bbbbbbbbbbbbbbbbbbb .ccccccccccccccccccccccccccccccccccccc .ddddddddddddddddddddddddddd ...
() { let z = Foo { field1: val1, field2: val2, }; let x = Foo { field1: val1, field2: val2, } .method_call() .method_call(); let y = if cond { val1 } else { val2 } .method_call(); { match x { PushParam => { ...
floaters
identifier_name
chains.rs
// rustfmt-use_small_heuristics: Off // Test chain formatting. fn main() { let a = b.c.d.1.foo(|x| x + 1); bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc.ddddddddddddddddddddddddddd(); bbbbbbbbbbbbbbbbbbb .ccccccccccccccccccccccccccccccccccccc .ddddddddddddddddddddddddddd ...
if let Some(mi) = attr.meta() { if let Some(value) = mi.value_str() { doc_strings.push(DocFragment::Include( line, attr.span, filename, contents, )); ...
.iter() .filter_map(|attr| { attr.with_desugared_doc(|attr| { if attr.check_name("doc") {
random_line_split
call_analytics.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version.
// Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along ...
random_line_split
call_analytics.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
{ /// Make a transaction trace. pub transaction_tracing: bool, /// Make a VM trace. pub vm_tracing: bool, /// Make a diff. pub state_diffing: bool, }
CallAnalytics
identifier_name
sound.rs
use libxm::XMContext; use sdl2; use sdl2::audio::{AudioCallback, AudioDevice, AudioSpecDesired}; use std::fs::File; use std::io::Read; const SAMPLE_RATE: i32 = 48000; struct XmCallback { xm: XMContext, } impl AudioCallback for XmCallback { type Channel = f32; fn callback(&mut self, out: &mut [f32]) { ...
, } SoundPlayer { device: None } } pub fn hit_event(player: &mut SoundPlayer) -> f32 { use std::ops::Deref; let audio_device_lock = player.device.as_mut().unwrap().lock(); let xm_callback = audio_device_lock.deref(); let xm = &xm_callback.xm; let n_samples = xm.latest_trigger_of_instrument(...
{ println!("Couldn't open module {}: {:?}", filename, err); }
conditional_block
sound.rs
use libxm::XMContext; use sdl2; use sdl2::audio::{AudioCallback, AudioDevice, AudioSpecDesired}; use std::fs::File; use std::io::Read; const SAMPLE_RATE: i32 = 48000; struct XmCallback { xm: XMContext, } impl AudioCallback for XmCallback { type Channel = f32; fn callback(&mut self, out: &mut [f32]) {
self.xm.generate_samples(out); } } pub struct SoundPlayer { device: Option<AudioDevice<XmCallback>>, } fn play_xm(raw_xm: &[u8]) -> SoundPlayer { let sdl_context = sdl2::init().unwrap(); let sdl_audio = sdl_context.audio().unwrap(); let desired_spec = AudioSpecDesired { freq: Some...
random_line_split
sound.rs
use libxm::XMContext; use sdl2; use sdl2::audio::{AudioCallback, AudioDevice, AudioSpecDesired}; use std::fs::File; use std::io::Read; const SAMPLE_RATE: i32 = 48000; struct XmCallback { xm: XMContext, } impl AudioCallback for XmCallback { type Channel = f32; fn callback(&mut self, out: &mut [f32]) { ...
(player: &mut SoundPlayer) -> f32 { use std::ops::Deref; let audio_device_lock = player.device.as_mut().unwrap().lock(); let xm_callback = audio_device_lock.deref(); let xm = &xm_callback.xm; let n_samples = xm.latest_trigger_of_instrument(0x1D); n_samples as f32 / SAMPLE_RATE as f32 }
hit_event
identifier_name
interpolated-idents.rs
// only-x86_64 #![feature(asm)] macro_rules! m { ($in:ident $out:ident $lateout:ident $inout:ident $inlateout:ident $const:ident $sym:ident $pure:ident $nomem:ident $readonly:ident $preserves_flags:ident $noreturn:ident $nostack:ident $att_syntax:ident $options:ident) => { unsafe { a...
{ m!(in out lateout inout inlateout const sym pure nomem readonly preserves_flags noreturn nostack att_syntax options); }
identifier_body
interpolated-idents.rs
// only-x86_64 #![feature(asm)]
($in:ident $out:ident $lateout:ident $inout:ident $inlateout:ident $const:ident $sym:ident $pure:ident $nomem:ident $readonly:ident $preserves_flags:ident $noreturn:ident $nostack:ident $att_syntax:ident $options:ident) => { unsafe { asm!("", $in(x) x, $out(x) x, $lateout(x) x, $inout(...
macro_rules! m {
random_line_split
interpolated-idents.rs
// only-x86_64 #![feature(asm)] macro_rules! m { ($in:ident $out:ident $lateout:ident $inout:ident $inlateout:ident $const:ident $sym:ident $pure:ident $nomem:ident $readonly:ident $preserves_flags:ident $noreturn:ident $nostack:ident $att_syntax:ident $options:ident) => { unsafe { a...
() { m!(in out lateout inout inlateout const sym pure nomem readonly preserves_flags noreturn nostack att_syntax options); }
main
identifier_name
headerbar.rs
use gtk; use gtk::prelude::*; use views::trending; use NAME; pub fn get_headerbar( stack: &gtk::Stack, revealer: &gtk::Revealer, viewport: &gtk::Viewport, ) -> gtk::HeaderBar { let builder = gtk::Builder::new_from_resource("/com/github/kil0meters/sentinel/gtk/headerbar.ui"); let headerbar: gtk::H...
})); stack_switcher.set_stack(stack); headerbar.set_title(NAME); headerbar }
} })); refresh_button.connect_clicked(clone!(viewport => move |_| { trending::refresh(&viewport);
random_line_split
headerbar.rs
use gtk; use gtk::prelude::*; use views::trending; use NAME; pub fn
( stack: &gtk::Stack, revealer: &gtk::Revealer, viewport: &gtk::Viewport, ) -> gtk::HeaderBar { let builder = gtk::Builder::new_from_resource("/com/github/kil0meters/sentinel/gtk/headerbar.ui"); let headerbar: gtk::HeaderBar = builder.get_object("headerbar").unwrap(); let refresh_button: gtk::B...
get_headerbar
identifier_name
headerbar.rs
use gtk; use gtk::prelude::*; use views::trending; use NAME; pub fn get_headerbar( stack: &gtk::Stack, revealer: &gtk::Revealer, viewport: &gtk::Viewport, ) -> gtk::HeaderBar
})); stack_switcher.set_stack(stack); headerbar.set_title(NAME); headerbar }
{ let builder = gtk::Builder::new_from_resource("/com/github/kil0meters/sentinel/gtk/headerbar.ui"); let headerbar: gtk::HeaderBar = builder.get_object("headerbar").unwrap(); let refresh_button: gtk::Button = builder.get_object("refresh_button").unwrap(); let search_button: gtk::Button = builder.get_ob...
identifier_body
server.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. #[macro_use] extern crate log; #[path = "../log_util.rs"] mod log_util; use std::io::Read; use std::sync::Arc; use std::{io, thread}; use futures_channel::oneshot; use futures_executor::block_on; use futures_util::future::{FutureExt as _, TryFutureE...
{ name: String, } impl Greeter for GreeterService { fn say_hello(&mut self, ctx: RpcContext<'_>, req: HelloRequest, sink: UnarySink<HelloReply>) { let msg = format!("Hello {}, I'm {}", req.get_name(), self.name); let mut resp = HelloReply::default(); resp.set_message(msg); let ...
GreeterService
identifier_name
server.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. #[macro_use] extern crate log; #[path = "../log_util.rs"] mod log_util; use std::io::Read; use std::sync::Arc; use std::{io, thread}; use futures_channel::oneshot; use futures_executor::block_on; use futures_util::future::{FutureExt as _, TryFutureE...
fn main() { let _guard = log_util::init_log(None); let env = Arc::new(Environment::new(1)); let mut server1 = build_server(env.clone(), 50_051); let mut server2 = build_server(env.clone(), 50_052); let (tx, rx) = oneshot::channel(); thread::spawn(move || { info!("Press ENTER to exit......
{ let service = create_greeter(GreeterService { name: format!("{}", port), }); let quota = ResourceQuota::new(Some("HelloServerQuota")).resize_memory(1024 * 1024); let ch_builder = ChannelBuilder::new(env.clone()).set_resource_quota(quota); let mut server = ServerBuilder::new(env) ....
identifier_body
server.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. #[macro_use] extern crate log; #[path = "../log_util.rs"] mod log_util; use std::io::Read; use std::sync::Arc; use std::{io, thread}; use futures_channel::oneshot; use futures_executor::block_on; use futures_util::future::{FutureExt as _, TryFutureE...
let _ = block_on(server2.shutdown()); }
tx.send(()) }); let _ = block_on(rx); let _ = block_on(server1.shutdown());
random_line_split
client.rs
use tokio::net::TcpStream; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use std::net::SocketAddr; const MESSAGES: &[&str] = &["hello", "world", "one two three"]; async fn run_client(addr: SocketAddr) -> std::io::Result<()> { let mut stream = TcpStream::connect(&addr).await?; println!("Connected"); // B...
() -> Result<(), Box<dyn std::error::Error>> { use std::env; let addr = env::args().nth(1).unwrap_or("127.0.0.1:8000".to_string()); let addr = addr.parse::<SocketAddr>()?; // Connect to the echo server match run_client(addr).await { Ok(_) => println!("done."), Err(e) => eprintln!("...
main
identifier_name
client.rs
use tokio::net::TcpStream; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use std::net::SocketAddr; const MESSAGES: &[&str] = &["hello", "world", "one two three"]; async fn run_client(addr: SocketAddr) -> std::io::Result<()> { let mut stream = TcpStream::connect(&addr).await?; println!("Connected"); // B...
stream.write_all(msg.as_bytes()).await?; // Read the message back from the server stream.read(&mut buf).await?; assert_eq!(&buf[..msg.len()], msg.as_bytes()); } Ok(()) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { use std::env; let addr...
random_line_split
client.rs
use tokio::net::TcpStream; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use std::net::SocketAddr; const MESSAGES: &[&str] = &["hello", "world", "one two three"]; async fn run_client(addr: SocketAddr) -> std::io::Result<()>
} #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { use std::env; let addr = env::args().nth(1).unwrap_or("127.0.0.1:8000".to_string()); let addr = addr.parse::<SocketAddr>()?; // Connect to the echo server match run_client(addr).await { Ok(_) => println!("done."...
{ let mut stream = TcpStream::connect(&addr).await?; println!("Connected"); // Buffer to read into let mut buf = [0; 128]; for msg in MESSAGES { println!(" > write = {:?}", msg); // Write the message to the server stream.write_all(msg.as_bytes()).await?; // Read t...
identifier_body
toolshell.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
} }
{ Some(gtk::SizeGroup::wrap_pointer(tmp_pointer)) }
conditional_block
toolshell.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
(&self) -> ReliefStyle { unsafe { ffi::gtk_tool_shell_get_relief_style(GTK_TOOLSHELL(self.get_widget())) } } fn get_style(&self) -> ToolbarStyle { unsafe { ffi::gtk_tool_shell_get_style(GTK_TOOLSHELL(self.get_widget())) } } fn get_text_alignment(...
get_relief_style
identifier_name
toolshell.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
ffi::gtk_tool_shell_get_text_alignment(GTK_TOOLSHELL(self.get_widget())) } } fn get_text_orientation(&self) -> Orientation { unsafe { ffi::gtk_tool_shell_get_text_orientation(GTK_TOOLSHELL(self.get_widget())) } } fn rebuild_menu(&mut self) -> () { ...
random_line_split
toolshell.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
fn get_text_size_group(&self) -> Option<gtk::SizeGroup> { let tmp_pointer = unsafe { ffi::gtk_tool_shell_get_text_size_group(GTK_TOOLSHELL(self.get_widget()) as *const ffi::C_GtkToolShell) }; if tmp_pointer.is_null() { None } else { Some(gtk::SizeGroup::wrap_pointe...
{ unsafe { ffi::gtk_tool_shell_rebuild_menu(GTK_TOOLSHELL(self.get_widget())) } }
identifier_body
pmaxuw.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pmaxuw_1() {
fn pmaxuw_2() { run_test(&Instruction { mnemonic: Mnemonic::PMAXUW, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced(EDI, Eight, 1300239391, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: ...
run_test(&Instruction { mnemonic: Mnemonic::PMAXUW, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM3)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 62, 235], OperandSize::Dword) }
random_line_split
pmaxuw.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pmaxuw_1() { run_test(&Instruction { mnemonic: Mnemonic::PMAXUW, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XM...
() { run_test(&Instruction { mnemonic: Mnemonic::PMAXUW, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced(EDI, Eight, 1300239391, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[1...
pmaxuw_2
identifier_name
pmaxuw.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pmaxuw_1() { run_test(&Instruction { mnemonic: Mnemonic::PMAXUW, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XM...
fn pmaxuw_3() { run_test(&Instruction { mnemonic: Mnemonic::PMAXUW, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 62, 247], OperandSize::Qword) } fn pmaxuw_4...
{ run_test(&Instruction { mnemonic: Mnemonic::PMAXUW, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced(EDI, Eight, 1300239391, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102,...
identifier_body
lib.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/. */ #![feature(box_syntax)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(plugin)] #![feature(sl...
struct PendingLoadGuard { loaded: bool, } impl PendingLoadGuard { fn neuter(&mut self) { self.loaded = true; } } impl Drop for PendingLoadGuard { fn drop(&mut self) { if!thread::panicking() { assert!(self.loaded) } } } impl PendingAsyncLoad { pub fn new(con...
random_line_split
lib.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/. */ #![feature(box_syntax)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(plugin)] #![feature(sl...
} impl PendingAsyncLoad { pub fn new(context: LoadContext, resource_thread: ResourceThread, url: Url, pipeline: Option<PipelineId>) -> PendingAsyncLoad { PendingAsyncLoad { resource_thread: resource_thread, url: url, pipeline: pipeline, guard:...
{ if !thread::panicking() { assert!(self.loaded) } }
identifier_body
lib.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/. */ #![feature(box_syntax)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(plugin)] #![feature(sl...
(context: LoadContext, url: Url, id: Option<PipelineId>) -> LoadData { LoadData { url: url, method: Method::Get, headers: Headers::new(), preserved_headers: Headers::new(), data: None, cors: None, pipeline_id: id, cr...
new
identifier_name
tests.rs
extern crate env_logger; use {ActorSpawner}; use tests::{CountingActor, CountingMessage, ForwardingActor, ForwardMessage}; use js_pool::{WorkPoolSpawner}; use channel::channel_actor_ref; #[test] fn test_counting_actor_with_dedicated_thread() { let counting_actor = CountingActor { count: 0 }; let spawner = WorkPoo...
let forwarding_ref = forwarding_cell.clone(); println!("2"); let count_ref = count_cell.clone(); forwarding_ref .send(ForwardMessage {forward_to: count_ref.clone(), message: CountingMessage::Count }) .ok().expect("send1 failed"); forwarding_ref .send(ForwardMessage {forward_to: count_ref.clone(), message: ...
random_line_split
tests.rs
extern crate env_logger; use {ActorSpawner}; use tests::{CountingActor, CountingMessage, ForwardingActor, ForwardMessage}; use js_pool::{WorkPoolSpawner}; use channel::channel_actor_ref; #[test] fn test_counting_actor_with_dedicated_thread()
#[test] fn test_actor_ref() { let counting_actor = CountingActor { count: 0 }; let spawner = WorkPoolSpawner::new(); let count_cell = spawner.spawn(counting_actor); println!("1"); let forwarding_actor = ForwardingActor; let forwarding_cell = spawner.spawn(forwarding_actor); let forwarding_ref = forwarding_ce...
{ let counting_actor = CountingActor { count: 0 }; let spawner = WorkPoolSpawner::new(); let actor_ref = spawner.spawn(counting_actor); actor_ref.send(CountingMessage::Count).unwrap(); actor_ref.send(CountingMessage::Count).unwrap(); actor_ref.send(CountingMessage::Count).unwrap(); let (channel_ref, receive) =...
identifier_body
tests.rs
extern crate env_logger; use {ActorSpawner}; use tests::{CountingActor, CountingMessage, ForwardingActor, ForwardMessage}; use js_pool::{WorkPoolSpawner}; use channel::channel_actor_ref; #[test] fn
() { let counting_actor = CountingActor { count: 0 }; let spawner = WorkPoolSpawner::new(); let actor_ref = spawner.spawn(counting_actor); actor_ref.send(CountingMessage::Count).unwrap(); actor_ref.send(CountingMessage::Count).unwrap(); actor_ref.send(CountingMessage::Count).unwrap(); let (channel_ref, receive...
test_counting_actor_with_dedicated_thread
identifier_name
errors.rs
use std::fmt; use serde::{de, ser}; use crate::header::header_byte_desc; error_chain! { errors { DeInvalidStartByte(kind: String, byte: u8) { description("while deserializing BSER: invalid start byte") display("while deserializing BSER: invalid start byte for {}: {}", ...
}
{ ErrorKind::SerCustom(format!("{}", msg)).into() }
identifier_body
errors.rs
use std::fmt; use serde::{de, ser}; use crate::header::header_byte_desc; error_chain! { errors { DeInvalidStartByte(kind: String, byte: u8) { description("while deserializing BSER: invalid start byte") display("while deserializing BSER: invalid start byte for {}: {}", ...
} SerCustom(msg: String) { description("error while serializing BSER") display("error while serializing BSER: {}", msg) } SerNeedSize(kind: &'static str) { description("while serializing BSER: need size") display("while serializing BSER: ne...
} DeRecursionLimitExceeded(kind: String) { description("while deserializing BSER: recursion limit exceeded") display("while deserializing BSER: recursion limit exceeded with {}", kind)
random_line_split
errors.rs
use std::fmt; use serde::{de, ser}; use crate::header::header_byte_desc; error_chain! { errors { DeInvalidStartByte(kind: String, byte: u8) { description("while deserializing BSER: invalid start byte") display("while deserializing BSER: invalid start byte for {}: {}", ...
<T: fmt::Display>(msg: T) -> Self { ErrorKind::DeCustom(format!("{}", msg)).into() } } impl ser::Error for Error { fn custom<T: fmt::Display>(msg: T) -> Self { ErrorKind::SerCustom(format!("{}", msg)).into() } }
custom
identifier_name
inotify.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/. pub use lrs_inotify::{Inotify, InodeWatch, InodeData, InodeDataIter}; pub use lrs_inotify::flags::{WatchFlags, Inotif...
pub use lrs_inotify::event::{ INEV_ALL, INEV_CLOSE, INEV_MOVE, INEV_NONE, INEV_ACCESS, INEV_MODIFY, INEV_ATTRIB, INEV_CLOSE_WRITE, INEV_CLOSE_READ, INEV_OPEN, INEV_MOVED_FROM, INEV_MOVED_TO, INEV_CREATE, INEV_DELETE, INEV_DELETE_SELF, INEV_MOVE_SELF, INEV_UNMOUNT, INEV_OVERFLOW, ...
} pub mod events {
random_line_split
cargo_new.rs
use std::os; use std::io::{self, fs, File}; use std::io::fs::PathExtensions; use rustc_serialize::{Decodable, Decoder}; use git2::Config; use util::{GitRepo, HgRepo, CargoResult, human, ChainError, config, internal}; use core::shell::MultiShell; #[derive(Copy, Show, PartialEq)] pub enum VersionControl { Git, Hg, No...
})).0.to_string()) } }; cfg.version_control = match cargo_new.get("vcs") { None => None, Some(vcs) => { let vcs_str = try!(vcs.string().chain_error(|| { internal("invalid configuration for key `cargo-new.vcs`") })).0; let ve...
internal("invalid configuration for key `cargo-new.email`")
random_line_split
cargo_new.rs
use std::os; use std::io::{self, fs, File}; use std::io::fs::PathExtensions; use rustc_serialize::{Decodable, Decoder}; use git2::Config; use util::{GitRepo, HgRepo, CargoResult, human, ChainError, config, internal}; use core::shell::MultiShell; #[derive(Copy, Show, PartialEq)] pub enum VersionControl { Git, Hg, No...
{ name: Option<String>, email: Option<String>, version_control: Option<VersionControl>, } pub fn new(opts: NewOptions, _shell: &mut MultiShell) -> CargoResult<()> { let path = try!(os::getcwd()).join(opts.path); if path.exists() { return Err(human(format!("Destination `{}` already exists",...
CargoNewConfig
identifier_name
cargo_new.rs
use std::os; use std::io::{self, fs, File}; use std::io::fs::PathExtensions; use rustc_serialize::{Decodable, Decoder}; use git2::Config; use util::{GitRepo, HgRepo, CargoResult, human, ChainError, config, internal}; use core::shell::MultiShell; #[derive(Copy, Show, PartialEq)] pub enum VersionControl { Git, Hg, No...
} struct CargoNewConfig { name: Option<String>, email: Option<String>, version_control: Option<VersionControl>, } pub fn new(opts: NewOptions, _shell: &mut MultiShell) -> CargoResult<()> { let path = try!(os::getcwd()).join(opts.path); if path.exists() { return Err(human(format!("Destinat...
{ Ok(match try!(d.read_str()).as_slice() { "git" => VersionControl::Git, "hg" => VersionControl::Hg, "none" => VersionControl::NoVcs, n => { let err = format!("could not decode '{}' as version control", n); return Err(d.error(err.as...
identifier_body
layout.rs
extern crate dataflow_join; use std::io::{BufWriter, Write}; use std::fs::File; use std::slice; use std::mem; use dataflow_join::graph::{GraphTrait, GraphVector, GraphMMap}; fn main() { println!("Usage: layout <source> <target>"); let source = std::env::args().skip(1).next().unwrap(); let target = std::e...
else { 1000000 }; edge_writer.write_all(&slice[..to_write]).unwrap(); println!("wrote some; remaining: {}", slice.len()); slice = &slice[to_write..]; } } unsafe fn _typed_as_byte_slice<T>(slice: &[T]) -> &[u8] { slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * mem::size...
{ slice.len() }
conditional_block
layout.rs
extern crate dataflow_join; use std::io::{BufWriter, Write}; use std::fs::File; use std::slice; use std::mem; use dataflow_join::graph::{GraphTrait, GraphVector, GraphMMap}; fn main() { println!("Usage: layout <source> <target>"); let source = std::env::args().skip(1).next().unwrap(); let target = std::e...
(graph: &Vec<(u32, u32)>, index: u64, parts: u64) -> GraphVector<u32> { let mut nodes = Vec::new(); let mut edges = Vec::new(); for &(src,dst) in graph { if src as u64 % parts == index { while src + 1 >= nodes.len() as u32 { nodes.push(0); } while dst + 1 >= nodes.len() as u...
_extract_fragment
identifier_name
layout.rs
extern crate dataflow_join; use std::io::{BufWriter, Write}; use std::fs::File; use std::slice; use std::mem; use dataflow_join::graph::{GraphTrait, GraphVector, GraphMMap}; fn main() { println!("Usage: layout <source> <target>"); let source = std::env::args().skip(1).next().unwrap(); let target = std::e...
{ slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * mem::size_of::<T>()) }
identifier_body
layout.rs
extern crate dataflow_join; use std::io::{BufWriter, Write}; use std::fs::File; use std::slice; use std::mem; use dataflow_join::graph::{GraphTrait, GraphVector, GraphMMap}; fn main() { println!("Usage: layout <source> <target>"); let source = std::env::args().skip(1).next().unwrap(); let target = std::e...
for index in (1..nodes.len()) { nodes[index] += nodes[index - 1]; } return GraphVector { nodes: nodes, edges: edges }; } fn _digest_graph_vector<E: Ord+Copy>(graph: &GraphVector<E>, output_prefix: &str) { let mut edge_writer = BufWriter::new(File::create(format!("{}.targets", output_prefix))....
edges.push(dst); } }
random_line_split
atomic_ref.rs
/// This is essentially an `AtomicPtr` but is guaranteed to always be valid pub struct AtomicRef<T:'static>(AtomicPtr<T>, PhantomData<&'static T>); impl<T:'static> AtomicRef<T> { pub const fn new(initial: &'static T) -> AtomicRef<T> { AtomicRef(AtomicPtr::new(initial as *const T as *mut T), PhantomData) ...
use std::marker::PhantomData; use std::sync::atomic::{AtomicPtr, Ordering};
random_line_split
atomic_ref.rs
use std::marker::PhantomData; use std::sync::atomic::{AtomicPtr, Ordering}; /// This is essentially an `AtomicPtr` but is guaranteed to always be valid pub struct AtomicRef<T:'static>(AtomicPtr<T>, PhantomData<&'static T>); impl<T:'static> AtomicRef<T> { pub const fn new(initial: &'static T) -> AtomicRef<T> { ...
(&self) -> &Self::Target { // We never allow storing anything but a `'static` reference so it's safe to lend // it out for any amount of time. unsafe { &*self.0.load(Ordering::SeqCst) } } }
deref
identifier_name
memcached.rs
extern crate libc; use std::ptr; use std::mem::size_of; use std::c_str::CString; use libc::{ c_char, c_uint, size_t, malloc, free, c_void }; use native::{ memcached_create, memcached_set, memcached_get, memcached_st, memcached_return_t, memcached_server_add, }; pub mod native; pub struct Clie...
Server { host: host, port: port } } } impl Client { pub fn new() -> Client { Client{ cl: unsafe { memcached_create(ptr::null_mut()) } } } pub fn add_server(&self, server: &Server) { unsafe { memcached_server_add(self.cl, server.host.to_c_str().unwrap(), server.port as u16) }; } pub fn set(&se...
impl<'a> Server<'a> { pub fn new<'a>(host: &'a str, port: uint) -> Server<'a> {
random_line_split
memcached.rs
extern crate libc; use std::ptr; use std::mem::size_of; use std::c_str::CString; use libc::{ c_char, c_uint, size_t, malloc, free, c_void }; use native::{ memcached_create, memcached_set, memcached_get, memcached_st, memcached_return_t, memcached_server_add, }; pub mod native; pub struct Clie...
() -> Client { Client{ cl: unsafe { memcached_create(ptr::null_mut()) } } } pub fn add_server(&self, server: &Server) { unsafe { memcached_server_add(self.cl, server.host.to_c_str().unwrap(), server.port as u16) }; } pub fn set(&self, key: &str, value: &str, expire: int) { let key_c = key.to_c_str...
new
identifier_name
memcached.rs
extern crate libc; use std::ptr; use std::mem::size_of; use std::c_str::CString; use libc::{ c_char, c_uint, size_t, malloc, free, c_void }; use native::{ memcached_create, memcached_set, memcached_get, memcached_st, memcached_return_t, memcached_server_add, }; pub mod native; pub struct Clie...
pub fn set(&self, key: &str, value: &str, expire: int) { let key_c = key.to_c_str(); let value_c = value.to_c_str(); unsafe { memcached_set(self.cl, key_c.clone().unwrap(), key_c.len() as u64, value_c.clone().unwrap(), value_c.len() as u64, expire as i64, 0); } } pub fn get(&self, key: &s...
{ unsafe { memcached_server_add(self.cl, server.host.to_c_str().unwrap(), server.port as u16) }; }
identifier_body
server.rs
use std::borrow::Cow; use std::collections::BTreeMap; use std::convert::Infallible; use std::net::{Ipv4Addr, SocketAddr}; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use aes_ctr::cipher::generic_array::GenericArray; use aes_ctr::cipher::{NewStreamCipher, SyncStreamCipher}; use aes_ctr::Aes12...
let decrypted = { let mut data = encrypted.to_vec(); let mut cipher = Aes128Ctr::new( GenericArray::from_slice(&encryption_key[0..16]), GenericArray::from_slice(iv), ); cipher.apply_keystream(&mut data); data }...
{ warn!("Login error for user {:?}: MAC mismatch", username); let result = json!({ "status": 102, "spotifyError": 1, "statusString": "ERROR-MAC" }); let body = result.to_string(); return Response::new(Body::from...
conditional_block
server.rs
use std::borrow::Cow; use std::collections::BTreeMap; use std::convert::Infallible; use std::net::{Ipv4Addr, SocketAddr}; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use aes_ctr::cipher::generic_array::GenericArray; use aes_ctr::cipher::{NewStreamCipher, SyncStreamCipher}; use aes_ctr::Aes12...
} fn not_found(&self) -> Response<hyper::Body> { let mut res = Response::default(); *res.status_mut() = StatusCode::NOT_FOUND; res } async fn handle(self: Arc<Self>, request: Request<Body>) -> hyper::Result<Response<Body>> { let mut params = Params::new(); let ...
Response::new(Body::from(body))
random_line_split
server.rs
use std::borrow::Cow; use std::collections::BTreeMap; use std::convert::Infallible; use std::net::{Ipv4Addr, SocketAddr}; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use aes_ctr::cipher::generic_array::GenericArray; use aes_ctr::cipher::{NewStreamCipher, SyncStreamCipher}; use aes_ctr::Aes12...
async fn handle(self: Arc<Self>, request: Request<Body>) -> hyper::Result<Response<Body>> { let mut params = Params::new(); let (parts, body) = request.into_parts(); if let Some(query) = parts.uri.query() { let query_params = form_urlencoded::parse(query.as_bytes()); ...
{ let mut res = Response::default(); *res.status_mut() = StatusCode::NOT_FOUND; res }
identifier_body
server.rs
use std::borrow::Cow; use std::collections::BTreeMap; use std::convert::Infallible; use std::net::{Ipv4Addr, SocketAddr}; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use aes_ctr::cipher::generic_array::GenericArray; use aes_ctr::cipher::{NewStreamCipher, SyncStreamCipher}; use aes_ctr::Aes12...
{ config: Config, keys: DhLocalKeys, tx: mpsc::UnboundedSender<Credentials>, } impl RequestHandler { fn new(config: Config) -> (Self, mpsc::UnboundedReceiver<Credentials>) { let (tx, rx) = mpsc::unbounded_channel(); let discovery = Self { config, keys: DhLocalK...
RequestHandler
identifier_name
4.rs
// Single-byte XOR cipher // The hex encoded string: // 1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736 //... has been XOR'd against a single character. Find the key, decrypt the message. // You can do this by hand. But don't: write code to do it for you. // How? Devise some method for "scoring"...
(lines: Vec<String>) -> String { let mut best_string_score = 0; let mut best_string = String::new(); for line in lines.iter() { let pairs = cryptopalslib::convert::hex_string_to_decimal_pairs(line); let (score, _, string) = cryptopalslib::xor::score_and_xor(pairs); if score > best_string_score { b...
detect_xor_in_lines
identifier_name
4.rs
// Single-byte XOR cipher // The hex encoded string: // 1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736 //... has been XOR'd against a single character. Find the key, decrypt the message. // You can do this by hand. But don't: write code to do it for you. // How? Devise some method for "scoring"...
} let arg = match env::args().nth(1) { Some(s) => s, None => panic!("No input argument given") }; println!("input: {:?}", arg); let output = detect_xor_in_file(&arg); println!("output string: {:?}", output); } #[cfg(not(test))] fn detect_xor_in_file(path: &str) -> String { let path = Path::new(path); let ...
#[cfg(not(test))] fn main() { if env::args().count() < 2 { panic!("Must pass a file to decode")
random_line_split
4.rs
// Single-byte XOR cipher // The hex encoded string: // 1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736 //... has been XOR'd against a single character. Find the key, decrypt the message. // You can do this by hand. But don't: write code to do it for you. // How? Devise some method for "scoring"...
} best_string } #[cfg(test)] mod set1challenge4 { #[test] fn test() { let output = super::detect_xor_in_lines(vec!("1234567890ABCDEF123456".to_string(), "4574626531626563787f76".to_string(), "FEDCBA0987654321FEDCBA".to_string())); assert_eq!(output, "Test string"); } }
{ best_string_score = score; best_string = string; }
conditional_block
4.rs
// Single-byte XOR cipher // The hex encoded string: // 1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736 //... has been XOR'd against a single character. Find the key, decrypt the message. // You can do this by hand. But don't: write code to do it for you. // How? Devise some method for "scoring"...
#[cfg(test)] mod set1challenge4 { #[test] fn test() { let output = super::detect_xor_in_lines(vec!("1234567890ABCDEF123456".to_string(), "4574626531626563787f76".to_string(), "FEDCBA0987654321FEDCBA".to_string())); assert_eq!(output, "Test string"); } }
{ let mut best_string_score = 0; let mut best_string = String::new(); for line in lines.iter() { let pairs = cryptopalslib::convert::hex_string_to_decimal_pairs(line); let (score, _, string) = cryptopalslib::xor::score_and_xor(pairs); if score > best_string_score { best_string_score = score; be...
identifier_body
mod.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/. */ //! Enum wrappers to be able to select different channel implementations at runtime.
mod mpsc; use ::webgl::WebGLMsg; use serde::{Deserialize, Serialize}; use servo_config::opts; use std::fmt; lazy_static! { static ref IS_MULTIPROCESS: bool = { opts::multiprocess() }; } #[derive(Clone, Deserialize, Serialize)] pub enum WebGLSender<T: Serialize> { Ipc(ipc::WebGLSender<T>), Mps...
mod ipc;
random_line_split
mod.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/. */ //! Enum wrappers to be able to select different channel implementations at runtime. mod ipc; mod mpsc; use ::we...
(pub WebGLChan); impl WebGLPipeline { pub fn channel(&self) -> WebGLChan { self.0.clone() } }
WebGLPipeline
identifier_name
mod.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/. */ //! Enum wrappers to be able to select different channel implementations at runtime. mod ipc; mod mpsc; use ::we...
, WebGLSender::Mpsc(ref sender) => { sender.send(msg).map_err(|_| ()) } } } } pub type WebGLSendResult = Result<(), ()>; pub enum WebGLReceiver<T> where T: for<'de> Deserialize<'de> + Serialize { Ipc(ipc::WebGLReceiver<T>), Mpsc(mpsc::WebGLReceiver<T>), } i...
{ sender.send(msg).map_err(|_| ()) }
conditional_block
terminal.rs
use std::error::Error; use std::io::stdin; use std::io::Read; use std::thread; use std::sync::mpsc::{channel, Receiver}; pub fn init() -> Receiver<ControlKeys> { let (tx, rx) = channel::<ControlKeys>(); thread::spawn(move|| { loop { tx.send(read_stdin()).unwrap(); } }); rx ...
(rx: &Receiver<ControlKeys>, old: ControlKeys) -> ControlKeys { match rx.try_recv() { Ok(key) => key, Err(_) => old } } pub fn clear() { println!("\u{001B}[2J"); // "\u001B" is the ASCII code for ESCape } pub fn println(str: &str) { println!("{0}", str); } pub fn set_cursor(x: usize...
get
identifier_name
terminal.rs
use std::error::Error; use std::io::stdin; use std::io::Read; use std::thread; use std::sync::mpsc::{channel, Receiver}; pub fn init() -> Receiver<ControlKeys> { let (tx, rx) = channel::<ControlKeys>(); thread::spawn(move|| { loop { tx.send(read_stdin()).unwrap(); } }); rx ...
pub enum ControlKeys { KeyUp, KeyDown, KeyLeft, KeyRight, Unknown } /** * Read input from standard in. * It is expected to deliver a sequence of characters for every key press. * The console should be set in an appropriate manner to avoid line buffering. */ fn read_stdin() -> ControlKeys { let mut reader = s...
{ print!("\u{001B}[{0};{1}H", y + 1, x + 1); }
identifier_body
terminal.rs
use std::error::Error; use std::io::stdin; use std::io::Read; use std::thread; use std::sync::mpsc::{channel, Receiver}; pub fn init() -> Receiver<ControlKeys> { let (tx, rx) = channel::<ControlKeys>(); thread::spawn(move|| { loop { tx.send(read_stdin()).unwrap(); } }); rx ...
return ControlKeys::Unknown; } } } pub fn put(str: &str) { print!("{0}", str); }
{ if buf[2] == 65 { return ControlKeys::KeyUp; } if buf[2] == 66 { return ControlKeys::KeyDown; } if buf[2] == 67 { return ControlKeys::KeyRight; } if buf[2] == 68 { return ControlKeys::KeyLeft; } }
conditional_block
terminal.rs
use std::error::Error; use std::io::stdin; use std::io::Read; use std::thread; use std::sync::mpsc::{channel, Receiver}; pub fn init() -> Receiver<ControlKeys> { let (tx, rx) = channel::<ControlKeys>(); thread::spawn(move|| { loop { tx.send(read_stdin()).unwrap(); } }); rx
match rx.try_recv() { Ok(key) => key, Err(_) => old } } pub fn clear() { println!("\u{001B}[2J"); // "\u001B" is the ASCII code for ESCape } pub fn println(str: &str) { println!("{0}", str); } pub fn set_cursor(x: usize, y: usize) { print!("\u{001B}[{0};{1}H", y + 1, x + 1); } ...
} pub fn get(rx: &Receiver<ControlKeys>, old: ControlKeys) -> ControlKeys {
random_line_split
dir_walker.rs
extern crate libc; use std::path::{Path, PathBuf}; use std::ptr; use std::os::unix::io::RawFd; use catfs::error; use catfs::rlibc; pub struct DirWalker { dir: RawFd, cur: *mut libc::DIR, cur_path: PathBuf, stack: Vec<PathBuf>, } impl DirWalker { pub fn new(dir: RawFd) -> error::Result<DirWalker>...
(&mut self) -> error::Result<Option<PathBuf>> { loop { match rlibc::readdir(self.cur)? { Some(entry) => { if entry.en.d_type == libc::DT_DIR { let name = entry.name(); if name!= Path::new(".") && name!= Path::new(".....
next_internal
identifier_name
dir_walker.rs
extern crate libc; use std::path::{Path, PathBuf}; use std::ptr; use std::os::unix::io::RawFd; use catfs::error; use catfs::rlibc; pub struct DirWalker { dir: RawFd, cur: *mut libc::DIR, cur_path: PathBuf, stack: Vec<PathBuf>, } impl DirWalker { pub fn new(dir: RawFd) -> error::Result<DirWalker>...
let mut files: Vec<PathBuf> = DirWalker::new(fd).unwrap().collect(); files.sort(); assert_eq!(files.len(), 5); let mut iter = files.into_iter(); assert_eq!(iter.next().unwrap(), Path::new("dir1/file1")); assert_eq!(iter.next().unwrap(), Path::new("dir1/file2")); ...
let _ = env_logger::init(); let manifest = env::var_os("CARGO_MANIFEST_DIR").unwrap(); let resources = PathBuf::from(manifest).join("tests/resources"); let fd = rlibc::open(&resources, rlibc::O_RDONLY, 0).unwrap();
random_line_split
csssupportsrule.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::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindi...
} } impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self....
{ let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom(&url, Some(CssRuleType::Supports), ...
conditional_block
csssupportsrule.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::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindi...
let mut input = Parser::new(&mut input); let cond = SupportsCondition::parse(&mut input); if let Ok(cond) = cond { let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mod...
/// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn set_condition_text(&self, text: DOMString) { let mut input = ParserInput::new(&text);
random_line_split
csssupportsrule.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::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindi...
(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule.read_with(&guard).to_css_string(&guard).into() } }
get_css
identifier_name
csssupportsrule.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::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindi...
}
{ let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule.read_with(&guard).to_css_string(&guard).into() }
identifier_body
watch.rs
// Copyright 2015 Matthias Schorsch // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
else { let error_desc = format!("Failure detected with system error code {}", get_last_error()); Result::Err(errors::Error::new_with_description(errors::ErrorKind::Unknown, error_desc)) } } fn from_u16_slice(v: &[u8]) -> Box<Vec<FileNotifyInformation>> { let mut result:Vec<FileNotifyInformatio...
{ Result::Ok(from_u16_slice(result_buffer)) }
conditional_block