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 |
|---|---|---|---|---|
router.rs | use std::collections::HashMap;
use futures::sync::mpsc::{unbounded, UnboundedSender, UnboundedReceiver};
use tokio::net::TcpStream;
use protobuf_codec::MessageStream;
use protocol;
pub enum RoutingMessage {
Connecting {
stream: MessageStream<TcpStream, protocol::Packet>,
},
}
pub struct RoutingTable ... | let (tx, rx) = unbounded();
self.routing_channels.insert(token.to_vec(), tx);
return rx;
}
pub fn get(&mut self, token: &[u8]) -> Option<UnboundedSender<RoutingMessage>> {
self.routing_channels.get(token).cloned()
}
pub fn remove(&mut self, token: &[u8]) {
self.... | routing_channels: HashMap::new(),
}
}
pub fn register(&mut self, token: &[u8]) -> UnboundedReceiver<RoutingMessage> { | random_line_split |
router.rs | use std::collections::HashMap;
use futures::sync::mpsc::{unbounded, UnboundedSender, UnboundedReceiver};
use tokio::net::TcpStream;
use protobuf_codec::MessageStream;
use protocol;
pub enum RoutingMessage {
Connecting {
stream: MessageStream<TcpStream, protocol::Packet>,
},
}
pub struct RoutingTable ... | (&mut self, token: &[u8]) -> UnboundedReceiver<RoutingMessage> {
let (tx, rx) = unbounded();
self.routing_channels.insert(token.to_vec(), tx);
return rx;
}
pub fn get(&mut self, token: &[u8]) -> Option<UnboundedSender<RoutingMessage>> {
self.routing_channels.get(token).cloned()
... | register | identifier_name |
switch.rs | use arch;
use core::sync::atomic::Ordering;
use context::{contexts, Context, Status, CONTEXT_ID};
/// Switch to the next context.
pub unsafe fn switch() -> bool {
use core::ops::DerefMut;
// Set the global lock to avoid the unsafe operations below from causing issues
while arch::context::CONTEXT_SWITCH_L... |
}
}
}
// whether there is no contexts to switch to, we remove the lock and return false
if to_ptr as usize == 0 {
arch::context::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst);
return false;
}
// mark the prev context as stopped
(&mut *from_ptr).running... | {
to_ptr = context.deref_mut() as *mut Context;
} | conditional_block |
switch.rs | use arch;
use core::sync::atomic::Ordering;
use context::{contexts, Context, Status, CONTEXT_ID};
/// Switch to the next context.
pub unsafe fn | () -> bool {
use core::ops::DerefMut;
// Set the global lock to avoid the unsafe operations below from causing issues
while arch::context::CONTEXT_SWITCH_LOCK.compare_and_swap(false, true, Ordering::SeqCst) {
arch::interrupts::pause();
}
// get current CPU id
let cpu_id = ::cpu_id();
... | switch | identifier_name |
switch.rs | use arch;
use core::sync::atomic::Ordering;
use context::{contexts, Context, Status, CONTEXT_ID};
/// Switch to the next context.
pub unsafe fn switch() -> bool | let mut context = context_lock.write();
from_ptr = context.deref_mut() as *mut Context;
}
let check_context = |context: &mut Context| -> bool {
// Set the CPU id on the context if none specified
if context.cpu_id == None && cpu_id == 0 {
c... | {
use core::ops::DerefMut;
// Set the global lock to avoid the unsafe operations below from causing issues
while arch::context::CONTEXT_SWITCH_LOCK.compare_and_swap(false, true, Ordering::SeqCst) {
arch::interrupts::pause();
}
// get current CPU id
let cpu_id = ::cpu_id();
let fro... | identifier_body |
switch.rs | use arch;
use core::sync::atomic::Ordering;
use context::{contexts, Context, Status, CONTEXT_ID};
/// Switch to the next context.
pub unsafe fn switch() -> bool {
use core::ops::DerefMut;
// Set the global lock to avoid the unsafe operations below from causing issues
while arch::context::CONTEXT_SWITCH_L... | from_ptr = context.deref_mut() as *mut Context;
}
let check_context = |context: &mut Context| -> bool {
// Set the CPU id on the context if none specified
if context.cpu_id == None && cpu_id == 0 {
context.cpu_id = Some(cpu_id);
}
... | // get the current context
{
let context_lock = contexts.current().expect("context::switch: not inside of context");
let mut context = context_lock.write(); | random_line_split |
example.rs | extern mod extra;
use extra::sort;
use std::hashmap::HashMap;
struct School {
priv grades: HashMap<uint, ~[~str]>
}
fn sorted<T: Clone + Ord>(array: &[T]) -> ~[T] {
let mut res = array.iter().map(|v| v.clone()).to_owned_vec();
sort::tim_sort(res);
res
}
impl School {
pub fn new() -> School { | pub fn add(self, grade: uint, student: &str) -> School {
let mut s = self;
s.grades.mangle(
grade,
student,
|_, x| ~[x.into_owned()],
|_, xs, x| xs.push(x.into_owned()));
s
}
pub fn sorted(self) -> ~[(uint, ~[~str])] {
sorted(s... | School { grades: HashMap::new() }
}
| random_line_split |
example.rs | extern mod extra;
use extra::sort;
use std::hashmap::HashMap;
struct School {
priv grades: HashMap<uint, ~[~str]>
}
fn sorted<T: Clone + Ord>(array: &[T]) -> ~[T] {
let mut res = array.iter().map(|v| v.clone()).to_owned_vec();
sort::tim_sort(res);
res
}
impl School {
pub fn new() -> School {
... | (self, grade: uint) -> ~[~str] {
self.grades.find(&grade).map(|&v| sorted(v.to_owned())).unwrap_or(~[])
}
}
| grade | identifier_name |
example.rs | extern mod extra;
use extra::sort;
use std::hashmap::HashMap;
struct School {
priv grades: HashMap<uint, ~[~str]>
}
fn sorted<T: Clone + Ord>(array: &[T]) -> ~[T] {
let mut res = array.iter().map(|v| v.clone()).to_owned_vec();
sort::tim_sort(res);
res
}
impl School {
pub fn new() -> School {
... |
pub fn sorted(self) -> ~[(uint, ~[~str])] {
sorted(self.grades.iter().map(|(&grade, students)| {
(grade, sorted(students.clone()))
}).to_owned_vec())
}
pub fn grade(self, grade: uint) -> ~[~str] {
self.grades.find(&grade).map(|&v| sorted(v.to_owned())).unwrap_or(~[])
... | {
let mut s = self;
s.grades.mangle(
grade,
student,
|_, x| ~[x.into_owned()],
|_, xs, x| xs.push(x.into_owned()));
s
} | identifier_body |
pic.rs | /*
* 8259A PIC interface
*
* TODO: some code here is common with PIC implementation in xvm
* make some common definition crate if possible
*/
use arch;
use pio::{inb, outb};
const PIC_MASTER_CMD: u16 = 0x20;
const PIC_MASTER_DATA: u16 = 0x21;
const PIC_SLAVE_CMD: u16 = 0xA0;
const PIC_SLAVE_DATA: u16 = 0xA... | unsafe {
outb(PIC_MASTER_CMD, PIC_READ_ISR);
outb(PIC_SLAVE_CMD, PIC_READ_ISR);
make_arg(inb(PIC_MASTER_CMD), inb(PIC_SLAVE_CMD))
}
}
/**
* Read IRR registers
*/
pub fn IRR() -> u16
{
unsafe {
outb(PIC_MASTER_CMD, PIC_READ_IRR);
outb(PIC_SLAVE_CMD, PIC_READ_IRR);
... | /**
* Read ISR registers
*/
pub fn ISR() -> u16
{ | random_line_split |
pic.rs | /*
* 8259A PIC interface
*
* TODO: some code here is common with PIC implementation in xvm
* make some common definition crate if possible
*/
use arch;
use pio::{inb, outb};
const PIC_MASTER_CMD: u16 = 0x20;
const PIC_MASTER_DATA: u16 = 0x21;
const PIC_SLAVE_CMD: u16 = 0xA0;
const PIC_SLAVE_DATA: u16 = 0xA... | () -> u16
{
unsafe {
outb(PIC_MASTER_CMD, PIC_READ_ISR);
outb(PIC_SLAVE_CMD, PIC_READ_ISR);
make_arg(inb(PIC_MASTER_CMD), inb(PIC_SLAVE_CMD))
}
}
/**
* Read IRR registers
*/
pub fn IRR() -> u16
{
unsafe {
outb(PIC_MASTER_CMD, PIC_READ_IRR);
outb(PIC_SLAVE_CMD, PIC_... | ISR | identifier_name |
pic.rs | /*
* 8259A PIC interface
*
* TODO: some code here is common with PIC implementation in xvm
* make some common definition crate if possible
*/
use arch;
use pio::{inb, outb};
const PIC_MASTER_CMD: u16 = 0x20;
const PIC_MASTER_DATA: u16 = 0x21;
const PIC_SLAVE_CMD: u16 = 0xA0;
const PIC_SLAVE_DATA: u16 = 0xA... |
pub fn slave_offset() -> u8
{
slave_arg(offset())
}
// TODO: move to common utils code
fn set_bit8(val: u8, bit: u8) -> u8 {
assert!(bit < 8);
val | (1_u8 << bit)
}
// TODO: move to common utils code
fn clear_bit8(val: u8, bit: u8) -> u8 {
assert!(bit < 8);
val &!(1_u8 << bit)
}
/**
* For a gi... | {
master_arg(offset())
} | identifier_body |
pic.rs | /*
* 8259A PIC interface
*
* TODO: some code here is common with PIC implementation in xvm
* make some common definition crate if possible
*/
use arch;
use pio::{inb, outb};
const PIC_MASTER_CMD: u16 = 0x20;
const PIC_MASTER_DATA: u16 = 0x21;
const PIC_SLAVE_CMD: u16 = 0xA0;
const PIC_SLAVE_DATA: u16 = 0xA... |
}
/**
* Mask or unmask and IRQ given its interrupt vector
*/
pub fn mask_vector(vec: u8, is_masked: bool)
{
let mask = mask();
let mut master = master_arg(mask);
let mut slave = slave_arg(mask);
if vec >= master_offset() && vec < (master_offset() + 8) {
if is_masked {
m... | {
panic!()
} | conditional_block |
lib.rs | use std::str::FromStr;
#[macro_use]
extern crate nom;
use std::collections::HashMap;
| pub struct Config {
map: HashMap<String, String>,
}
impl Config {
pub fn get(&self, property_name: &str) -> Option<&str> {
self.map.get(property_name).map(|s| s.as_str())
}
fn from_lines(lines: Vec<Line>) -> Config {
let mut map = HashMap::new();
for line in lines {
... | mod parser;
use parser::{get_lines, Line};
pub use parser::ParseError;
#[derive(Debug)] | random_line_split |
lib.rs | use std::str::FromStr;
#[macro_use]
extern crate nom;
use std::collections::HashMap;
mod parser;
use parser::{get_lines, Line};
pub use parser::ParseError;
#[derive(Debug)]
pub struct Config {
map: HashMap<String, String>,
}
impl Config {
pub fn get(&self, property_name: &str) -> Option<&str> {
sel... |
#[test]
fn missing_key_value() {
let config = Config::from_lines(vec![Line::KeyValue("hostname".to_string(),
"dynamo".to_string())]);
assert_eq!(config.get("port"), None);
}
#[test]
fn many_key_values() {
let conf... | {
let config = Config::from_lines(vec![Line::KeyValue("hostname".to_string(),
"dynamo".to_string())]);
assert_eq!(config.get("hostname"), Some("dynamo"));
} | identifier_body |
lib.rs | use std::str::FromStr;
#[macro_use]
extern crate nom;
use std::collections::HashMap;
mod parser;
use parser::{get_lines, Line};
pub use parser::ParseError;
#[derive(Debug)]
pub struct Config {
map: HashMap<String, String>,
}
impl Config {
pub fn get(&self, property_name: &str) -> Option<&str> {
sel... |
Line::Comment(_) => {}
};
}
Config { map: map }
}
}
impl FromStr for Config {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let lines = try!(get_lines(s));
Ok(Config::from_lines(lines))
}
}
#[cfg(test)]
mod tests ... | {
map.insert(key, value);
} | conditional_block |
lib.rs | use std::str::FromStr;
#[macro_use]
extern crate nom;
use std::collections::HashMap;
mod parser;
use parser::{get_lines, Line};
pub use parser::ParseError;
#[derive(Debug)]
pub struct Config {
map: HashMap<String, String>,
}
impl Config {
pub fn get(&self, property_name: &str) -> Option<&str> {
sel... | () {
let config = Config::from_lines(vec![Line::KeyValue("hostname".to_string(),
"dynamo".to_string())]);
assert_eq!(config.get("port"), None);
}
#[test]
fn many_key_values() {
let config =
Config::from_lines(ve... | missing_key_value | identifier_name |
size_of.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use script::test::size_of;
// Macro so that we can stringify type names
// I'd really prefer the tests themselve... | }
});
);
// Update the sizes here
sizeof_checker!(size_event_target, EventTarget, 48);
sizeof_checker!(size_node, Node, 184);
sizeof_checker!(size_element, Element, 360);
sizeof_checker!(size_htmlelement, HTMLElement, 376);
sizeof_checker!(size_div, HTMLDivElement, 376);
sizeof_checker!(size_span, HTMLSpan... | update to the new size in tests/unit/script/size_of.rs.",
stringify!($t), old, new) | random_line_split |
mod.rs | use token;
use roolang_regex;
use common::ParseError as ParseError;
mod test;
#[derive(Clone)]
#[derive(PartialEq)]
pub enum Constant {
IntegerConst {value: i32},
BooleanConst {value: bool},
CharSeqConst {value: String},
DecimalConst {value: f64}
}
pub fn get_constant(tokens: &Vec<token::Token>, sta... |
fn as_decimal_number(tokens: &Vec<token::Token>, whole_number: String, start: usize, negative: bool) -> (Result<Constant, ParseError>, usize) {
let mut number = whole_number.clone();
number.push_str(".");
if tokens.len() < start {
return bad_token(&tokens[start], "Unexcpected end");
} else if... | {
let number = tokens[start].text.clone();
if tokens.len() > start + 1 && &tokens[start + 1].text == "." {
return as_decimal_number(&tokens, number, start + 2, negative);
}
let val = match number.parse::<i32>() {
Ok(n) => if negative {n * -1} else {n},
Err(_) => 0
};
... | identifier_body |
mod.rs | use token;
use roolang_regex;
use common::ParseError as ParseError;
mod test;
#[derive(Clone)]
#[derive(PartialEq)]
pub enum Constant {
IntegerConst {value: i32},
BooleanConst {value: bool},
CharSeqConst {value: String},
DecimalConst {value: f64}
}
pub fn get_constant(tokens: &Vec<token::Token>, sta... | (tokens: &Vec<token::Token>, start: usize) -> (Result<Constant, ParseError>, usize) {
return (Ok(Constant::BooleanConst {value: &tokens[start].text == "true"}), start + 1);
}
fn as_string(tokens: &Vec<token::Token>, start: usize) -> (Result<Constant, ParseError>, usize) {
let mut val = tokens[start].text.clone... | as_boolean | identifier_name |
mod.rs | use token;
use roolang_regex;
use common::ParseError as ParseError;
mod test;
#[derive(Clone)]
#[derive(PartialEq)]
pub enum Constant {
IntegerConst {value: i32},
BooleanConst {value: bool},
CharSeqConst {value: String},
DecimalConst {value: f64}
}
pub fn get_constant(tokens: &Vec<token::Token>, sta... |
fn as_string(tokens: &Vec<token::Token>, start: usize) -> (Result<Constant, ParseError>, usize) {
let mut val = tokens[start].text.clone();
val.remove(tokens[start].text.len() - 1);
val.remove(0);
return (Ok(Constant::CharSeqConst{value: val.clone()}), start + 1);
}
fn bad_token(token: &token::Token,... | return (Ok(Constant::BooleanConst {value: &tokens[start].text == "true"}), start + 1);
} | random_line_split |
mod.rs | use token;
use roolang_regex;
use common::ParseError as ParseError;
mod test;
#[derive(Clone)]
#[derive(PartialEq)]
pub enum Constant {
IntegerConst {value: i32},
BooleanConst {value: bool},
CharSeqConst {value: String},
DecimalConst {value: f64}
}
pub fn get_constant(tokens: &Vec<token::Token>, sta... | else {n},
Err(_) => 0.0
};
return (Ok(Constant::DecimalConst {value: val}), start + 1)
}
fn as_boolean(tokens: &Vec<token::Token>, start: usize) -> (Result<Constant, ParseError>, usize) {
return (Ok(Constant::BooleanConst {value: &tokens[start].text == "true"}), start + 1);
}
fn as_string(tokens... | {n * -1.0} | conditional_block |
gpushadermodule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::GPUShaderModuleBinding::... | (&self, value: Option<DOMString>) {
*self.label.borrow_mut() = value;
}
}
| SetLabel | identifier_name |
gpushadermodule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::GPUShaderModuleBinding::... | pub fn id(&self) -> WebGPUShaderModule {
self.shader_module
}
}
impl GPUShaderModuleMethods for GPUShaderModule {
/// https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label
fn GetLabel(&self) -> Option<DOMString> {
self.label.borrow().clone()
}
/// https://gpuweb.github.io/gp... | )
}
}
impl GPUShaderModule { | random_line_split |
iterator.rs | use crate::ops::{Decrement, Increment, Indirection};
use crate::{CppBox, CppDeletable, Ref};
use std::os::raw::c_char;
/// `Iterator` and `DoubleEndedIterator` backed by C++ iterators.
///
/// This object is produced by `IntoIterator` implementations on pointer types
/// (`&CppBox`, `&mut CppBox`, `Ptr`, `Ref`). You ... | (&self) -> *const T {
unsafe { self.as_ptr().add(self.len()) }
}
}
impl<'a> EndPtr for &'a str {
type Item = c_char;
fn end_ptr(&self) -> *const c_char {
unsafe { self.as_ptr().add(self.len()) as *const c_char }
}
}
| end_ptr | identifier_name |
iterator.rs | use crate::ops::{Decrement, Increment, Indirection};
use crate::{CppBox, CppDeletable, Ref};
use std::os::raw::c_char;
/// `Iterator` and `DoubleEndedIterator` backed by C++ iterators.
///
/// This object is produced by `IntoIterator` implementations on pointer types
/// (`&CppBox`, `&mut CppBox`, `Ptr`, `Ref`). You ... |
}
}
}
/// A convenience trait that provides `end_ptr()` method for slices.
pub trait EndPtr {
/// Type of item.
type Item;
/// Returns pointer to the end of the slice (past the last element).
fn end_ptr(&self) -> *const Self::Item;
}
impl<'a, T> EndPtr for &'a [T] {
type Item = T;
... | {
let inner = &mut *self.end.as_mut_raw_ptr();
inner.dec();
let inner = &mut *self.end.as_mut_raw_ptr();
let value = inner.indirection();
Some(value)
} | conditional_block |
iterator.rs | use crate::ops::{Decrement, Increment, Indirection};
use crate::{CppBox, CppDeletable, Ref};
use std::os::raw::c_char;
/// `Iterator` and `DoubleEndedIterator` backed by C++ iterators.
///
/// This object is produced by `IntoIterator` implementations on pointer types
/// (`&CppBox`, `&mut CppBox`, `Ptr`, `Ref`). You ... | unsafe {
if self.begin == self.end.as_ref() {
None
} else {
let inner = &mut *self.end.as_mut_raw_ptr();
inner.dec();
let inner = &mut *self.end.as_mut_raw_ptr();
let value = inner.indirection();
... | fn next_back(&mut self) -> Option<Self::Item> { | random_line_split |
iterator.rs | use crate::ops::{Decrement, Increment, Indirection};
use crate::{CppBox, CppDeletable, Ref};
use std::os::raw::c_char;
/// `Iterator` and `DoubleEndedIterator` backed by C++ iterators.
///
/// This object is produced by `IntoIterator` implementations on pointer types
/// (`&CppBox`, `&mut CppBox`, `Ptr`, `Ref`). You ... |
impl<T1, T2> Iterator for CppIterator<T1, T2>
where
T1: CppDeletable + PartialEq<Ref<T2>> + Indirection + Increment,
T2: CppDeletable,
{
type Item = <T1 as Indirection>::Output;
fn next(&mut self) -> Option<Self::Item> {
unsafe {
if self.begin == self.end.as_ref() {
... | {
CppIterator { begin, end }
} | identifier_body |
shootout-pfib.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 ... | {
stress: bool
}
fn parse_opts(argv: Vec<String> ) -> Config {
let opts = vec!(getopts::optflag("", "stress", ""));
let argv = argv.iter().map(|x| x.to_string()).collect::<Vec<_>>();
let opt_args = argv.slice(1, argv.len());
match getopts::getopts(opt_args, opts.as_slice()) {
Ok(ref m) => ... | Config | identifier_name |
shootout-pfib.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 main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_string(), "20".to_string())
} else if args.len() <= 1u {
vec!("".to_string(), "8".to_string())
} else {
args.move_iter().map(|x| x.to_string()).collect()
};
let opts = pars... | {
let mut results = Vec::new();
for i in range(0, num_tasks) {
results.push(task::try_future(proc() {
stress_task(i);
}));
}
for r in results.move_iter() {
r.unwrap();
}
} | identifier_body |
shootout-pfib.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 ... |
Err(_) => { fail!(); }
}
}
fn stress_task(id: int) {
let mut i = 0i;
loop {
let n = 15i;
assert_eq!(fib(n), fib(n));
i += 1;
println!("{}: Completed {} iterations", id, i);
}
}
fn stress(num_tasks: int) {
let mut results = Vec::new();
for i in range(0, nu... | {
return Config {stress: m.opt_present("stress")}
} | conditional_block |
shootout-pfib.rs | // 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 http://opensource.org/licenses/MIT>, at your
// option. This file... | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | random_line_split | |
fussy.rs | extern crate fuss;
use self::fuss::Simplex;
use core::world::dungeon::builder::Buildable;
use core::world::dungeon::map;
use core::world::dungeon::map::Measurable;
///
/// Builder for generating noise maps
///
pub struct Fussy {
pub grid: map::Grid<u8>,
pub w: usize,
pub h: usize,
pub noise: Simplex,
pub t... | if self.noise.sum_octave_2d(16, x as f32, y as f32, 0.5, 0.007) + 1.0 > self.threshold {
self.grid[x][y] = 1;
}
}
}
}
///
/// Return a new `Fussy`
///
pub fn new(grid: map::Grid<u8>, threshold: f32) -> Self {
// Make a new dungeon with our fresh grid of size `w` by `... | random_line_split | |
fussy.rs | extern crate fuss;
use self::fuss::Simplex;
use core::world::dungeon::builder::Buildable;
use core::world::dungeon::map;
use core::world::dungeon::map::Measurable;
///
/// Builder for generating noise maps
///
pub struct Fussy {
pub grid: map::Grid<u8>,
pub w: usize,
pub h: usize,
pub noise: Simplex,
pub t... | (grid: map::Grid<u8>, threshold: f32) -> Self {
// Make a new dungeon with our fresh grid of size `w` by `h`
let fussy = Fussy {
grid: grid.clone(),
w: grid.width(),
h: grid.height(),
noise: Simplex::new(),
threshold
};
return fussy;
}
}
impl Buildable for Fussy {... | new | identifier_name |
fussy.rs | extern crate fuss;
use self::fuss::Simplex;
use core::world::dungeon::builder::Buildable;
use core::world::dungeon::map;
use core::world::dungeon::map::Measurable;
///
/// Builder for generating noise maps
///
pub struct Fussy {
pub grid: map::Grid<u8>,
pub w: usize,
pub h: usize,
pub noise: Simplex,
pub t... |
}
impl Buildable for Fussy {
type Output = u8;
fn build(&mut self) -> map::Grid<u8> {
self.add_noise();
return self.grid.clone();
}
} | {
// Make a new dungeon with our fresh grid of size `w` by `h`
let fussy = Fussy {
grid: grid.clone(),
w: grid.width(),
h: grid.height(),
noise: Simplex::new(),
threshold
};
return fussy;
} | identifier_body |
fussy.rs | extern crate fuss;
use self::fuss::Simplex;
use core::world::dungeon::builder::Buildable;
use core::world::dungeon::map;
use core::world::dungeon::map::Measurable;
///
/// Builder for generating noise maps
///
pub struct Fussy {
pub grid: map::Grid<u8>,
pub w: usize,
pub h: usize,
pub noise: Simplex,
pub t... |
}
}
}
///
/// Return a new `Fussy`
///
pub fn new(grid: map::Grid<u8>, threshold: f32) -> Self {
// Make a new dungeon with our fresh grid of size `w` by `h`
let fussy = Fussy {
grid: grid.clone(),
w: grid.width(),
h: grid.height(),
noise: Simplex::new(),
... | {
self.grid[x][y] = 1;
} | conditional_block |
font.rs | First round out to pixel boundaries
// CG Origin is bottom left
let mut left = bounds.origin.x.floor() as i32;
let mut bottom = bounds.origin.y.floor() as i32;
let mut right = (bounds.origin.x + bounds.size.width + x_offset).ceil() as i32;
let mut top = (bounds.origin.y + bounds.size.height + y_off... | let rb = if should_use_white_on_black(font.color) { 255 } else { 0 };
ColorU::new(rb, g, rb, a)
} else {
ColorU::new(255, 255, 255, 255)
};
}
FontRenderMode::Subpixel => {
// Quantization ... | font.color = if font.flags.contains(FontInstanceFlags::FONT_SMOOTHING) {
// Only the G channel is used to index grayscale tables,
// so use R and B to preserve light/dark determination.
let ColorU { g, a, .. } = font.color.luminance_color().qua... | random_line_split |
font.rs | () -> bool {
let mut cg_context = CGContext::create_bitmap_context(
None,
1,
1,
8,
4,
&CGColorSpace::create_device_rgb(),
kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little,
);
let ct_font = core_text::font::new_from_name("Helvetica", 16.).unwrap(... | supports_subpixel_aa | identifier_name | |
font.rs | round out to pixel boundaries
// CG Origin is bottom left
let mut left = bounds.origin.x.floor() as i32;
let mut bottom = bounds.origin.y.floor() as i32;
let mut right = (bounds.origin.x + bounds.size.width + x_offset).ceil() as i32;
let mut top = (bounds.origin.y + bounds.size.height + y_offset).c... |
fn get_ct_font(
&mut self,
font_key: FontKey,
size: Au,
variations: &[FontVariation],
) -> Option<CTFont> {
match self.ct_fonts.entry((font_key, size, variations.to_vec())) {
Entry::Occupied(entry) => Some((*entry.get()).clone()),
Entry::Vacant(e... | {
if let Some(_) = self.cg_fonts.remove(font_key) {
self.ct_fonts.retain(|k, _| k.0 != *font_key);
}
} | identifier_body |
font.rs | round out to pixel boundaries
// CG Origin is bottom left
let mut left = bounds.origin.x.floor() as i32;
let mut bottom = bounds.origin.y.floor() as i32;
let mut right = (bounds.origin.x + bounds.size.width + x_offset).ceil() as i32;
let mut top = (bounds.origin.y + bounds.size.height + y_offset).c... |
None => return ct_font,
};
let mut val = match variations.iter().find(|variation| (variation.tag as i64) == tag_val) {
Some(variation) => variation.value as f64,
None => continue,
};
let name: CFString = match axis.find(kC... | {
let tag: CFNumber = TCFType::wrap_under_get_rule(tag_ptr as CFNumberRef);
if !tag.instance_of::<CFNumber>() {
return ct_font;
}
match tag.to_i64() {
Some(val) => val,
... | conditional_block |
options.rs | use std::str::FromStr;
use crate::params_style::ParamStyle;
use crate::rpc_attr::path_eq_str;
const CLIENT_META_WORD: &str = "client";
const SERVER_META_WORD: &str = "server";
const PARAMS_META_KEY: &str = "params";
#[derive(Debug)]
pub struct DeriveOptions {
pub enable_client: bool,
pub enable_server: bool,
pub ... | syn::Meta::NameValue(nv) => {
if path_eq_str(&nv.path, PARAMS_META_KEY) {
if let syn::Lit::Str(ref lit) = nv.lit {
options.params_style = ParamStyle::from_str(&lit.value())
.map_err(|e| syn::Error::new_spanned(nv.clone(), e))?;
}
} else {
return Err(syn::Error::new... | {
let mut options = DeriveOptions::new(false, false, ParamStyle::default());
for arg in args {
if let syn::NestedMeta::Meta(meta) = arg {
match meta {
syn::Meta::Path(ref p) => {
match p
.get_ident()
.ok_or(syn::Error::new_spanned(
p,
format!("Expecting identifier `{}... | identifier_body |
options.rs | use std::str::FromStr;
use crate::params_style::ParamStyle;
use crate::rpc_attr::path_eq_str;
const CLIENT_META_WORD: &str = "client";
const SERVER_META_WORD: &str = "server";
const PARAMS_META_KEY: &str = "params";
#[derive(Debug)]
pub struct DeriveOptions {
pub enable_client: bool,
pub enable_server: bool,
pub ... | }
_ => return Err(syn::Error::new_spanned(meta, "Unexpected use of RPC attribute macro")),
}
}
}
if!options.enable_client &&!options.enable_server {
// if nothing provided default to both
options.enable_client = true;
options.enable_server = true;
}
if options.enable_server && options.... | }
} else {
return Err(syn::Error::new_spanned(nv, "Unexpected RPC attribute key"));
} | random_line_split |
options.rs | use std::str::FromStr;
use crate::params_style::ParamStyle;
use crate::rpc_attr::path_eq_str;
const CLIENT_META_WORD: &str = "client";
const SERVER_META_WORD: &str = "server";
const PARAMS_META_KEY: &str = "params";
#[derive(Debug)]
pub struct DeriveOptions {
pub enable_client: bool,
pub enable_server: bool,
pub ... |
if options.enable_server && options.params_style == ParamStyle::Named {
// This is not allowed at this time
panic!("Server code generation only supports `params = \"positional\"` (default) or `params = \"raw\" at this time.")
}
Ok(options)
}
}
| {
// if nothing provided default to both
options.enable_client = true;
options.enable_server = true;
} | conditional_block |
options.rs | use std::str::FromStr;
use crate::params_style::ParamStyle;
use crate::rpc_attr::path_eq_str;
const CLIENT_META_WORD: &str = "client";
const SERVER_META_WORD: &str = "server";
const PARAMS_META_KEY: &str = "params";
#[derive(Debug)]
pub struct DeriveOptions {
pub enable_client: bool,
pub enable_server: bool,
pub ... | (enable_client: bool, enable_server: bool, params_style: ParamStyle) -> Self {
DeriveOptions {
enable_client,
enable_server,
params_style,
}
}
pub fn try_from(args: syn::AttributeArgs) -> Result<Self, syn::Error> {
let mut options = DeriveOptions::new(false, false, ParamStyle::default());
for arg in... | new | identifier_name |
module.rs | use crate::base::ModuleData;
use rustc_ast::ptr::P;
use rustc_ast::{token, Attribute, Inline, Item};
use rustc_errors::{struct_span_err, DiagnosticBuilder};
use rustc_parse::new_parser_from_file;
use rustc_parse::validate_attr;
use rustc_session::parse::ParseSess;
use rustc_session::Session;
use rustc_span::symbol::{sy... | {
pub items: Vec<P<Item>>,
pub inner_span: Span,
pub file_path: PathBuf,
pub dir_path: PathBuf,
pub dir_ownership: DirOwnership,
}
pub enum ModError<'a> {
CircularInclusion(Vec<PathBuf>),
ModInBlock(Option<Ident>),
FileNotFound(Ident, PathBuf, PathBuf),
MultipleCandidates(Ident, Pa... | ParsedExternalMod | identifier_name |
module.rs | use crate::base::ModuleData;
use rustc_ast::ptr::P;
use rustc_ast::{token, Attribute, Inline, Item};
use rustc_errors::{struct_span_err, DiagnosticBuilder};
use rustc_parse::new_parser_from_file;
use rustc_parse::validate_attr;
use rustc_session::parse::ParseSess;
use rustc_session::Session;
use rustc_span::symbol::{sy... | // Note that this will produce weirdness when a file named `foo.rs` is
// `#[path]` included and contains a `mod foo;` declaration.
// If you encounter this, it's your own darn fault :P
let dir_ownership = DirOwnership::Owned { relative: None };
return Ok(ModulePathSuccess { file... | // All `#[path]` files are treated as though they are a `mod.rs` file.
// This means that `mod foo;` declarations inside `#[path]`-included
// files are siblings,
// | random_line_split |
fields.rs | //! Defines the fields used in the query result structs
// don't show deprecation warnings about NewField when we build this file
#![allow(deprecated)]
use crate::prelude::*;
use serde::Deserialize;
use std::path::PathBuf;
/// This trait is used to furnish the caller with the watchman
/// field name for an entry in ... | "uid"
);
define_field!(
/// The field corresponding to the `gid` field.
/// The gid field is the owning gid expressed as an integer.
/// This field is not meaningful on Windows.
OwnerGidField,
u32,
"gid"
);
define_field!(
/// The field corresponding to the `ino` field.
/// The ino ... | /// The field corresponding to the `uid` field.
/// The uid field is the owning uid expressed as an integer.
/// This field is not meaningful on Windows.
OwnerUidField,
u32, | random_line_split |
fields.rs | //! Defines the fields used in the query result structs
// don't show deprecation warnings about NewField when we build this file
#![allow(deprecated)]
use crate::prelude::*;
use serde::Deserialize;
use std::path::PathBuf;
/// This trait is used to furnish the caller with the watchman
/// field name for an entry in ... | {
pub name: NameField,
}
impl QueryFieldList for NameOnly {
fn field_list() -> Vec<&'static str> {
vec!["name"]
}
}
impl From<PathBuf> for NameOnly {
fn from(path: PathBuf) -> Self {
Self {
name: NameField { val: path },
}
}
}
| NameOnly | identifier_name |
fields.rs | //! Defines the fields used in the query result structs
// don't show deprecation warnings about NewField when we build this file
#![allow(deprecated)]
use crate::prelude::*;
use serde::Deserialize;
use std::path::PathBuf;
/// This trait is used to furnish the caller with the watchman
/// field name for an entry in ... |
}
| {
Self {
name: NameField { val: path },
}
} | identifier_body |
view.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... | (&mut self) {
for (kind, value) in self.core.drain_queue() {
if kind == 0 {
self.show_columns = value!= 0;
} else if kind == 1 && value >= 0 {
self.columns
.set_hilight_color(value as usize, (255, 128, 255));
} else if kind =... | drain_queue | identifier_name |
view.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... |
}
action.merge(subaction.but_no_value());
}
if!action.should_stop() {
self.core.begin_character_scene_on_click(event);
}
action
}
}
impl PuzzleView for View {
fn info_text(&self, game: &Game) -> &'static str {
if game.whatcha_column.i... | {
self.core.push_undo((col, by));
} | conditional_block |
view.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... | }
self.core.draw_middle_layer(canvas);
self.core.draw_front_layer(canvas, state);
}
fn handle_event(
&mut self,
event: &Event,
game: &mut Game,
) -> Action<PuzzleCmd> {
let state = &mut game.whatcha_column;
let mut action = self.core.handle_ev... | random_line_split | |
view.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... |
fn solve(&mut self, game: &mut Game) {
self.columns.clear_drag();
game.whatcha_column.solve();
self.core.begin_outro_scene();
}
fn drain_queue(&mut self) {
for (kind, value) in self.core.drain_queue() {
if kind == 0 {
self.show_columns = value!=... | {
self.columns.clear_drag();
self.core.clear_undo_redo();
game.whatcha_column.reset();
} | identifier_body |
multidispatch2.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 ... |
trait MyTrait<T> {
fn get(&self) -> T;
}
impl<T> MyTrait<T> for T
where T : Default
{
fn get(&self) -> T {
Default::default()
}
}
#[derive(Copy)]
struct MyType {
dummy: uint
}
impl MyTrait<uint> for MyType {
fn get(&self) -> uint { self.dummy }
}
fn test_eq<T,M>(m: M, v: T)
where T ... | use std::default::Default; | random_line_split |
multidispatch2.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 ... | <T,M>(m: M, v: T)
where T : Eq + Debug,
M : MyTrait<T>
{
assert_eq!(m.get(), v);
}
pub fn main() {
test_eq(22_usize, 0_usize);
let value = MyType { dummy: 256 + 22 };
test_eq(value, value.dummy);
}
| test_eq | identifier_name |
color_button.rs | // Copyright 2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ColorButton;
use Widget;
use ffi;
use gdk;
use glib::object::Downcast;
use glib::translate::*;... |
pub fn new_with_rgba(rgba: &gdk::RGBA) -> ColorButton {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_color_button_new_with_rgba(rgba)).downcast_unchecked()
}
}
pub fn get_color(&self) -> gdk::Color {
unsafe {
let mut c... | {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_color_button_new_with_color(color)).downcast_unchecked()
}
} | identifier_body |
color_button.rs | // Copyright 2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ColorButton;
use Widget;
use ffi;
use gdk;
use glib::object::Downcast;
use glib::translate::*;... | (rgba: &gdk::RGBA) -> ColorButton {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_color_button_new_with_rgba(rgba)).downcast_unchecked()
}
}
pub fn get_color(&self) -> gdk::Color {
unsafe {
let mut color = mem::uninitialized(... | new_with_rgba | identifier_name |
color_button.rs | // Copyright 2016, The Gtk-rs Project Developers. | // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ColorButton;
use Widget;
use ffi;
use gdk;
use glib::object::Downcast;
use glib::translate::*;
use std::mem;
impl ColorButton {
pub fn new_with_color(color: &gdk::Color) -> ColorButton {
assert_initialized_... | // See the COPYRIGHT file at the top-level directory of this distribution. | random_line_split |
net.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn accept(&self, storage: *mut libc::sockaddr,
len: *mut libc::socklen_t) -> io::Result<Socket> {
match unsafe { libc::accept(self.0, storage, len) } {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
}
pub fn duplicate(&self) -> io:... | {
let fam = match *addr {
SocketAddr::V4(..) => libc::AF_INET,
SocketAddr::V6(..) => libc::AF_INET6,
};
match unsafe { libc::socket(fam, ty, 0) } {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
} | identifier_body |
net.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
impl Socket {
pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
let fam = match *addr {
SocketAddr::V4(..) => libc::AF_INET,
SocketAddr::V6(..) => libc::AF_INET6,
};
match unsafe { libc::socket(fam, ty, 0) } {
INVALID_SOCKET => Err(last_err... | cvt(f())
} | random_line_split |
net.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (err: c_int) -> io::Result<()> {
if err == 0 { return Ok(()) }
cvt(err).map(|_| ())
}
/// Provides the functionality of `cvt` for a closure.
#[allow(deprecated)]
pub fn cvt_r<T: SignedInt, F>(mut f: F) -> io::Result<T> where F: FnMut() -> T {
cvt(f())
}
impl Socket {
pub fn new(addr: &SocketAddr, ty: ... | cvt_gai | identifier_name |
from_bits.rs | use itertools::Itertools;
use malachite_base::num::basic::traits::Zero;
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::num::logic::traits::BitAccess;
use malachite_nz::natural::Natural;
pub fn from_bits_asc_naive<I: Iterator<Item = bool>>(bits: I) -> Natural {
let mut n = Natural::ZERO... | {
let bits = bits.collect_vec();
let mut n = Natural::ZERO;
for i in bits.iter().rev().enumerate().filter_map(|(index, &bit)| {
if bit {
Some(u64::exact_from(index))
} else {
None
}
}) {
n.set_bit(i);
}
n
} | identifier_body | |
from_bits.rs | use itertools::Itertools;
use malachite_base::num::basic::traits::Zero;
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::num::logic::traits::BitAccess;
use malachite_nz::natural::Natural;
pub fn | <I: Iterator<Item = bool>>(bits: I) -> Natural {
let mut n = Natural::ZERO;
for i in bits.enumerate().filter_map(|(index, bit)| {
if bit {
Some(u64::exact_from(index))
} else {
None
}
}) {
n.set_bit(i);
}
n
}
pub fn from_bits_desc_naive<I: Ite... | from_bits_asc_naive | identifier_name |
from_bits.rs | use itertools::Itertools;
use malachite_base::num::basic::traits::Zero;
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::num::logic::traits::BitAccess;
use malachite_nz::natural::Natural;
pub fn from_bits_asc_naive<I: Iterator<Item = bool>>(bits: I) -> Natural {
let mut n = Natural::ZERO... | else {
None
}
}) {
n.set_bit(i);
}
n
}
| {
Some(u64::exact_from(index))
} | conditional_block |
from_bits.rs | use itertools::Itertools;
use malachite_base::num::basic::traits::Zero;
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::num::logic::traits::BitAccess;
use malachite_nz::natural::Natural; | if bit {
Some(u64::exact_from(index))
} else {
None
}
}) {
n.set_bit(i);
}
n
}
pub fn from_bits_desc_naive<I: Iterator<Item = bool>>(bits: I) -> Natural {
let bits = bits.collect_vec();
let mut n = Natural::ZERO;
for i in bits.iter().rev()... |
pub fn from_bits_asc_naive<I: Iterator<Item = bool>>(bits: I) -> Natural {
let mut n = Natural::ZERO;
for i in bits.enumerate().filter_map(|(index, bit)| { | random_line_split |
integer-overflow.rs | // Copyright 2015 Keegan McAllister.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// See `LICENSE` in this repository.
#![feature(plugin, raw)]
#![plugin(afl_coverage_plugin)]
// Integer overflow bug.
// Loosely based on:
//... | use byteorder::{ReadBytesExt, LittleEndian, Error};
fn main() {
let mut stdin = io::stdin();
// First, the element size.
let bytes_per_element = stdin.read_u32::<LittleEndian>().unwrap();
loop {
let element_count = match stdin.read_u32::<LittleEndian>() {
Err(Error::UnexpectedEOF)... | use std::io::Read; | random_line_split |
integer-overflow.rs | // Copyright 2015 Keegan McAllister.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// See `LICENSE` in this repository.
#![feature(plugin, raw)]
#![plugin(afl_coverage_plugin)]
// Integer overflow bug.
// Loosely based on:
//... | () {
let mut stdin = io::stdin();
// First, the element size.
let bytes_per_element = stdin.read_u32::<LittleEndian>().unwrap();
loop {
let element_count = match stdin.read_u32::<LittleEndian>() {
Err(Error::UnexpectedEOF) => break,
Err(e) => panic!(e),
Ok(n... | main | identifier_name |
integer-overflow.rs | // Copyright 2015 Keegan McAllister.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// See `LICENSE` in this repository.
#![feature(plugin, raw)]
#![plugin(afl_coverage_plugin)]
// Integer overflow bug.
// Loosely based on:
//... | mem::transmute(raw::Slice {
data: buf.as_ptr(),
len: (element_count as usize) * (bytes_per_element as usize),
})
};
match stdin.by_ref().read(dest) {
Ok(n) if n == total_size => {
unsafe {
buf.set_le... | {
let mut stdin = io::stdin();
// First, the element size.
let bytes_per_element = stdin.read_u32::<LittleEndian>().unwrap();
loop {
let element_count = match stdin.read_u32::<LittleEndian>() {
Err(Error::UnexpectedEOF) => break,
Err(e) => panic!(e),
Ok(n) =... | identifier_body |
line.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library 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 ... |
}
| {
use error::ListErrorKind as LEK;
for entry in entries {
let s = entry.get_location().to_str().unwrap_or(String::from(self.unknown_output));
write!(stdout(), "{:?}\n", s).chain_err(|| LEK::FormatError)?
}
Ok(())
} | identifier_body |
line.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library 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 ... | <'a> {
unknown_output: &'a str,
}
impl<'a> LineLister<'a> {
pub fn new(unknown_output: &'a str) -> LineLister<'a> {
LineLister {
unknown_output: unknown_output,
}
}
}
impl<'a> Lister for LineLister<'a> {
fn list<'b, I: Iterator<Item = FileLockEntry<'b>>>(&self, entries: ... | LineLister | identifier_name |
line.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library 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 ... | unknown_output: &'a str,
}
impl<'a> LineLister<'a> {
pub fn new(unknown_output: &'a str) -> LineLister<'a> {
LineLister {
unknown_output: unknown_output,
}
}
}
impl<'a> Lister for LineLister<'a> {
fn list<'b, I: Iterator<Item = FileLockEntry<'b>>>(&self, entries: I) -> R... |
pub struct LineLister<'a> { | random_line_split |
tir.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | (i: i32) -> PrimExpr {
IntImm::from(i).upcast()
}
}
define_node!(Var, "Var", "tir.Var";
VarNode { name_hint: TVMString });
define_node!(Add, "Add", "tir.Add"; AddNode { a: PrimExpr, b: PrimExpr });
define_node!(Sub, "Sub", "tir.Sub"; SubNode { a: PrimExpr, b: PrimExpr });
define_node!(Mul, "M... | from | identifier_name |
tir.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | use crate::DataType;
use tvm_macros::Object;
macro_rules! define_node {
($name:ident, $ref:expr, $typekey:expr; $node:ident { $($id:ident : $t:ty),*}) => {
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = $ref]
#[type_key = $typekey]
pub struct $node {
base: Pri... | random_line_split | |
tir.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
}
define_node!(Var, "Var", "tir.Var";
VarNode { name_hint: TVMString });
define_node!(Add, "Add", "tir.Add"; AddNode { a: PrimExpr, b: PrimExpr });
define_node!(Sub, "Sub", "tir.Sub"; SubNode { a: PrimExpr, b: PrimExpr });
define_node!(Mul, "Mul", "tir.Mul"; MulNode { a: PrimExpr, b: PrimExpr });
defin... | {
IntImm::from(i).upcast()
} | identifier_body |
write_events.rs | use std::fmt;
use std::error::Error;
use std::ops::Range;
use raw::client_messages::{OperationResult};
use {StreamVersion, LogPosition};
/// Successful response to `Message::WriteEvents`
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WriteEventsCompleted {
/// The event number range assigned to the written even... |
}
| {
use self::WriteEventsFailure::*;
match *self {
PrepareTimeout => "Internal server timeout, should be retried",
CommitTimeout => "Internal server timeout, should be retried",
ForwardTimeout => "Server timed out while awaiting response to forwarded request, should be ... | identifier_body |
write_events.rs | use std::fmt;
use std::error::Error;
use std::ops::Range;
use raw::client_messages::{OperationResult};
use {StreamVersion, LogPosition};
/// Successful response to `Message::WriteEvents`
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WriteEventsCompleted {
/// The event number range assigned to the written even... | (&self) -> &str {
use self::WriteEventsFailure::*;
match *self {
PrepareTimeout => "Internal server timeout, should be retried",
CommitTimeout => "Internal server timeout, should be retried",
ForwardTimeout => "Server timed out while awaiting response to forwarded req... | description | identifier_name |
write_events.rs | use std::fmt;
use std::error::Error;
use std::ops::Range;
use raw::client_messages::{OperationResult};
use {StreamVersion, LogPosition};
/// Successful response to `Message::WriteEvents`
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WriteEventsCompleted {
/// The event number range assigned to the written even... | /// No authentication provided or insufficient permissions to a stream
AccessDenied,
}
impl WriteEventsFailure {
/// Return `true` if the operation failed in a transient way that might be resolved by
/// retrying.
pub fn is_transient(&self) -> bool {
use self::WriteEventsFailure::*;
... | ForwardTimeout,
/// Optimistic locking failure; stream version was not the expected
WrongExpectedVersion,
/// Stream has been deleted
StreamDeleted, | 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 http://mozilla.org/MPL/2.0/. */
//! Specified color values.
use cssparser::{Color as CSSParserColor, Parser, RGBA, Token, BasicParseError};
#[cfg... |
}
/// Specified value for the "color" property, which resolves the `currentcolor`
/// keyword to the parent color instead of self's color.
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[derive(Clone, Debug, PartialEq, ToCss)]
pub struct ColorPropertyValue(pub Color);
impl ToComputedValue for ColorPropertyVal... | {
RGBAColor(color)
} | identifier_body |
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 http://mozilla.org/MPL/2.0/. */
//! Specified color values.
use cssparser::{Color as CSSParserColor, Parser, RGBA, Token, BasicParseError};
#[cfg... | ,
};
if value < 0 {
return Err(StyleParseError::UnspecifiedError.into());
}
let length = if value <= 9 {
1
} else if value <= 99 {
2
} else if value <= 999 {
3
} else if value <= 9999 {
4
} else i... | {
return Err(BasicParseError::UnexpectedToken(t.clone()).into());
} | conditional_block |
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 http://mozilla.org/MPL/2.0/. */
//! Specified color values.
use cssparser::{Color as CSSParserColor, Parser, RGBA, Token, BasicParseError};
#[cfg... | (color: nscolor) -> ComputedColor {
use gecko::values::convert_nscolor_to_rgba;
ComputedColor::rgba(convert_nscolor_to_rgba(color))
}
impl ToComputedValue for Color {
type ComputedValue = ComputedColor;
fn to_computed_value(&self, context: &Context) -> ComputedColor {
match *self {
... | convert_nscolor_to_computedcolor | 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 http://mozilla.org/MPL/2.0/. */
//! Specified color values.
use cssparser::{Color as CSSParserColor, Parser, RGBA, Token, BasicParseError};
#[cfg... | match *self {
Color::CurrentColor => {
if let Some(longhand) = context.for_non_inherited_property {
if longhand.stores_complex_colors_lossily() {
context.rule_cache_conditions.borrow_mut()
.set_uncacheable();
... | random_line_split | |
lib.rs | #[macro_use]
extern crate nom;
use std::fmt::{Debug, Formatter, Result};
mod parser;
macro_rules! pp {
($msg:expr) => {{
println!("{:?}", $msg);
}};
}
mod Warc{
use parser;
use std::collections::HashMap;
pub fn parse(data: &String) -> Vec<Record> | break;
}
},
None => {
ended = true;
break;
}
}
}
pp!(next_new_line);
pp!(ended);
let (s, rest) =... | {
let mut header = HashMap::new();
let mut attr = HashMap::new();
let mut records: Vec<Record> = Vec::new();
let mut current_record: Option<Record> = None;
let mut data_chars_: Vec<char> = data.chars().collect();
let mut data_chars = &data_chars_[..];
let mut next... | identifier_body |
lib.rs | #[macro_use]
extern crate nom;
use std::fmt::{Debug, Formatter, Result};
mod parser;
macro_rules! pp {
($msg:expr) => {{
println!("{:?}", $msg);
}};
}
mod Warc{
use parser;
use std::collections::HashMap;
pub fn parse(data: &String) -> Vec<Record>{
let mut header = HashMap::new();
... | pp!(rest);
data_chars = rest;
if ended{ break;}
}
return vec![Record::new(attr, Header::new(header), "".to_string())]
}
pub struct Record{
attributes: HashMap<String, String>,
header: Header,
content: String,
}
impl Record{
... | random_line_split | |
lib.rs | #[macro_use]
extern crate nom;
use std::fmt::{Debug, Formatter, Result};
mod parser;
macro_rules! pp {
($msg:expr) => {{
println!("{:?}", $msg);
}};
}
mod Warc{
use parser;
use std::collections::HashMap;
pub fn parse(data: &String) -> Vec<Record>{
let mut header = HashMap::new();
... |
}
return vec![Record::new(attr, Header::new(header), "".to_string())]
}
pub struct Record{
attributes: HashMap<String, String>,
header: Header,
content: String,
}
impl Record{
fn new(attributes: HashMap<String, String>, header: Header, content: String) ... | { break;} | conditional_block |
lib.rs | #[macro_use]
extern crate nom;
use std::fmt::{Debug, Formatter, Result};
mod parser;
macro_rules! pp {
($msg:expr) => {{
println!("{:?}", $msg);
}};
}
mod Warc{
use parser;
use std::collections::HashMap;
pub fn parse(data: &String) -> Vec<Record>{
let mut header = HashMap::new();
... | () {
let s= "s
s".to_string();
let warc = Warc::parse(&s);
}
| it_debugs | identifier_name |
aarch64.rs | pub type c_long = i64;
pub type c_ulong = u64;
pub type c_char = u8;
pub type ucontext_t = sigcontext;
s! {
pub struct sigcontext {
__sc_unused: ::c_int,
pub sc_mask: ::c_int,
pub sc_sp: ::c_ulong,
pub sc_lr: ::c_ulong,
pub sc_elr: ::c_ulong,
pub sc_spsr: ::c_ulong,
... | pub const _MAX_PAGE_SHIFT: u32 = 12; | pub const _ALIGNBYTES: usize = 8 - 1;
}
}
| random_line_split |
observer.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use engine_traits::KvEngine;
use kvproto::metapb::Region;
use raft::StateRole;
use raftstore::coprocessor::*;
use tikv_util::worker::Scheduler;
use crate::cmd::lock_only_filter;
use crate::endpoint::Task;
use crate::metrics::RTS_CHANNEL_PENDING_CMD_BY... |
}
}
}
impl<E: KvEngine> RoleObserver for Observer<E> {
fn on_role_change(&self, ctx: &mut ObserverContext<'_>, role: StateRole) {
// Stop to advance resolved ts after peer steps down to follower or candidate.
// Do not need to check observe id because we expect all role change events a... | {
info!("failed to schedule register region task"; "err" => ?e);
} | conditional_block |
observer.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use engine_traits::KvEngine;
use kvproto::metapb::Region;
use raft::StateRole;
use raftstore::coprocessor::*;
use tikv_util::worker::Scheduler;
use crate::cmd::lock_only_filter;
use crate::endpoint::Task;
use crate::metrics::RTS_CHANNEL_PENDING_CMD_BY... | () {
let (scheduler, mut rx) = dummy_scheduler();
let observer = Observer::new(scheduler);
let engine = TestEngineBuilder::new().build().unwrap().get_rocksdb();
let mut data = vec![
put_cf(CF_LOCK, b"k1", b"v"),
put_cf(CF_DEFAULT, b"k2", b"v"),
put_cf(... | test_observing | identifier_name |
observer.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use engine_traits::KvEngine;
use kvproto::metapb::Region;
use raft::StateRole;
use raftstore::coprocessor::*;
use tikv_util::worker::Scheduler;
use crate::cmd::lock_only_filter;
use crate::endpoint::Task;
use crate::metrics::RTS_CHANNEL_PENDING_CMD_BY... |
}
impl<E: KvEngine> Clone for Observer<E> {
fn clone(&self) -> Self {
Self {
scheduler: self.scheduler.clone(),
}
}
}
impl<E: KvEngine> Coprocessor for Observer<E> {}
impl<E: KvEngine> CmdObserver<E> for Observer<E> {
fn on_flush_applied_cmd_batch(
&self,
max_... | {
// The `resolved-ts` cmd observer will `mem::take` the `Vec<CmdBatch>`, use a low priority
// to let it be the last observer and avoid affecting other observers
coprocessor_host
.registry
.register_cmd_observer(1000, BoxCmdObserver::new(self.clone()));
coprocess... | identifier_body |
observer.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use engine_traits::KvEngine;
use kvproto::metapb::Region;
use raft::StateRole;
use raftstore::coprocessor::*;
use tikv_util::worker::Scheduler;
use crate::cmd::lock_only_filter;
use crate::endpoint::Task;
use crate::metrics::RTS_CHANNEL_PENDING_CMD_BY... | cmd_batch: cmd_batches,
snapshot: None,
}) {
info!("failed to schedule change log event"; "err" =>?e);
}
}
fn on_applied_current_term(&self, role: StateRole, region: &Region) {
// Start to advance resolved ts after peer becomes leader and apply on its... | let size = cmd_batches.iter().map(|b| b.size()).sum::<usize>();
RTS_CHANNEL_PENDING_CMD_BYTES.add(size as i64);
if let Err(e) = self.scheduler.schedule(Task::ChangeLog { | 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/. */
//! Servo, the mighty web browser engine from the future.
//!
//! This is a very simple library that wires all of ... | () {
panic!("Sandboxing is not supported on Windows.");
}
| create_sandbox | identifier_name |
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/. */
//! Servo, the mighty web browser engine from the future.
//!
//! This is a very simple library that wires all of ... |
pub fn request_title_for_main_frame(&self) {
self.compositor.title_for_main_frame()
}
pub fn setup_logging(&self) {
let constellation_chan = self.constellation_chan.clone();
log::set_logger(|max_log_level| {
let env_logger = EnvLogger::new();
let con_logger... | {
self.compositor.pinch_zoom_level()
} | 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/. */
| //! Servo, the mighty web browser engine from the future.
//!
//! This is a very simple library that wires all of Servo's components
//! together as type `Browser`, along with a generic client
//! implementing the `WindowMethods` trait, to create a working web
//! browser.
//!
//! The `Browser` type is responsible for ... | random_line_split | |
rt-spawn-rate.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 ... | };
for _ in range(0, n) {
spawn(proc() {});
}
} | random_line_split | |
rt-spawn-rate.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 main() {
let args = os::args();
let args = args.as_slice();
let n = if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()
} else {
100000
};
for _ in range(0, n) {
spawn(proc() {});
}
}
| {
green::start(argc, argv, rustuv::event_loop, main)
} | identifier_body |
rt-spawn-rate.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 ... | (argc: int, argv: **u8) -> int {
green::start(argc, argv, rustuv::event_loop, main)
}
fn main() {
let args = os::args();
let args = args.as_slice();
let n = if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()
} else {
100000
};
for _ in range(0, n) {
spawn(proc... | start | identifier_name |
rt-spawn-rate.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 ... | else {
100000
};
for _ in range(0, n) {
spawn(proc() {});
}
}
| {
from_str::<uint>(args[1]).unwrap()
} | conditional_block |
base64.rs | /// Entry point for encoding input strings into base64-encoded output strings.
pub fn encode(inp: &str) -> String {
let base64_index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.chars()
.collect::<Vec<char>>();
let mut result = String:... | animals, which is a lust of the mind, that by a perseverance of delight in the continued \
and indefatigable generation of knowledge, exceeds the short vehemence of any carnal \
pleasure."
}
fn leviathan_b64() -> &'static str {
"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGh... | mod tests {
use super::{encode, decode};
fn leviathan() -> &'static str {
"Man is distinguished, not only by his reason, but by this singular passion from other \ | random_line_split |
base64.rs | /// Entry point for encoding input strings into base64-encoded output strings.
pub fn encode(inp: &str) -> String {
let base64_index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.chars()
.collect::<Vec<char>>();
let mut result = String:... |
}
let octet2 = match quartet[3] {
0x3D => 0x0,
_ => (bit_string & 0xFF) as u8,
};
bit_string >>= 8;
let octet1 = match quartet[2] {
0x3D => 0x0,
_ => (bit_string & 0xFF) as u8,
};
bit_string >>= 8;
let octe... | {
bit_string <<= 6;
} | conditional_block |
base64.rs | /// Entry point for encoding input strings into base64-encoded output strings.
pub fn encode(inp: &str) -> String {
let base64_index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.chars()
.collect::<Vec<char>>();
let mut result = String:... | () {
assert_eq!(leviathan_b64(), encode(leviathan()));
}
#[test]
fn decode_man() {
assert_eq!("Man".to_owned(), decode("TWFu"));
}
#[test]
fn decode_leviathan() {
assert_eq!(leviathan(), decode(leviathan_b64()));
}
}
| encode_leviathan | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.