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
box.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let a = ~1; let b = ~(2, 3.5); let c = @4; let d = @false; _zzz(); } fn _zzz() {()}
main
identifier_name
enum-alignment.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T>(ptr: &T) -> uint { let ptr = ptr::to_unsafe_ptr(ptr); ptr as uint } fn is_aligned<T>(ptr: &T) -> bool { unsafe { let addr: uint = cast::transmute(ptr); (addr % sys::min_align_of::<T>()) == 0 } } pub fn main() { let x = Some(0u64); match x { None => fail2!(), ...
addr_of
identifier_name
enum-alignment.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn is_aligned<T>(ptr: &T) -> bool { unsafe { let addr: uint = cast::transmute(ptr); (addr % sys::min_align_of::<T>()) == 0 } } pub fn main() { let x = Some(0u64); match x { None => fail2!(), Some(ref y) => assert!(is_aligned(y)) } }
{ let ptr = ptr::to_unsafe_ptr(ptr); ptr as uint }
identifier_body
enum-alignment.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
None => fail2!(), Some(ref y) => assert!(is_aligned(y)) } }
let x = Some(0u64); match x {
random_line_split
io.rs
/*! This module provides some miscellaneous IO support routines. */ use std::io::{IoError, IoResult, OtherIoError}; /** Reads a line of input from the given `Reader`. This does not require a push-back buffer. It returns the line *with* the line terminator. Note that this function *does not* support old-school Mac ...
(s: &[u8]) -> IoResult<char> { let mut reader = ::std::io::BufReader::new(s); read_utf8_char(&mut reader) } test_str("abcdef"); test_str("私の日本語わ下手ですよ!"); assert!(first(&[0b1000_0000u8]).is_err()); assert!(first(&[0b1100_0000u8, 0b0000_0000]).is_err()); } /** Reads a single line from standard input. */ pub f...
first
identifier_name
io.rs
/*! This module provides some miscellaneous IO support routines. */ use std::io::{IoError, IoResult, OtherIoError}; /** Reads a line of input from the given `Reader`. This does not require a push-back buffer. It returns the line *with* the line terminator. Note that this function *does not* support old-school Mac ...
}
random_line_split
io.rs
/*! This module provides some miscellaneous IO support routines. */ use std::io::{IoError, IoResult, OtherIoError}; /** Reads a line of input from the given `Reader`. This does not require a push-back buffer. It returns the line *with* the line terminator. Note that this function *does not* support old-school Mac ...
:io::stdio::stdin_raw()) }
identifier_body
builder.rs
use ecs::state::State; use ecs::state::update_queue::UpdateQueues; use ecs::group::Groups; use ecs::module::{Module, Modules,Component}; pub struct StateBuilder<Cx: Send> { update_queues: UpdateQueues, groups: Groups, modules: Modules<Cx>, } impl<Cx: Send> StateBuilder<Cx> { pub fn new() -> Self { ...
self.update_queues.register::<C>(); self } pub fn register_module<M: Module<Cx>>(&mut self, module: M) -> &mut Self { self.modules.insert(Box::new(module)); self } pub fn build(self) -> State<Cx> { State::new(self.modules, self.groups, ...
pub fn register_component<C: Component>(&mut self) -> &mut Self {
random_line_split
builder.rs
use ecs::state::State; use ecs::state::update_queue::UpdateQueues; use ecs::group::Groups; use ecs::module::{Module, Modules,Component}; pub struct StateBuilder<Cx: Send> { update_queues: UpdateQueues, groups: Groups, modules: Modules<Cx>, } impl<Cx: Send> StateBuilder<Cx> { pub fn new() -> Self
pub fn register_component<C: Component>(&mut self) -> &mut Self { self.update_queues.register::<C>(); self } pub fn register_module<M: Module<Cx>>(&mut self, module: M) -> &mut Self { self.modules.insert(Box::new(module)); self } pub fn build(self) -> State<Cx> { ...
{ StateBuilder { update_queues: UpdateQueues::new(), groups: Groups::new(), modules: Modules::new(), } }
identifier_body
builder.rs
use ecs::state::State; use ecs::state::update_queue::UpdateQueues; use ecs::group::Groups; use ecs::module::{Module, Modules,Component}; pub struct StateBuilder<Cx: Send> { update_queues: UpdateQueues, groups: Groups, modules: Modules<Cx>, } impl<Cx: Send> StateBuilder<Cx> { pub fn new() -> Self { ...
<C: Component>(&mut self) -> &mut Self { self.update_queues.register::<C>(); self } pub fn register_module<M: Module<Cx>>(&mut self, module: M) -> &mut Self { self.modules.insert(Box::new(module)); self } pub fn build(self) -> State<Cx> { State::new(self.modules...
register_component
identifier_name
angle.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 angles. use num_traits::Zero; use std::{f32, f64}; use std::f64::consts::PI; use std::ops::Add; use ...
Angle::Grad(val) | Angle::Turn(val) | Angle::Rad(val) => val == 0. } } } impl ComputeSquaredDistance for Angle { #[inline] fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { // Use the formula for calculating the distance be...
random_line_split
angle.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 angles. use num_traits::Zero; use std::{f32, f64}; use std::f64::consts::PI; use std::ops::Add; use ...
(&self, other: &Self) -> Result<SquaredDistance, ()> { // Use the formula for calculating the distance between angles defined in SVG: // https://www.w3.org/TR/SVG/animate.html#complexDistances self.radians64().compute_squared_distance(&other.radians64()) } }
compute_squared_distance
identifier_name
angle.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 angles. use num_traits::Zero; use std::{f32, f64}; use std::f64::consts::PI; use std::ops::Add; use ...
} impl Add for Angle { type Output = Self; #[inline] fn add(self, rhs: Self) -> Self { match (self, rhs) { (Angle::Deg(x), Angle::Deg(y)) => Angle::Deg(x + y), (Angle::Grad(x), Angle::Grad(y)) => Angle::Grad(x + y), (Angle::Turn(x), Angle::Turn(y)) => Angle::Tu...
{ self }
identifier_body
FWTCBFbC.rs
pub fn count_characters(words: Vec<String>, chars: String) -> i32 { use std::collections::{HashMap, HashSet}; let char_set = { let mut char_table = HashMap::new(); for c in chars.chars() { *char_table.entry(c).or_insert(0) += 1 } char_table }; let words_sets =...
{ dbg!(count_characters( vec![ "cat".to_string(), "bt".to_string(), "hat".to_string(), "tree".to_string() ], "atach".to_string() )); dbg!(count_characters( vec![ "hello".to_string(), "world".to_string(),...
identifier_body
FWTCBFbC.rs
pub fn count_characters(words: Vec<String>, chars: String) -> i32 { use std::collections::{HashMap, HashSet}; let char_set = { let mut char_table = HashMap::new(); for c in chars.chars() { *char_table.entry(c).or_insert(0) += 1 } char_table }; let words_sets =...
"welldonehoneyr".to_string() )); }
vec![ "hello".to_string(), "world".to_string(), "leetcode".to_string(), ],
random_line_split
FWTCBFbC.rs
pub fn count_characters(words: Vec<String>, chars: String) -> i32 { use std::collections::{HashMap, HashSet}; let char_set = { let mut char_table = HashMap::new(); for c in chars.chars() { *char_table.entry(c).or_insert(0) += 1 } char_table }; let words_sets =...
() { dbg!(count_characters( vec![ "cat".to_string(), "bt".to_string(), "hat".to_string(), "tree".to_string() ], "atach".to_string() )); dbg!(count_characters( vec![ "hello".to_string(), "world".to_string...
main
identifier_name
FWTCBFbC.rs
pub fn count_characters(words: Vec<String>, chars: String) -> i32 { use std::collections::{HashMap, HashSet}; let char_set = { let mut char_table = HashMap::new(); for c in chars.chars() { *char_table.entry(c).or_insert(0) += 1 } char_table }; let words_sets =...
let mut flag = true; for (k, v) in &words_sets[i] { if let Some(n) = char_set.get(k) { if n < v { flag = false; break; } } else { flag = false; break; } }...
{ continue; }
conditional_block
game.rs
use common::GeneralError; use ctrl::{GameController, Gesture}; use gfx::{Scene, SceneBuilder, Window}; use level::Level; use player::Player; use sdl2::keyboard::Scancode; use sdl2::{self, Sdl}; use std::error::Error; use std::path::PathBuf; use super::SHADER_ROOT; use time; use wad::{Archive, TextureDirectory}; use gfx...
(config: GameConfig) -> Result<Game, Box<Error>> { let sdl = try!(sdl2::init().map_err(|e| GeneralError(e.0))); let window = try!(Window::new(&sdl, config.width, config.height)); let wad = try!(Archive::open(&config.wad_file, &config.metadata_file)); let textures = try!(TextureDirectory:...
new
identifier_name
game.rs
use common::GeneralError; use ctrl::{GameController, Gesture}; use gfx::{Scene, SceneBuilder, Window}; use level::Level; use player::Player; use sdl2::keyboard::Scancode; use sdl2::{self, Sdl}; use std::error::Error; use std::path::PathBuf; use super::SHADER_ROOT; use time; use wad::{Archive, TextureDirectory}; use gfx...
} } self.player.update(delta, &self.control, &self.level); self.scene.set_modelview(&self.player.camera().modelview()); self.scene.set_projection(self.player.camera().projection()); self.level.update(delta, &mut self.scene); try!(...
2 => self.text[long_help].set_visible(false), _ => unreachable!(),
random_line_split
game.rs
use common::GeneralError; use ctrl::{GameController, Gesture}; use gfx::{Scene, SceneBuilder, Window}; use level::Level; use player::Player; use sdl2::keyboard::Scancode; use sdl2::{self, Sdl}; use std::error::Error; use std::path::PathBuf; use super::SHADER_ROOT; use time; use wad::{Archive, TextureDirectory}; use gfx...
else if self.control.poll_gesture(&grab_toggle_gesture) { mouse_grabbed =!mouse_grabbed; self.control.set_mouse_enabled(mouse_grabbed); self.control.set_cursor_grabbed(mouse_grabbed); } else if self.control.poll_gesture(&help_gesture) { curren...
{ running = false; }
conditional_block
nil-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// 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. // LLDB can't handle zero-sized values // ignore-lldb // ignore-android: FIXME(#10381) ...
// 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
random_line_split
nil-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{} enum AnotherNilEnum {} // This test relies on gdb printing the string "{<No data fields>}" for empty // structs (which may change some time) fn main() { unsafe { let first: ANilEnum = ::std::mem::zeroed(); let second: AnotherNilEnum = ::std::mem::zeroed(); zzz(); // #break } } fn ...
ANilEnum
identifier_name
client.rs
// A client to the server. // Contains its own map and response variables use super::super::ui::*; use super::*; use context::*; pub struct Client { connection: ClientConn, pub map: Map, pub side: Side, response_queue: Vec<Response>, } impl Client { pub fn new(mut connection: ClientConn) -> Resul...
pub fn recv(&mut self) -> bool { let mut recieved_message = false; while let Ok(message) = self.connection.recv() { match message { ServerMessage::Responses(mut responses) => { self.response_queue.append(&mut responses) } ...
{ let client_stream = TcpStream::connect(addr) .chain_err(|| format!("Failed to connect to server at '{}'", addr))?; let connection = Connection::new_tcp(client_stream)?; Client::new(connection) }
identifier_body
client.rs
// A client to the server. // Contains its own map and response variables use super::super::ui::*; use super::*; use context::*; pub struct Client { connection: ClientConn, pub map: Map, pub side: Side, response_queue: Vec<Response>, } impl Client { pub fn new(mut connection: ClientConn) -> Resul...
(&self, unit: u8, path: &[PathPoint]) { self.send_command(unit, Command::walk(path)); } pub fn turn(&self, unit: u8, facing: UnitFacing) { self.send_command(unit, Command::Turn(facing)); } pub fn fire(&self, unit: u8, x: usize, y: usize) { self.send_command(unit, Command::Fire ...
walk
identifier_name
client.rs
// A client to the server. // Contains its own map and response variables use super::super::ui::*; use super::*; use context::*; pub struct Client { connection: ClientConn, pub map: Map, pub side: Side, response_queue: Vec<Response>, } impl Client { pub fn new(mut connection: ClientConn) -> Resul...
i += 1; } if status.blocking { break; } } } pub fn process_state_updates(&mut self) -> (bool, bool) { let mut invalid_command = false; for response in self.response_queue.drain(..) { match response { ...
if status.finished { self.response_queue.remove(0); } else {
random_line_split
lang_items.rs
/// Default panic handler #[linkage = "weak"] #[lang = "panic_fmt"] unsafe extern "C" fn panic_fmt( _args: ::core::fmt::Arguments, _file: &'static str, _line: u32, ) ->! { hprint!("panicked at '"); match () { #[cfg(feature = "semihosting")] () => { ::cortex_m_semihosting:...
{ main(); 0 }
identifier_body
lang_items.rs
/// Default panic handler #[linkage = "weak"] #[lang = "panic_fmt"] unsafe extern "C" fn panic_fmt( _args: ::core::fmt::Arguments, _file: &'static str, _line: u32, ) ->! { hprint!("panicked at '"); match () { #[cfg(feature = "semihosting")] () => { ::cortex_m_semihosting:...
} hprintln!("', {}:{}", _file, _line); bkpt!(); loop {} } /// Lang item required to make the normal `main` work in applications // This is how the `start` lang item works: // When `rustc` compiles a binary crate, it creates a `main` function that looks // like this: // // ``` // #[export_name = "mai...
{}
conditional_block
lang_items.rs
/// Default panic handler #[linkage = "weak"] #[lang = "panic_fmt"] unsafe extern "C" fn panic_fmt( _args: ::core::fmt::Arguments, _file: &'static str, _line: u32, ) ->! { hprint!("panicked at '"); match () { #[cfg(feature = "semihosting")] () => { ::cortex_m_semihosting:...
(main: fn(), _argc: isize, _argv: *const *const u8) -> isize { main(); 0 }
start
identifier_name
lang_items.rs
/// Default panic handler #[linkage = "weak"] #[lang = "panic_fmt"] unsafe extern "C" fn panic_fmt( _args: ::core::fmt::Arguments, _file: &'static str, _line: u32, ) ->! { hprint!("panicked at '"); match () { #[cfg(feature = "semihosting")] () => { ::cortex_m_semihosting:...
// // The final piece is that the entry point of our program, the reset handler, // has to call `rustc_main`. That's covered by the `reset_handler` function in // `src/exceptions.rs` #[lang = "start"] extern "C" fn start(main: fn(), _argc: isize, _argv: *const *const u8) -> isize { main(); 0 }
random_line_split
block-iter-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let v = ~[1, 2, 3, 4, 5]; let mut sum = 0; iter_vec(v.clone(), |i| { iter_vec(v.clone(), |j| { sum += *i * *j; }); }); error!("{:?}", sum); assert_eq!(sum, 225); }
{ for x in v.iter() { f(x); } }
identifier_body
block-iter-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T>(v: ~[T], f: |&T|) { for x in v.iter() { f(x); } } pub fn main() { let v = ~[1, 2, 3, 4, 5]; let mut sum = 0; iter_vec(v.clone(), |i| { iter_vec(v.clone(), |j| { sum += *i * *j; }); }); error!("{:?}", sum); assert_eq!(sum, 225); }
iter_vec
identifier_name
block-iter-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn iter_vec<T>(v: ~[T], f: |&T|) { for x in v.iter() { f(x); } } pub fn main() { let v = ~[1, 2, 3, 4, 5]; let mut sum = 0; iter_vec(v.clone(), |i| { iter_vec(v.clone(), |j| { sum += *i * *j; }); }); error!("{:?}", sum); assert_eq!(sum, 225); }
// option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast
random_line_split
clipboard_provider.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 ipc_channel::ipc; use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as Constellat...
(&mut self) -> String { self.content.clone() } fn set_clipboard_contents(&mut self, s: String) { self.content = s; } }
clipboard_contents
identifier_name
clipboard_provider.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 ipc_channel::ipc; use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as Constellat...
} } pub struct DummyClipboardContext { content: String } impl DummyClipboardContext { pub fn new(s: &str) -> DummyClipboardContext { DummyClipboardContext { content: s.to_owned() } } } impl ClipboardProvider for DummyClipboardContext { fn clipboard_contents(&mut self) ...
random_line_split
lib.rs
//! stal-rs //! ==== //! //! Set algebra solver for Redis in Rust, based on //! [Stal](https://github.com/soveran/stal). //! //! Description //! ----------- //!
//! //! Usage //! ----- //! //! `stal-rs` has no dependencies. It produces a vector of Redis operations that //! have to be run by the user. //! //! ```rust //! extern crate stal; //! //! let foobar = stal::Set::Inter(vec![stal::Set::Key(b"foo".to_vec()), stal::Set::Key(b"bar".to_vec())]); //! let foobar_nobaz = stal::...
//! `stal-rs` provide set operations and resolves them in [Redis][redis].
random_line_split
lib.rs
//! stal-rs //! ==== //! //! Set algebra solver for Redis in Rust, based on //! [Stal](https://github.com/soveran/stal). //! //! Description //! ----------- //! //! `stal-rs` provide set operations and resolves them in [Redis][redis]. //! //! Usage //! ----- //! //! `stal-rs` has no dependencies. It produces a vector o...
(&self) -> &'static str { match *self { Key(_) => unreachable!(), Union(_) => "SUNIONSTORE", Inter(_) => "SINTERSTORE", Diff(_) => "SDIFFSTORE", } } /// Appends the operation to `ops` and any temporary id created to `ids`. /// Returns the key ...
command
identifier_name
bluetoothdevice.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::BluetoothDeviceBinding; use dom::bindings::codegen::Bindings::BluetoothDevic...
pub fn new(global: GlobalRef, id: DOMString, name: Option<DOMString>, adData: &BluetoothAdvertisingData) -> Root<BluetoothDevice> { reflect_dom_object(box BluetoothDevice::new_inherited(id, ...
{ BluetoothDevice { reflector_: Reflector::new(), id: id, name: name, adData: MutHeap::new(adData), gatt: Default::default(), } }
identifier_body
bluetoothdevice.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::BluetoothDeviceBinding; use dom::bindings::codegen::Bindings::BluetoothDevic...
adData: &BluetoothAdvertisingData) -> BluetoothDevice { BluetoothDevice { reflector_: Reflector::new(), id: id, name: name, adData: MutHeap::new(adData), gatt: Default::default(), } } p...
random_line_split
bluetoothdevice.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::BluetoothDeviceBinding; use dom::bindings::codegen::Bindings::BluetoothDevic...
(id: DOMString, name: Option<DOMString>, adData: &BluetoothAdvertisingData) -> BluetoothDevice { BluetoothDevice { reflector_: Reflector::new(), id: id, name: name, adData: MutHeap::new(adD...
new_inherited
identifier_name
color.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/. */ //! Resolved color values. use super::{Context, ToResolvedValue}; use crate::values::computed; use crate::value...
fn from_resolved_value(resolved: Self::ResolvedValue) -> Self { generics::Color::Numeric(resolved) } } impl ToResolvedValue for computed::ColorOrAuto { // A resolved caret-color value is an rgba color, with auto resolving to // currentcolor. type ResolvedValue = cssparser::RGBA; #[inli...
fn to_resolved_value(self, context: &Context) -> Self::ResolvedValue { context.style.resolve_color(self) } #[inline]
random_line_split
color.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/. */ //! Resolved color values. use super::{Context, ToResolvedValue}; use crate::values::computed; use crate::value...
(self, context: &Context) -> Self::ResolvedValue { context.style.resolve_color(self) } #[inline] fn from_resolved_value(resolved: Self::ResolvedValue) -> Self { generics::Color::Numeric(resolved) } } impl ToResolvedValue for computed::ColorOrAuto { // A resolved caret-color value i...
to_resolved_value
identifier_name
color.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/. */ //! Resolved color values. use super::{Context, ToResolvedValue}; use crate::values::computed; use crate::value...
#[inline] fn from_resolved_value(resolved: Self::ResolvedValue) -> Self { generics::ColorOrAuto::Color(computed::Color::from_resolved_value(resolved)) } }
{ let color = match self { generics::ColorOrAuto::Color(color) => color, generics::ColorOrAuto::Auto => generics::Color::CurrentColor, }; color.to_resolved_value(context) }
identifier_body
main.rs
#![feature(plugin)] #![plugin(regex_macros)] extern crate itertools; extern crate regex; extern crate rustc_serialize; extern crate strsim; extern crate telegram_bot as telegram; extern crate term_painter; #[macro_use] mod log;
mod needed; use bot::MartiniBot; use log::LogLevel; use std::env; use std::path::Path; fn main() { // Fetch environment variable with bot token let token = match env::var("TELEGRAM_BOT_TOKEN") { Ok(tok) => tok, Err(e) => panic!("Environment variable 'TELEGRAM_BOT_TOKEN' missing! {...
mod bot; mod iter;
random_line_split
main.rs
#![feature(plugin)] #![plugin(regex_macros)] extern crate itertools; extern crate regex; extern crate rustc_serialize; extern crate strsim; extern crate telegram_bot as telegram; extern crate term_painter; #[macro_use] mod log; mod bot; mod iter; mod needed; use bot::MartiniBot; use log::LogLevel; use std::env; use...
{ // Fetch environment variable with bot token let token = match env::var("TELEGRAM_BOT_TOKEN") { Ok(tok) => tok, Err(e) => panic!("Environment variable 'TELEGRAM_BOT_TOKEN' missing! {}", e), }; // Create bot and print bot information, if it succeeded let mut bot = Marti...
identifier_body
main.rs
#![feature(plugin)] #![plugin(regex_macros)] extern crate itertools; extern crate regex; extern crate rustc_serialize; extern crate strsim; extern crate telegram_bot as telegram; extern crate term_painter; #[macro_use] mod log; mod bot; mod iter; mod needed; use bot::MartiniBot; use log::LogLevel; use std::env; use...
() { // Fetch environment variable with bot token let token = match env::var("TELEGRAM_BOT_TOKEN") { Ok(tok) => tok, Err(e) => panic!("Environment variable 'TELEGRAM_BOT_TOKEN' missing! {}", e), }; // Create bot and print bot information, if it succeeded let mut bot = Ma...
main
identifier_name
main.rs
use std::int; use std::comm::stream; use std::comm::Port; use std::comm::Chan; type MaybeInt = Option<int>; fn fib_generator(max: int, chan: &Chan<MaybeInt>) { let mut a = 0; let mut b = 1; loop { let next = a + b; if next > max { break; } b = a; a ...
} let mut accum: int = 0; loop { let next: MaybeInt = port.recv(); match next { Some(x) if x % 2 == 0 => accum += x, Some(_) => loop, None => break, }; } println(fmt!("%d", accum)); }
random_line_split
main.rs
use std::int; use std::comm::stream; use std::comm::Port; use std::comm::Chan; type MaybeInt = Option<int>; fn
(max: int, chan: &Chan<MaybeInt>) { let mut a = 0; let mut b = 1; loop { let next = a + b; if next > max { break; } b = a; a = next; chan.send(Some(next)); } chan.send(None); } fn main() { let (port, chan): (Port<MaybeInt>, Chan<...
fib_generator
identifier_name
main.rs
use std::int; use std::comm::stream; use std::comm::Port; use std::comm::Chan; type MaybeInt = Option<int>; fn fib_generator(max: int, chan: &Chan<MaybeInt>)
fn main() { let (port, chan): (Port<MaybeInt>, Chan<MaybeInt>) = stream(); do spawn { fib_generator(4000000, &chan); } let mut accum: int = 0; loop { let next: MaybeInt = port.recv(); match next { Some(x) if x % 2 == 0 => accum += x, Some(_) => ...
{ let mut a = 0; let mut b = 1; loop { let next = a + b; if next > max { break; } b = a; a = next; chan.send(Some(next)); } chan.send(None); }
identifier_body
document_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Tracking of pending loads in a document. //! //! <https://html.spec.whatwg.org/multipage/#the-end> use crate...
// Associated fetches will be canceled when dropping the canceller. self.cancellers.clear(); canceled_any } /// Add a load to the list of blocking loads. fn add_blocking_load(&mut self, load: LoadType) { debug!( "Adding blocking load {:?} ({}).", load...
let canceled_any = !self.cancellers.is_empty();
random_line_split
document_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Tracking of pending loads in a document. //! //! <https://html.spec.whatwg.org/multipage/#the-end> use crate...
(&self) -> bool { // TODO: Ensure that we report blocked if parsing is still ongoing. !self.blocking_loads.is_empty() } pub fn is_only_blocked_by_iframes(&self) -> bool { self.blocking_loads.iter().all(|load| match *load { LoadType::Subframe(_) => true, _ => false...
is_blocked
identifier_name
document_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Tracking of pending loads in a document. //! //! <https://html.spec.whatwg.org/multipage/#the-end> use crate...
} } #[derive(JSTraceable, MallocSizeOf)] pub struct DocumentLoader { resource_threads: ResourceThreads, blocking_loads: Vec<LoadType>, events_inhibited: bool, cancellers: Vec<FetchCanceller>, } impl DocumentLoader { pub fn new(existing: &DocumentLoader) -> DocumentLoader { DocumentLoa...
{ self.doc.finish_load(load); }
conditional_block
namespaces.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::hashmap::HashMap; use cssparser::*; use errors::log_css_error; pub struct NamespaceMap { default: Op...
url = Some(value); break }, _ => syntax_error!(), } } if iter.next().is_some() { syntax_error!() } match (prefix, url) { (Some(prefix), Some(url)) => { if namespaces.prefix_map.swap(prefix, url).is_some() { l...
{ let location = rule.location; macro_rules! syntax_error( () => {{ log_css_error(location, "Invalid @namespace rule"); return }}; ); if rule.block.is_some() { syntax_error!() } let mut prefix: Option<~str> = None; let mut url: Option<~str> = None; let...
identifier_body
namespaces.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::hashmap::HashMap; use cssparser::*; use errors::log_css_error; pub struct NamespaceMap { default: Op...
() -> NamespaceMap { NamespaceMap { default: None, prefix_map: HashMap::new() } } } pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) { let location = rule.location; macro_rules! syntax_error( () => {{ log_css_error(location, "Invalid @namespace rule"); ...
new
identifier_name
namespaces.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::hashmap::HashMap; use cssparser::*; use errors::log_css_error; pub struct NamespaceMap { default: Op...
let mut prefix: Option<~str> = None; let mut url: Option<~str> = None; let mut iter = rule.prelude.move_skip_whitespace(); for component_value in iter { match component_value { Ident(value) => { if prefix.is_some() { syntax_error!() } prefix = Some(va...
{ syntax_error!() }
conditional_block
namespaces.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::hashmap::HashMap; use cssparser::*; use errors::log_css_error; pub struct NamespaceMap { default: Op...
let location = rule.location; macro_rules! syntax_error( () => {{ log_css_error(location, "Invalid @namespace rule"); return }}; ); if rule.block.is_some() { syntax_error!() } let mut prefix: Option<~str> = None; let mut url: Option<~str> = None; let m...
pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) {
random_line_split
ns_t_array.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/. */ //! Rust helpers for Gecko's nsTArray. use gecko_bindings::bindings; use gecko_bindings::structs::{nsTArray, nsTA...
cap, mem::size_of::<T>(), ) } } } /// Clears the array storage without calling the destructor on the values. #[inline] pub unsafe fn clear(&mut self) { if self.len()!= 0 { bindings::Gecko_ClearPODTArray( ...
bindings::Gecko_EnsureTArrayCapacity( self as *mut nsTArray<T> as *mut _,
random_line_split
ns_t_array.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/. */ //! Rust helpers for Gecko's nsTArray. use gecko_bindings::bindings; use gecko_bindings::structs::{nsTArray, nsTA...
/// Resize and set the length of the array to `len`. /// /// unsafe because this may leave the array with uninitialized elements. /// /// This will not call constructors. If you need that, either manually add /// bindings or run the typed `EnsureCapacity` call on the gecko side. pub unsaf...
{ unsafe { self.clear() } }
identifier_body
ns_t_array.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/. */ //! Rust helpers for Gecko's nsTArray. use gecko_bindings::bindings; use gecko_bindings::structs::{nsTArray, nsTA...
(&mut self, len: u32) where T: Copy, { self.ensure_capacity(len as usize); let header = self.header_mut(); header.mLength = len; } /// Collects the given iterator into this array. /// /// Not unsafe because we won't leave uninitialized elements in the array. ...
set_len_pod
identifier_name
ns_t_array.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/. */ //! Rust helpers for Gecko's nsTArray. use gecko_bindings::bindings; use gecko_bindings::structs::{nsTArray, nsTA...
} /// Clears a POD array. This is safe since copy types are memcopyable. #[inline] pub fn clear_pod(&mut self) where T: Copy, { unsafe { self.clear() } } /// Resize and set the length of the array to `len`. /// /// unsafe because this may leave the array with u...
{ bindings::Gecko_ClearPODTArray( self as *mut nsTArray<T> as *mut _, mem::size_of::<T>(), mem::align_of::<T>(), ); }
conditional_block
credentials.rs
#[macro_use] extern crate accord; use accord::{Accord, Result as AccordResult}; use accord::validators::{length, contains, not_contain_any}; struct Credentials { pub email: String, pub password: String, } impl Accord for Credentials { #[cfg(not(feature = "inclusive_range"))] fn validate(&self) -> Acc...
(&self) -> AccordResult { rules!{ "email" => self.email => [length(5..=64), contains("@"), contains(".")], "password" => self.password => [not_contain_any(&["1234", "admin", "password"])] } } } #[test] fn main() { let a = Credentials { email: "test@test.test".to_...
validate
identifier_name
credentials.rs
#[macro_use] extern crate accord; use accord::{Accord, Result as AccordResult}; use accord::validators::{length, contains, not_contain_any}; struct Credentials { pub email: String, pub password: String, } impl Accord for Credentials { #[cfg(not(feature = "inclusive_range"))] fn validate(&self) -> Acc...
} #[test] fn main() { let a = Credentials { email: "test@test.test".to_string(), password: "lfdsfsfsfghdgdljddsjfkdlsf".to_string(), }; let b = Credentials { email: "t".to_string(), password: "admin1234password".to_string(), }; assert!(a.validate().is_ok()); a...
{ rules!{ "email" => self.email => [length(5..=64), contains("@"), contains(".")], "password" => self.password => [not_contain_any(&["1234", "admin", "password"])] } }
identifier_body
credentials.rs
#[macro_use] extern crate accord; use accord::{Accord, Result as AccordResult};
pub password: String, } impl Accord for Credentials { #[cfg(not(feature = "inclusive_range"))] fn validate(&self) -> AccordResult { rules!{ "email" => self.email => [length(5, 64), contains("@"), contains(".")], "password" => self.password => [not_contain_any(&["1234", "admi...
use accord::validators::{length, contains, not_contain_any}; struct Credentials { pub email: String,
random_line_split
p13.rs
use std::collections::BTreeMap; use rand::{Rng, weak_rng}; use serialize::json::{Json, ToJson}; use ssl::symm::{self, encrypt, decrypt}; fn parse_querystr(input: &str) -> Result<Json, ()> { let mut obj = BTreeMap::new(); for pair in input.split('&') { let mut items = pair.split('='); match (it...
}; } Ok(Json::Object(obj)) } #[test] fn test_parse_queryst() { let json = parse_querystr("foo=bar&baz=wanker@foobar.com").unwrap(); let obj = json.as_object().unwrap(); assert_eq!(obj["foo"], "bar".to_json()); assert_eq!(obj["baz"], "wanker@foobar.com".to_json()); } fn profile_for(ema...
{ return Err(()); }
conditional_block
p13.rs
use std::collections::BTreeMap; use rand::{Rng, weak_rng}; use serialize::json::{Json, ToJson}; use ssl::symm::{self, encrypt, decrypt}; fn parse_querystr(input: &str) -> Result<Json, ()> { let mut obj = BTreeMap::new(); for pair in input.split('&') { let mut items = pair.split('='); match (it...
let mut rng = weak_rng(); let mut key = [0_u8; 16]; rng.fill_bytes(&mut key); // 0123456789012345|0123456789012345|0123456789012345|012345678912345 // email=AAAAAAAAAA|adminPPPPPPPPPPP|AAA&uid=10&role=|userPPPPPPPPPPP // ^^^^^^^^^^|^^^^^^^^^^^^^^^^|^^^ // input ...
let blocksize = 16;
random_line_split
p13.rs
use std::collections::BTreeMap; use rand::{Rng, weak_rng}; use serialize::json::{Json, ToJson}; use ssl::symm::{self, encrypt, decrypt}; fn parse_querystr(input: &str) -> Result<Json, ()> { let mut obj = BTreeMap::new(); for pair in input.split('&') { let mut items = pair.split('='); match (it...
(key: &[u8], input: &str) -> Vec<u8> { let plaintext = profile_for(input); let data = plaintext.as_bytes(); encrypt(symm::Cipher::aes_128_ecb(), key, None, data).unwrap() } fn decryption_oracle(key: &[u8], data: &[u8]) -> Json { let plaintext = decrypt(symm::Cipher::aes_128_ecb(), key, None, data).unwr...
encryption_oracle
identifier_name
p13.rs
use std::collections::BTreeMap; use rand::{Rng, weak_rng}; use serialize::json::{Json, ToJson}; use ssl::symm::{self, encrypt, decrypt}; fn parse_querystr(input: &str) -> Result<Json, ()>
#[test] fn test_parse_queryst() { let json = parse_querystr("foo=bar&baz=wanker@foobar.com").unwrap(); let obj = json.as_object().unwrap(); assert_eq!(obj["foo"], "bar".to_json()); assert_eq!(obj["baz"], "wanker@foobar.com".to_json()); } fn profile_for(email: &str) -> String { let email_clean = e...
{ let mut obj = BTreeMap::new(); for pair in input.split('&') { let mut items = pair.split('='); match (items.next(), items.next(), items.next()) { (Some(key), Some(val), None) => { obj.insert(key.to_string(), Json::String(val.to_string())); }, ...
identifier_body
tokenizer.rs
/* * Copyright 2006 Kenta Cho. Some rights reserved. */ use std::io::prelude::*; use std::fs::File; fn readFile(fileName : &string, separator : &string) -> string { let mut file = File::open(fileName.unwrap()); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); let mut...
() { } /* /* * Tokenizer. */ public class Tokenizer { private: public static string[] readFile(string fileName, string separator) { string[] result; auto file = new File(fileName, FileMode.In); char[][] lines = splitLines(file); foreach(line; lines) { char[][] spl =...
main
identifier_name
tokenizer.rs
/* * Copyright 2006 Kenta Cho. Some rights reserved. */ use std::io::prelude::*; use std::fs::File;
file.read_to_string(&mut contents).unwrap(); let mut result : Vec[String]; // Returns amount of bytes read and append the result to the buffer let result = file.read_to_end(&mut contents).unwrap(); for line in result.lines() { for s in line.split(separator) { result.push(s.trim()); } } ...
fn readFile(fileName : &string, separator : &string) -> string { let mut file = File::open(fileName.unwrap()); let mut contents = String::new();
random_line_split
tokenizer.rs
/* * Copyright 2006 Kenta Cho. Some rights reserved. */ use std::io::prelude::*; use std::fs::File; fn readFile(fileName : &string, separator : &string) -> string
fn main() { } /* /* * Tokenizer. */ public class Tokenizer { private: public static string[] readFile(string fileName, string separator) { string[] result; auto file = new File(fileName, FileMode.In); char[][] lines = splitLines(file); foreach(line; lines) { cha...
{ let mut file = File::open(fileName.unwrap()); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); let mut result : Vec[String]; // Returns amount of bytes read and append the result to the buffer let result = file.read_to_end(&mut contents).unwrap(); for line in resul...
identifier_body
connection.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // Th...
/// Creates a new peer connection. pub fn peer(id: ServerId, addr: SocketAddr) -> Result<Connection> { let stream = try!(TcpStream::connect(&addr)); Ok(Connection { kind: ConnectionKind::Peer(id), addr: addr, stream: Some(MessageStream::new(stream, ...
{ let addr = try!(socket.peer_addr()); Ok(Connection { kind: ConnectionKind::Unknown, addr: addr, stream: Some(MessageStream::new(socket, ReaderOptions::new())), backoff: Backoff::with_duration_range(50, 10000), }) }
identifier_body
connection.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // Th...
use std::rc::Rc; fn poll_opt() -> PollOpt { PollOpt::edge() | PollOpt::oneshot() } /// The type of a connection. #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] pub enum ConnectionKind { /// A peer in the cluster. Peer(ServerId), /// A client which is asking the Raft cluster to do things. Clien...
use state_machine::StateMachine; use std::fmt; use std::net::SocketAddr;
random_line_split
connection.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // Th...
(&self) -> &SocketAddr { &self.addr } pub fn set_addr(&mut self, addr: SocketAddr) { self.addr = addr; } /// Returns the connection's stream. /// Must only be called while the connection is active. fn stream(&self) -> &MessageStream<TcpStream, HeapAllocator, Rc<Builder<HeapAllo...
addr
identifier_name
mod.rs
use std::rc::Rc; use std::vec::Vec; pub mod database; pub mod parser; // bytes -> events pub mod builder; // events -> DOM pub mod generator; // DOM -> bytes pub mod templates; pub mod midlevel; // events -> events+DOM #[derive(Debug,Eq,PartialEq,Clone,Copy)] pub enum Type { Master, Unsigned, Signed, ...
(c: database::Class, d:i64 ) -> Element { Element { class: c, content: ElementContent::MatroskaDate(d)}} pub fn el<T>(c: database::Class, d:T) -> Element where T:IntoIterator<Item=Element> { let mut v = vec![]; for i in d { v.push ( Rc::new(i) ); } Element { class: c, content: ElementCont...
el_date
identifier_name
mod.rs
use std::rc::Rc; use std::vec::Vec; pub mod database; pub mod parser; // bytes -> events pub mod builder; // events -> DOM pub mod generator; // DOM -> bytes pub mod templates; pub mod midlevel; // events -> events+DOM #[derive(Debug,Eq,PartialEq,Clone,Copy)] pub enum Type { Master, Unsigned, Signed, ...
.to_string(); Element { class: EBML, content: Master(vec![ Rc::new(Element {class: EBMLVersion, content: Unsigned(1)}), Rc::new(Element {class: EBMLReadVersion, content: Unsigned(1)}), Rc::new(Element {class: EBMLMaxIDLength, content: Unsigned(4)}), Rc::new(Element {class: ...
{ "matroska"}
conditional_block
mod.rs
use std::rc::Rc; use std::vec::Vec; pub mod database; pub mod parser; // bytes -> events pub mod builder; // events -> DOM pub mod generator; // DOM -> bytes pub mod templates; pub mod midlevel; // events -> events+DOM #[derive(Debug,Eq,PartialEq,Clone,Copy)] pub enum Type { Master, Unsigned, Signed, ...
{ use self::database::Class::*; use self::ElementContent::{Unsigned,Text,Master}; let doctype = if webm { "webm" } else { "matroska"}.to_string(); Element { class: EBML, content: Master(vec![ Rc::new(Element {class: EBMLVersion, content: Unsigned(1)}), Rc::new(Element {class: EBML...
identifier_body
mod.rs
use std::rc::Rc; use std::vec::Vec; pub mod database; pub mod parser; // bytes -> events pub mod builder; // events -> DOM pub mod generator; // DOM -> bytes pub mod templates; pub mod midlevel; // events -> events+DOM #[derive(Debug,Eq,PartialEq,Clone,Copy)] pub enum Type { Master, Unsigned, Signed, ...
} #[derive(PartialEq,Debug,PartialOrd,Clone)] #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))] pub struct Element { pub class : database::Class, pub content : ElementContent, } // Cosy constructors pub fn el_bin (c: database::Class, d:Vec<u8>) -> Element { Element { class: c, ...
Float(f64), MatroskaDate(i64), // Nanoseconds since 20010101_000000_UTC Unknown(u64, Rc<Vec<u8>>)
random_line_split
membership.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 async_trait::async_trait; use std::panic::RefUnwindSafe; use std::sync::Arc; use crate::MononokeIdentitySet; pub ...
struct AllowlistChecker { allowlist: MononokeIdentitySet, } #[async_trait] impl MembershipChecker for AllowlistChecker { async fn is_member(&self, identities: &MononokeIdentitySet) -> Result<bool> { Ok(!self.allowlist.is_disjoint(identities)) } }
random_line_split
membership.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 async_trait::async_trait; use std::panic::RefUnwindSafe; use std::sync::Arc; use crate::MononokeIdentitySet; pub ...
} struct NeverMember {} #[async_trait] impl MembershipChecker for NeverMember { async fn is_member(&self, _identities: &MononokeIdentitySet) -> Result<bool> { Ok(false) } } struct AllowlistChecker { allowlist: MononokeIdentitySet, } #[async_trait] impl MembershipChecker for AllowlistChecker { ...
{ Ok(true) }
identifier_body
membership.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 async_trait::async_trait; use std::panic::RefUnwindSafe; use std::sync::Arc; use crate::MononokeIdentitySet; pub ...
() -> BoxMembershipChecker { Box::new(AlwaysMember {}) } pub fn never_member() -> BoxMembershipChecker { Box::new(NeverMember {}) } pub fn allowlist_checker(allowlist: MononokeIdentitySet) -> BoxMembershipChecker { Box::new(AllowlistChecker { allowlist }) } } struct Always...
always_member
identifier_name
issue-36023.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} #[inline(never)] fn env_var(s: &str) -> Result<String, VarError> { Err(VarError::NotPresent) } pub enum VarError { NotPresent, NotUnicode(String), }
{ panic!() }
conditional_block
issue-36023.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(s: &str) -> Result<String, VarError> { Err(VarError::NotPresent) } pub enum VarError { NotPresent, NotUnicode(String), }
env_var
identifier_name
issue-36023.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
use std::ops::Deref; fn main() { if env_var("FOOBAR").as_ref().map(Deref::deref).ok() == Some("yes") { panic!() } let env_home: Result<String, ()> = Ok("foo-bar-baz".to_string()); let env_home = env_home.as_ref().map(Deref::deref).ok(); if env_home == Some("") { panic!() } } #[inline(nev...
// run-pass #![allow(unused_variables)]
random_line_split
main.rs
#![feature(custom_derive, plugin)] #![plugin(serde_macros)] extern crate mui; use std::cell::Cell; use mui::prelude::*; fn main() { let mut app = mui::App::new("Mui Widgets Demo!"); // primitives let rect = mui::Rect::new("r1", true); rect.set_zpos(3); app.add_widget(&rect); let count = Ce...
layout.set_zpos(5); layout.add_widget(&button); layout.add_widget(&button2); app.add_widget(&layout); let sa_textbox = mui::TextBox::new("textbox"); sa_textbox.set_xy(600.0, 200.0); app.add_widget(&sa_textbox); app.run(); }
let mut layout = mui::BoxLayout::new("l1"); layout.set_xy(300.0, 40.0);
random_line_split
main.rs
#![feature(custom_derive, plugin)] #![plugin(serde_macros)] extern crate mui; use std::cell::Cell; use mui::prelude::*; fn
() { let mut app = mui::App::new("Mui Widgets Demo!"); // primitives let rect = mui::Rect::new("r1", true); rect.set_zpos(3); app.add_widget(&rect); let count = Cell::new(0); let count2 = Cell::new(0); // sa - stand alone let mut sa_button = mui::Button::new("b1"); sa_butto...
main
identifier_name
main.rs
#![feature(custom_derive, plugin)] #![plugin(serde_macros)] extern crate mui; use std::cell::Cell; use mui::prelude::*; fn main()
let mut button = mui::Button::new("b2"); button.set_text("Click me"); button.set_on_click_fn(Box::new(move |this| { count.set(count.get()+1); this.set_text(format!("Clicked {}", count.get())); })); let mut button2 = mui::Button::new("b3"); button2.set_text("Click me"); butt...
{ let mut app = mui::App::new("Mui Widgets Demo!"); // primitives let rect = mui::Rect::new("r1", true); rect.set_zpos(3); app.add_widget(&rect); let count = Cell::new(0); let count2 = Cell::new(0); // sa - stand alone let mut sa_button = mui::Button::new("b1"); sa_button.s...
identifier_body
issue-15094.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 ...
(&self, _args: ()) { //~^ ERROR `call` has an incompatible type for trait: expected "rust-call" fn, found "Rust" fn println!("{}", self.x); } } fn make_shower<T>(x: T) -> Shower<T> { Shower { x: x } } pub fn main() { let show3 = make_shower(3i); show3(); }
call
identifier_name
issue-15094.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 show3 = make_shower(3i); show3(); }
identifier_body
issue-15094.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.
// except according to those terms. #![feature(unboxed_closures)] use std::{fmt, ops}; struct Shower<T> { x: T } impl<T: fmt::Show> ops::Fn<(), ()> for Shower<T> { fn call(&self, _args: ()) { //~^ ERROR `call` has an incompatible type for trait: expected "rust-call" fn, found "Rust" fn println!("{}"...
// // 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
random_line_split
issue-7663.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 fn my_main() { assert!(p() == 2); } } } mod test2 { mod foo { pub fn p() -> int { 1 } } mod bar { pub fn p() -> int { 2 } } pub mod baz { use test2::foo::p; //~ ERROR: unused import use test2::bar::p; pub fn my_main() { assert!(p() == 2); } } } mod test3 { ...
use test1::bar::*;
random_line_split
issue-7663.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 ...
} } mod test3 { mod foo { pub fn p() -> int { 1 } } mod bar { pub fn p() -> int { 2 } } pub mod baz { use test3::foo::*; //~ ERROR: unused import use test3::bar::p; pub fn my_main() { assert!(p() == 2); } } } fn main() { }
{ assert!(p() == 2); }
identifier_body
issue-7663.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 ...
() -> int { 2 } } pub mod baz { use test2::foo::p; //~ ERROR: unused import use test2::bar::p; pub fn my_main() { assert!(p() == 2); } } } mod test3 { mod foo { pub fn p() -> int { 1 } } mod bar { pub fn p() -> int { 2 } } pub mod baz { use test3::foo::*; //~ ERR...
p
identifier_name
parser_utils.rs
use std::collections::LinkedList; use std::iter::Iterator; use std::vec::Vec; use lexer::Token; use interpreter::ProgramStore; use interpreter::FunctionInfo; /// This function filters out comments and doubled newlines /// It also registers the functions with the program store pub fn filter_pass(tokens: Vec<Token>, m...
} else { return Err(format!("expected function name but found {:?}", next_token)); } } } // simply copy all other tokens _ => { output_tokens.push(token.clone()); tok_it.n...
program = try!(program.add_function(name.clone(), FunctionInfo::named_new(name)));
random_line_split
parser_utils.rs
use std::collections::LinkedList; use std::iter::Iterator; use std::vec::Vec; use lexer::Token; use interpreter::ProgramStore; use interpreter::FunctionInfo; /// This function filters out comments and doubled newlines /// It also registers the functions with the program store pub fn filter_pass(tokens: Vec<Token>, m...
(tokens: Vec<Token>) -> Result<LinkedList<Vec<Token>>, String> { let mut tok_it = tokens.into_iter(); let mut block = Vec::new(); let mut block_list = LinkedList::new(); while let Some(token) = tok_it.next() { match token { Token::Define => { if block.len()!= 0 && bl...
blockify_pass
identifier_name
parser_utils.rs
use std::collections::LinkedList; use std::iter::Iterator; use std::vec::Vec; use lexer::Token; use interpreter::ProgramStore; use interpreter::FunctionInfo; /// This function filters out comments and doubled newlines /// It also registers the functions with the program store pub fn filter_pass(tokens: Vec<Token>, m...
Ok(block_list) }
{ let mut tok_it = tokens.into_iter(); let mut block = Vec::new(); let mut block_list = LinkedList::new(); while let Some(token) = tok_it.next() { match token { Token::Define => { if block.len() != 0 && block[0] == Token::Define { block_list.push_...
identifier_body
parser_utils.rs
use std::collections::LinkedList; use std::iter::Iterator; use std::vec::Vec; use lexer::Token; use interpreter::ProgramStore; use interpreter::FunctionInfo; /// This function filters out comments and doubled newlines /// It also registers the functions with the program store pub fn filter_pass(tokens: Vec<Token>, m...
_ => {} } block.push(token); } // Add last block to block list block_list.push_back(block); Ok(block_list) }
{ if block.len() != 0 && block[0] == Token::Define { block_list.push_back(block); } block = Vec::new(); }
conditional_block
errors.rs
use std::ffi::CStr; use libc; error_chain! { types { Error, ErrorKind, ResultExt, Result; } links {}
FromBytesWithNul(::std::ffi::FromBytesWithNulError); IntoString(::std::ffi::IntoStringError); Utf8(::std::str::Utf8Error); IO(::std::io::Error); } errors { Rados(e: u32) { description("RADOS error") display("RADOS error code {}: `{}`", e, get_erro...
foreign_links { Nul(::ffi_pool::NulError); NulStd(::std::ffi::NulError);
random_line_split
errors.rs
use std::ffi::CStr; use libc; error_chain! { types { Error, ErrorKind, ResultExt, Result; } links {} foreign_links { Nul(::ffi_pool::NulError); NulStd(::std::ffi::NulError); FromBytesWithNul(::std::ffi::FromBytesWithNulError); IntoString(::std::ffi::IntoString...
else { Ok(()) } } /// Convert the integer output of a librados API function into a `Result<u32>`, returning the error /// value casted to a `u32` if it's positive and returning `Err` otherwise. pub fn librados_res(err: i32) -> Result<u32> { if err < 0 { bail!(ErrorKind::Rados(-err as u32)); ...
{ bail!(ErrorKind::Rados(-err as u32)); }
conditional_block
errors.rs
use std::ffi::CStr; use libc; error_chain! { types { Error, ErrorKind, ResultExt, Result; } links {} foreign_links { Nul(::ffi_pool::NulError); NulStd(::std::ffi::NulError); FromBytesWithNul(::std::ffi::FromBytesWithNulError); IntoString(::std::ffi::IntoString...
{ let error = unsafe { let err_str = libc::strerror(err as i32); try!( CStr::from_ptr(err_str) .to_str() .chain_err(|| "while decoding error string",) ) }; Ok(error.to_string()) }
identifier_body
errors.rs
use std::ffi::CStr; use libc; error_chain! { types { Error, ErrorKind, ResultExt, Result; } links {} foreign_links { Nul(::ffi_pool::NulError); NulStd(::std::ffi::NulError); FromBytesWithNul(::std::ffi::FromBytesWithNulError); IntoString(::std::ffi::IntoString...
(err: i32) -> Result<u32> { if err < 0 { bail!(ErrorKind::Rados(-err as u32)); } else { Ok(err as u32) } } /// Get the registered error string for a given error number. pub fn get_error_string(err: u32) -> Result<String> { let error = unsafe { let err_str = libc::strerror(err as...
librados_res
identifier_name
fill.rs
use lyon::tessellation::FillOptions; /// Nodes that support fill tessellation. /// /// This trait allows the `Drawing` context to automatically provide an implementation of the /// following builder methods for all primitives that provide some fill tessellation options. pub trait SetFill: Sized { /// Provide a mut...
} impl SetFill for Option<FillOptions> { fn fill_options_mut(&mut self) -> &mut FillOptions { self.get_or_insert_with(Default::default) } }
{ self.fill_options_mut().handle_intersections = handle; self }
identifier_body