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
mod.rs
//! Compiler utilities. //! //! This module contains a number of utilities used throughput the compiler, such as unique symbol //! and ID generators and a module for measuring compile-time performance of various aspects of the //! compiler. use fnv; use crate::ast::ExprKind::*; use crate::ast::*; use std::cmp::max; ...
<T: iter::Iterator<Item = String>>( start: &str, sep: &str, end: &str, strings: T, ) -> String { let mut res = String::new(); res.push_str(start); for (i, s) in strings.enumerate() { if i > 0 { res.push_str(sep); } res.push_str(&s); } res.push_str(...
join
identifier_name
mod.rs
//! Compiler utilities. //! //! This module contains a number of utilities used throughput the compiler, such as unique symbol //! and ID generators and a module for measuring compile-time performance of various aspects of the //! compiler. use fnv; use crate::ast::ExprKind::*; use crate::ast::*; use std::cmp::max; ...
{ let mut res = String::new(); res.push_str(start); for (i, s) in strings.enumerate() { if i > 0 { res.push_str(sep); } res.push_str(&s); } res.push_str(end); res }
identifier_body
mod.rs
//! Compiler utilities. //! //! This module contains a number of utilities used throughput the compiler, such as unique symbol
//! and ID generators and a module for measuring compile-time performance of various aspects of the //! compiler. use fnv; use crate::ast::ExprKind::*; use crate::ast::*; use std::cmp::max; use std::iter; pub mod colors; pub mod dump; pub mod stats; /// Utility struct that can track and generate unique IDs and sym...
random_line_split
mod.rs
//! Compiler utilities. //! //! This module contains a number of utilities used throughput the compiler, such as unique symbol //! and ID generators and a module for measuring compile-time performance of various aspects of the //! compiler. use fnv; use crate::ast::ExprKind::*; use crate::ast::*; use std::cmp::max; ...
}); SymbolGenerator { id_map } } pub fn new_symbol(&mut self, name: &str) -> Symbol { let id = self.id_map.entry(name.to_owned()).or_insert(-1); *id += 1; Symbol::new(name, *id) } } pub fn join<T: iter::Iterator<Item = String>>( start: &str, sep: &str, ...
{}
conditional_block
test_cargo.rs
use std::env; use std::ffi::OsString; use std::fs::{self, File}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::str; use cargo::util::process; use support::paths; use support::{execs, project, cargo_dir, mkdir_recursive, ProjectBuilder}; use hamcrest::{assert_that}; fn setup() { } /// Add an empty...
(_: &Path) {} } fn path() -> Vec<PathBuf> { env::split_paths(&env::var_os("PATH").unwrap_or(OsString::new())).collect() } test!(list_commands_looks_at_path { let proj = project("list-non-overlapping"); let proj = fake_executable(proj, &Path::new("path-test"), "cargo-1"); let mut pr = process(&cargo_di...
make_executable
identifier_name
test_cargo.rs
use std::env; use std::ffi::OsString; use std::fs::{self, File}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::str; use cargo::util::process; use support::paths; use support::{execs, project, cargo_dir, mkdir_recursive, ProjectBuilder}; use hamcrest::{assert_that}; fn setup() { } /// Add an empty...
test!(find_closest_biuld_to_build { let mut pr = process(&cargo_dir().join("cargo")); pr.arg("biuld").cwd(&paths::root()).env("HOME", &paths::home()); assert_that(pr, execs().with_status(127) .with_stderr("No such subcommand Did you mean `build`? ")); }); // if a s...
let output = output.exec_with_output().unwrap(); let output = str::from_utf8(&output.stdout).unwrap(); assert!(output.contains("\n 1\n"), "missing 1: {}", output); });
random_line_split
test_cargo.rs
use std::env; use std::ffi::OsString; use std::fs::{self, File}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::str; use cargo::util::process; use support::paths; use support::{execs, project, cargo_dir, mkdir_recursive, ProjectBuilder}; use hamcrest::{assert_that}; fn setup()
/// Add an empty file with executable flags (and platform-dependent suffix). /// TODO: move this to `ProjectBuilder` if other cases using this emerge. fn fake_executable(proj: ProjectBuilder, dir: &Path, name: &str) -> ProjectBuilder { let path = proj.root().join(dir).join(&format!("{}{}", name, ...
{ }
identifier_body
bandit.rs
use env::{Env, EnvConvert, EnvRepr, Action, DiscreteAction, Response, HorizonAveraged}; use rng::xorshift::{Xorshiftplus128Rng}; use rand::{Rng, thread_rng}; use rand::distributions::{IndependentSample}; use rand::distributions::range::{Range}; use std::f32::consts::{PI}; #[derive(Clone, Copy)] pub struct BanditActi...
else { Ok(Some(HorizonAveraged{value: 0.0, horizon: 100})) } } } impl EnvConvert<BanditEnv> for BanditEnv { fn clone_from_env(&mut self, other: &BanditEnv) { /*self.cfg = other.cfg; self.total_mass = other.total_mass; self.pole_mass_length = other.pole_mass_length; self.state = other.sta...
{ Ok(Some(HorizonAveraged{value: 1.0, horizon: 100})) }
conditional_block
bandit.rs
use env::{Env, EnvConvert, EnvRepr, Action, DiscreteAction, Response, HorizonAveraged}; use rng::xorshift::{Xorshiftplus128Rng}; use rand::{Rng, thread_rng}; use rand::distributions::{IndependentSample}; use rand::distributions::range::{Range}; use std::f32::consts::{PI}; #[derive(Clone, Copy)] pub struct BanditActi...
fn default() -> BanditConfig { BanditConfig{ } } } #[derive(Clone, Copy, Default)] struct BanditState { } //#[derive(Default)] pub struct BanditEnv { //cfg: BanditConfig, //state: BanditState, dist: Range<u32>, rng: Xorshiftplus128Rng, } impl Default for BanditEnv { fn default(...
} impl Default for BanditConfig {
random_line_split
bandit.rs
use env::{Env, EnvConvert, EnvRepr, Action, DiscreteAction, Response, HorizonAveraged}; use rng::xorshift::{Xorshiftplus128Rng}; use rand::{Rng, thread_rng}; use rand::distributions::{IndependentSample}; use rand::distributions::range::{Range}; use std::f32::consts::{PI}; #[derive(Clone, Copy)] pub struct BanditActi...
{ } //#[derive(Default)] pub struct BanditEnv { //cfg: BanditConfig, //state: BanditState, dist: Range<u32>, rng: Xorshiftplus128Rng, } impl Default for BanditEnv { fn default() -> BanditEnv { BanditEnv{ dist: Range::new(0, 10), rng: Xorshiftplus128Rng::new(&mut th...
BanditState
identifier_name
bandit.rs
use env::{Env, EnvConvert, EnvRepr, Action, DiscreteAction, Response, HorizonAveraged}; use rng::xorshift::{Xorshiftplus128Rng}; use rand::{Rng, thread_rng}; use rand::distributions::{IndependentSample}; use rand::distributions::range::{Range}; use std::f32::consts::{PI}; #[derive(Clone, Copy)] pub struct BanditActi...
} impl EnvRepr<f32> for BanditEnv { fn observable_sz(&self) -> usize { 10 } fn extract_observable(&self, obs: &mut [f32]) { /*obs[0] = self.state.x; obs[1] = self.state.x_dot; obs[2] = self.state.theta; obs[3] = self.state.theta_dot;*/ for i in 0.. 10 { obs[i] = 0.0; } obs...
{ /*self.cfg = other.cfg; self.total_mass = other.total_mass; self.pole_mass_length = other.pole_mass_length; self.state = other.state;*/ self.dist = other.dist; self.rng = other.rng.clone(); }
identifier_body
main.rs
extern crate clap; extern crate ansi_term; extern crate vagment; use std::io; use std::io::Write; use std::io::stdout; use clap::ArgMatches; use ansi_term::Colour::Yellow; use vagment::app::logger; use vagment::app::vagrant; use vagment::app::formatter; use vagment::app::machine::Machine; use vagment::app::machine:...
println!(""); std::process::exit(1); } } } fn parse(matches: &ArgMatches, machines: &[Machine]) -> Option<(String, u16)> { let mut number = 0; let mut command = String::from(""); if let Some(subcommand) = matches.subcommand_name() { command = subcommand.to_stri...
{ let mut cli = vagment::app::cli::init(); let matches = cli.clone().get_matches(); let machines = vagrant::get_machine_list(); match parse(&matches, &machines) { Some((command, number)) => { match run(command, number, machines) { Ok(m) => { logge...
identifier_body
main.rs
extern crate clap; extern crate ansi_term; extern crate vagment; use std::io; use std::io::Write; use std::io::stdout; use clap::ArgMatches; use ansi_term::Colour::Yellow; use vagment::app::logger; use vagment::app::vagrant; use vagment::app::formatter; use vagment::app::machine::Machine; use vagment::app::machine:...
fn parse(matches: &ArgMatches, machines: &[Machine]) -> Option<(String, u16)> { let mut number = 0; let mut command = String::from(""); if let Some(subcommand) = matches.subcommand_name() { command = subcommand.to_string(); if let Some(matches) = matches.subcommand_matches(subcommand) { ...
} }
random_line_split
main.rs
extern crate clap; extern crate ansi_term; extern crate vagment; use std::io; use std::io::Write; use std::io::stdout; use clap::ArgMatches; use ansi_term::Colour::Yellow; use vagment::app::logger; use vagment::app::vagrant; use vagment::app::formatter; use vagment::app::machine::Machine; use vagment::app::machine:...
(machines: &[Machine]) -> u16 { println!("{}", formatter::format(machines)); print!("{}", Yellow.paint("Please enter a machine number: ")); let _ = stdout().flush(); let mut input = String::new(); match io::stdin().read_line(&mut input) { Ok(bytes) => bytes, Err(error) => panic!("C...
ask_for_machine_number
identifier_name
cmp.rs
use core::ops::{Eq, Deref}; use str_one::{ByteStr, CStr, NoNullStr}; use string::{String}; use c_string::{CString}; use alloc::{MemPool}; macro_rules! owned { ($one:ident, $two:ident) => { impl<H1, H2> Eq<$two<H2>> for $one<H1> where H1: MemPool, H2: MemPool, { ...
// 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/.
random_line_split
gdb-pretty-struct-and-enums.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...
the_fourth_field: &'static str, } struct TupleStruct(f64, i16); struct EmptyStruct; enum CStyleEnum { CStyleEnumVar1, CStyleEnumVar2, CStyleEnumVar3, } enum MixedEnum { MixedEnumCStyleVar, MixedEnumTupleVar(u32, u16, bool), MixedEnumStructVar { field1: f64, field2: i32 } } struct Nested...
struct RegularStruct { the_first_field: int, the_second_field: f64, the_third_field: bool,
random_line_split
gdb-pretty-struct-and-enums.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...
() { let regular_struct = RegularStruct { the_first_field: 101, the_second_field: 102.5, the_third_field: false, the_fourth_field: "I'm so pretty, oh so pretty..." }; let tuple = ( true, 103u32, "blub" ); let tuple_struct = TupleStruct(-104.5, 105); let empty_stru...
main
identifier_name
packed-struct-with-destructor.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...
// debugger:print unpackedInPacked // check:$4 = {a = 987, b = {x = 876, y = 765, z = 654}, c = {x = 543, y = 432, z = 321}, d = 210} // debugger:print packedInPackedWithDrop // check:$5 = {a = 11, b = {x = 22, y = 33, z = 44}, c = 55, d = {x = 66, y = 77, z = 88}} // debugger:print packedInUnpackedWithDrop // check...
// debugger:print packedInUnpacked // check:$3 = {a = -1111, b = {x = -2222, y = -3333, z = -4444}, c = -5555, d = {x = -6666, y = -7777, z = -8888}}
random_line_split
packed-struct-with-destructor.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...
(&mut self) {} } #[packed] struct PackedInPacked { a: i32, b: Packed, c: i64, d: Packed } struct PackedInUnpacked { a: i32, b: Packed, c: i64, d: Packed } struct Unpacked { x: i64, y: i32, z: i16 } impl Drop for Unpacked { fn drop(&mut self) {} } #[packed] struct Unp...
drop
identifier_name
free_list.rs
// Copyright 2014 SiegeLord // Licensed under GPL, see LICENSE for full terms pub struct FreeList<T> { items: Vec<Option<T>>, free_idxs: Vec<uint>, } impl<T> FreeList<T> { pub fn new() -> FreeList<T> { FreeList { items: vec![], free_idxs: vec![], } } pub fn push(&mut self, item: T) -> uint { mat...
else { self.idx += 1; unsafe { match *self.items.unsafe_ref(self.idx - 1) { Some(ref item) => return Some(item), None => continue } } } } } } #[test] fn test_free_list() { let mut list = FreeList::new(); let idx1 = list.push(1u); let idx2 = list.push(2); list...
{ return None }
conditional_block
free_list.rs
// Copyright 2014 SiegeLord // Licensed under GPL, see LICENSE for full terms pub struct FreeList<T> { items: Vec<Option<T>>, free_idxs: Vec<uint>, } impl<T> FreeList<T> { pub fn new() -> FreeList<T> { FreeList { items: vec![], free_idxs: vec![], } } pub fn push(&mut self, item: T) -> uint { mat...
(&mut self, idx: uint) -> bool { if self.items.get(idx).is_some() { self.free_idxs.push(idx); *self.items.get_mut(idx) = None; true } else { false } } pub fn get<'l>(&'l self, idx: uint) -> Option<&'l T> { self.items.get(idx).as_ref() } pub fn get_mut<'l>(&'l mut self, idx: uint) -> O...
free
identifier_name
free_list.rs
// Copyright 2014 SiegeLord // Licensed under GPL, see LICENSE for full terms pub struct FreeList<T> { items: Vec<Option<T>>, free_idxs: Vec<uint>, } impl<T> FreeList<T> { pub fn new() -> FreeList<T> { FreeList { items: vec![], free_idxs: vec![], } } pub fn push(&mut self, item: T) -> uint { mat...
self.items.len() - self.free_idxs.len() } } #[allow(dead_code)] pub struct FreeListItems<'l, T> { idx: uint, items: &'l [Option<T>] } impl<'l, T> Iterator<&'l T> for FreeListItems<'l, T> { fn next(&mut self) -> Option<&'l T> { loop { if self.idx >= self.items.len() { return None } else {...
pub fn len(&self) -> uint {
random_line_split
multiple_files.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let args = os::args(); let rustc = args[1].as_slice(); let tmpdir = Path::new(args[2].as_slice()); let main_file = tmpdir.join("unicode_input_multiple_files_main.rs"); let main_file_str = main_file.as_str().unwrap(); { let _ = File::create(&main_file).unwrap() .write_str...
main
identifier_name
multiple_files.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { let args = os::args(); let rustc = args[1].as_slice(); let tmpdir = Path::new(args[2].as_slice()); let main_file = tmpdir.join("unicode_input_multiple_files_main.rs"); let main_file_str = main_file.as_str().unwrap(); { let _ = File::create(&main_file).unwrap() ....
{ let mut rng = task_rng(); // a subset of the XID_start unicode table (ensuring that the // compiler doesn't fail with an "unrecognised token" error) let (lo, hi): (u32, u32) = match rng.gen_range(1, 4 + 1) { 1 => (0x41, 0x5a), 2 => (0xf8, 0x1ba), 3 => (0x1401, 0x166c), ...
identifier_body
multiple_files.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 ...
} } // rustc is passed to us with --out-dir and -L etc., so we // can't exec it directly let result = Process::output("sh", [~"-c", rustc + " " + main_file_str]).unwrap(); let err = str::from_utf8_lossy(result.error.as_slice()); // positive test so that this...
{ let randoms = tmpdir.join("unicode_input_multiple_files_chars.rs"); let mut w = File::create(&randoms).unwrap(); for _ in range(0, 30) { let _ = w.write_char(random_char());
random_line_split
triehash.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
.into_iter() .map(|(k, v)| (as_nibbles(&k), v) ) .collect(); gen_trie_root(gen_input) } fn gen_trie_root(input: Vec<(Vec<u8>, Vec<u8>)>) -> H256 { let mut stream = RlpStream::new(); hash256rlp(&input, 0, &mut stream); stream.out().sha3() } /// Hex-prefix Notation. First nibble has flags: oddness = 2^0 & te...
.collect::<BTreeMap<_, _>>() // then move them to a vector
random_line_split
triehash.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
}
{ assert!(trie_root(vec![ (vec![0x01u8, 0x23], vec![0x01u8, 0x23]), (vec![0x81u8, 0x23], vec![0x81u8, 0x23]), (vec![0xf1u8, 0x23], vec![0xf1u8, 0x23]), ]) == trie_root(vec![ (vec![0x01u8, 0x23], vec![0x01u8, 0x23]), (vec![0xf1u8, 0x23], vec![0xf1u8, 0x23]), (vec![0x81u8, 0x23], vec![0x81u8, 0x23...
identifier_body
triehash.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
() { let v = vec![0x31, 0x23, 0x45]; let e = vec![3, 1, 2, 3, 4, 5]; assert_eq!(as_nibbles(&v), e); // A => 65 => 0x41 => [4, 1] let v: Vec<u8> = From::from("A"); let e = vec![4, 1]; assert_eq!(as_nibbles(&v), e); } #[test] fn test_hex_prefix_encode() { let v = vec![0, 0, 1, 2, 3, 4, 5]; let e = vec![0x10, 0...
test_nibbles
identifier_name
main.rs
/** * Tutorial 1 -- Creating a Basic Triangle * * In this tutorial we learn how to create a window using glutin/glium and use * OpenGL to render a triangle. **/ // import the crates that we need #[macro_use] extern crate glium; extern crate glutin; use glium::{DisplayBuild, Surface}; // this struct will hold o...
display.wait_events().next(); if display.is_closed() { break; } } }
target.finish();
random_line_split
main.rs
/** * Tutorial 1 -- Creating a Basic Triangle * * In this tutorial we learn how to create a window using glutin/glium and use * OpenGL to render a triangle. **/ // import the crates that we need #[macro_use] extern crate glium; extern crate glutin; use glium::{DisplayBuild, Surface}; // this struct will hold o...
{ position: [f32; 2], } // program entry point fn main() { let display = glutin::WindowBuilder::new() .with_title("tetra".to_string()) .build_glium() .unwrap(); implement_vertex!(Vertex, position); let vertex1 = Vertex { position: [-0.5, -0.5] }; let vertex2 = Vertex { posi...
Vertex
identifier_name
main.rs
/** * Tutorial 1 -- Creating a Basic Triangle * * In this tutorial we learn how to create a window using glutin/glium and use * OpenGL to render a triangle. **/ // import the crates that we need #[macro_use] extern crate glium; extern crate glutin; use glium::{DisplayBuild, Surface}; // this struct will hold o...
#version 130 in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } "#; let fragment_shader_src = r#" #version 130 void main() { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); } "#; let program = glium::Prog...
{ let display = glutin::WindowBuilder::new() .with_title("tetra".to_string()) .build_glium() .unwrap(); implement_vertex!(Vertex, position); let vertex1 = Vertex { position: [-0.5, -0.5] }; let vertex2 = Vertex { position: [ 0.0, 0.5] }; let vertex3 = Vertex { position: [ ...
identifier_body
main.rs
/** * Tutorial 1 -- Creating a Basic Triangle * * In this tutorial we learn how to create a window using glutin/glium and use * OpenGL to render a triangle. **/ // import the crates that we need #[macro_use] extern crate glium; extern crate glutin; use glium::{DisplayBuild, Surface}; // this struct will hold o...
} }
{ break; }
conditional_block
kindck-owned-trait.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:Clone + foo>(t: T) -> @foo { @t as @foo //~^ ERROR value may contain borrowed pointers; add `'static` bound //~^^ ERROR cannot pack type //~^^^ ERROR value may contain borrowed pointers } fn to_foo2<T:Clone + foo +'static>(t: T) -> @foo { @t as @foo } fn main() {}
to_foo
identifier_name
kindck-owned-trait.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 ...
//~^^^ ERROR value may contain borrowed pointers } fn to_foo2<T:Clone + foo +'static>(t: T) -> @foo { @t as @foo } fn main() {}
fn to_foo<T:Clone + foo>(t: T) -> @foo { @t as @foo //~^ ERROR value may contain borrowed pointers; add `'static` bound //~^^ ERROR cannot pack type
random_line_split
kindck-owned-trait.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() {}
{ @t as @foo }
identifier_body
server.rs
extern crate gj; extern crate gjio; extern crate slab; use std::io::{Error, ErrorKind}; use std::rc::{Rc, Weak}; use std::cell::{Cell, RefCell}; use slab::Slab; use gj::{EventLoop, Promise, TaskReaper, TaskSet}; use gjio::{SocketStream, AsyncRead, AsyncWrite}; struct WriteQueue { task: Promise<(SocketStream, Bomb...
} fn send(&mut self, message: Vec<u8>) { let task = ::std::mem::replace(&mut self.task, Promise::err(Error::new(ErrorKind::Other, "uninitialized"))); self.len.set(self.len.get() + 1); let len = self.len.clone(); self.task = task.then(move |(mut stream, bomb)| { let h...
self.len.get()
random_line_split
server.rs
extern crate gj; extern crate gjio; extern crate slab; use std::io::{Error, ErrorKind}; use std::rc::{Rc, Weak}; use std::cell::{Cell, RefCell}; use slab::Slab; use gj::{EventLoop, Promise, TaskReaper, TaskSet}; use gjio::{SocketStream, AsyncRead, AsyncWrite}; struct WriteQueue { task: Promise<(SocketStream, Bomb...
try!(accept_loop(listener, TaskSet::new(reaper), subscribers).wait(wait_scope, &mut event_port)); Ok(()) }).expect("top level"); }
{ let args: Vec<String> = ::std::env::args().collect(); if args.len() != 2 { println!("usage: {} HOST:PORT", args[0]); return; } EventLoop::top_level(move |wait_scope| -> Result<(), Box<::std::error::Error>> { let mut event_port = try!(gjio::EventPort::new()); let networ...
identifier_body
server.rs
extern crate gj; extern crate gjio; extern crate slab; use std::io::{Error, ErrorKind}; use std::rc::{Rc, Weak}; use std::cell::{Cell, RefCell}; use slab::Slab; use gj::{EventLoop, Promise, TaskReaper, TaskSet}; use gjio::{SocketStream, AsyncRead, AsyncWrite}; struct WriteQueue { task: Promise<(SocketStream, Bomb...
(&self) -> usize { self.len.get() } fn send(&mut self, message: Vec<u8>) { let task = ::std::mem::replace(&mut self.task, Promise::err(Error::new(ErrorKind::Other, "uninitialized"))); self.len.set(self.len.get() + 1); let len = self.len.clone(); self.task = task.then(mov...
len
identifier_name
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromLayoutMsg, CanvasData}; use dom::attr::Attr; use dom::attr::AttrValue; use dom:...
(&self) { let size = self.get_size(); if let Some(ref context) = *self.context.borrow() { match *context { CanvasContext::Context2d(ref context) => context.set_bitmap_dimensions(size), CanvasContext::WebGL(ref context) => context.recreate(size), } ...
recreate_contexts
identifier_name
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromLayoutMsg, CanvasData}; use dom::attr::Attr; use dom::attr::AttrValue; use dom:...
} else { repeat(0xffu8).take((size.height as usize) * (size.width as usize) * 4).collect() }; Some((data, size)) } } impl HTMLCanvasElementMethods for HTMLCanvasElement { // https://html.spec.whatwg.org/multipage/#dom-canvas-width make_uint_getter!(Width, "width", DEFA...
{ let size = self.get_size(); if size.width == 0 || size.height == 0 { return None } let data = if let Some(renderer) = self.ipc_renderer() { let (sender, receiver) = ipc::channel().unwrap(); let msg = CanvasMsg::FromLayout(FromLayoutMsg::SendData(se...
identifier_body
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromLayoutMsg, CanvasData}; use dom::attr::Attr; use dom::attr::AttrValue; use dom:...
impl<'a> From<&'a WebGLContextAttributes> for GLContextAttributes { fn from(attrs: &'a WebGLContextAttributes) -> GLContextAttributes { GLContextAttributes { alpha: attrs.alpha, depth: attrs.depth, stencil: attrs.stencil, antialias: attrs.antialias, ...
random_line_split
vec-matching-autoslice.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 x = [1, 2, 3]; match x { [2, _, _] => panic!(), [1, a, b] => { assert!([a, b] == [2, 3]); } [_, _, _] => panic!(), } let y = ([(1, true), (2, false)], 0.5f64); match y { ([(1, a), (b, false)], _) => { assert_eq!(a, true); ...
main
identifier_name
vec-matching-autoslice.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 x = [1, 2, 3]; match x { [2, _, _] => panic!(), [1, a, b] => { assert!([a, b] == [2, 3]); } [_, _, _] => panic!(), } let y = ([(1, true), (2, false)], 0.5f64); match y { ([(1, a), (b, false)], _) => { assert_eq!(a, true); ...
identifier_body
vec-matching-autoslice.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 ...
([(1, a), (b, false)], _) => { assert_eq!(a, true); assert_eq!(b, 2); } ([_, _], 0.5) => panic!(), ([_, _], _) => panic!(), } }
[_, _, _] => panic!(), } let y = ([(1, true), (2, false)], 0.5f64); match y {
random_line_split
v6.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
// block log blooms are removed if key[32] == 3 { return None; } // blocks blooms key changes: // - key is shorter 33 -> 6 bytes // - index is moved to the front // - index is changed 4 -> 3 if key[32] == 4 { // i have no idea why it was reversed let reverse = key.into_iter().rev(...
{ return Some((self.migrate_old_key(key, 2, 33), value)); }
conditional_block
v6.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(&self) -> Option<u32> { None } fn version(&self) -> u32 { 6 } fn simple_migrate(&mut self, key: Vec<u8>, value: Vec<u8>) -> Option<(Vec<u8>, Vec<u8>)> { //// at this version all extras keys are 33 bytes long. if key.len() == 33 { // block details key changes: // - index is moved to the front if key[3...
columns
identifier_name
v6.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
fn simple_migrate(&mut self, key: Vec<u8>, value: Vec<u8>) -> Option<(Vec<u8>, Vec<u8>)> { //// at this version all extras keys are 33 bytes long. if key.len() == 33 { // block details key changes: // - index is moved to the front if key[32] == 0 { return Some((self.migrate_old_key(key, 0, 33), val...
{ 6 }
identifier_body
v6.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
result[2] = reverse[4]; result[3] = reverse[3]; result[4] = reverse[2]; result[5] = reverse[1]; return Some((result.to_vec(), value)); } // blocks receipts key changes: // - index is moved to the front // - index is changed 5 -> 4 if key[32] == 5 { return Some((self.migrate_old_...
// 9th (+ prefix) byte was the level. Now it's second. result[1] = reverse[9];
random_line_split
controller.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/. */ extern crate serde_json; extern crate mio; use adapters::AdapterManager; use config_store::ConfigService; use fox...
(&self) -> Arc<UpnpManager> { self.upnp.clone() } fn get_users_manager(&self) -> Arc<UsersManager> { self.users_manager.clone() } fn get_certificate_manager(&self) -> CertificateManager { self.certificate_manager.clone() } /// Every box should create a self signed cert...
get_upnp_manager
identifier_name
controller.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/. */ extern crate serde_json; extern crate mio; use adapters::AdapterManager; use config_store::ConfigService; use fox...
fn get_certificate_manager(&self) -> CertificateManager { self.certificate_manager.clone() } /// Every box should create a self signed certificate for a local name. /// The fingerprint of that certificate becomes the box's identifier, /// which is used to create the public DNS zone and lo...
{ self.users_manager.clone() }
identifier_body
controller.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/. */ extern crate serde_json; extern crate mio; use adapters::AdapterManager; use config_store::ConfigService; use fox...
array.push(service); } serde_json::to_string(&array) } fn get_http_root_for_service(&self, service_id: String) -> String { let scheme = if self.get_tls_enabled() { "https" } else { "http" }; format!("{}://{}:{}/services/{}/", scheme, self.hostname, self.http_port, se...
let services = self.services.lock().unwrap(); let mut array: Vec<&Box<Service>> = vec!(); for service in services.values() {
random_line_split
expand.rs
#![crate_name = "expand"] #![feature(unicode)] /* * This file is part of the uutils coreutils package. * * (c) Virgile Andreani <virgile.andreani@anbuco.fr> * (c) kwantam <kwantam@gmail.com> * 20150428 updated to work with both UTF-8 and non-UTF-8 encodings * * For the full copyright and license information...
#[derive(PartialEq, Eq, Debug)] enum CharType { Backspace, Tab, Other, } fn expand(options: Options) { use self::CharType::*; let mut output = BufWriter::new(stdout()); let ts = options.tabstops.as_ref(); let mut buf = Vec::new(); for file in options.files.into_iter() { let ...
{ if tabstops.len() == 1 { tabstops[0] - col % tabstops[0] } else { match tabstops.iter().skip_while(|&&t| t <= col).next() { Some(t) => t - col, None => 1, } } }
identifier_body
expand.rs
#![crate_name = "expand"] #![feature(unicode)] /* * This file is part of the uutils coreutils package. * * (c) Virgile Andreani <virgile.andreani@anbuco.fr> * (c) kwantam <kwantam@gmail.com> * 20150428 updated to work with both UTF-8 and non-UTF-8 encodings * * For the full copyright and license information...
match nums.iter().fold((true, 0), |(acc, last), &n| (acc && last <= n, n)) { (false, _) => crash!(1, "{}\n", "tab sizes must be ascending"), _ => {} } nums } struct Options { files: Vec<String>, tabstops: Vec<usize>, tspaces: String, iflag: bool, uflag: bool, } impl Op...
}
random_line_split
expand.rs
#![crate_name = "expand"] #![feature(unicode)] /* * This file is part of the uutils coreutils package. * * (c) Virgile Andreani <virgile.andreani@anbuco.fr> * (c) kwantam <kwantam@gmail.com> * 20150428 updated to work with both UTF-8 and non-UTF-8 encodings * * For the full copyright and license information...
, } byte += nbytes; // advance the pointer } buf.truncate(0); // clear the buffer } } }
{ col = if ctype == Other { col + cwidth } else if col > 0 { col - 1 } else { 0 }; // if we're writing anything oth...
conditional_block
expand.rs
#![crate_name = "expand"] #![feature(unicode)] /* * This file is part of the uutils coreutils package. * * (c) Virgile Andreani <virgile.andreani@anbuco.fr> * (c) kwantam <kwantam@gmail.com> * 20150428 updated to work with both UTF-8 and non-UTF-8 encodings * * For the full copyright and license information...
(options: Options) { use self::CharType::*; let mut output = BufWriter::new(stdout()); let ts = options.tabstops.as_ref(); let mut buf = Vec::new(); for file in options.files.into_iter() { let mut fh = open(file); while match fh.read_until('\n' as u8, &mut buf) { Ok(s)...
expand
identifier_name
htmldatalistelement.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::codegen::Bindings::HTMLDataListElementBinding; use crate::dom::bindings::codegen::Bindi...
prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLDataListElement> { Node::reflect_node( Box::new(HTMLDataListElement::new_inherited( local_name, prefix, document, )), document, HTMLDataListElementBinding::Wrap, ...
#[allow(unrooted_must_root)] pub fn new( local_name: LocalName,
random_line_split
htmldatalistelement.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::codegen::Bindings::HTMLDataListElementBinding; use crate::dom::bindings::codegen::Bindi...
#[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLDataListElement> { Node::reflect_node( Box::new(HTMLDataListElement::new_inherited( local_name, prefix, document, ...
{ HTMLDataListElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } }
identifier_body
htmldatalistelement.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::codegen::Bindings::HTMLDataListElementBinding; use crate::dom::bindings::codegen::Bindi...
( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLDataListElement> { Node::reflect_node( Box::new(HTMLDataListElement::new_inherited( local_name, prefix, document, )), document, HTMLD...
new
identifier_name
else_if_without_else.rs
//! Lint on if expressions with an else if, but without a final else branch. use clippy_utils::diagnostics::span_lint_and_help; use rustc_ast::ast::{Expr, ExprKind}; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_middle::lint::in_external_macro; use rustc_session::{declare_lint_pass, declare_tool_lint}; dec...
}
{ if in_external_macro(cx.sess, item.span) { return; } while let ExprKind::If(_, _, Some(ref els)) = item.kind { if let ExprKind::If(_, _, None) = els.kind { span_lint_and_help( cx, ELSE_IF_WITHOUT_ELSE, ...
identifier_body
else_if_without_else.rs
//! Lint on if expressions with an else if, but without a final else branch. use clippy_utils::diagnostics::span_lint_and_help; use rustc_ast::ast::{Expr, ExprKind}; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_middle::lint::in_external_macro; use rustc_session::{declare_lint_pass, declare_tool_lint}; dec...
(&mut self, cx: &EarlyContext<'_>, mut item: &Expr) { if in_external_macro(cx.sess, item.span) { return; } while let ExprKind::If(_, _, Some(ref els)) = item.kind { if let ExprKind::If(_, _, None) = els.kind { span_lint_and_help( cx, ...
check_expr
identifier_name
else_if_without_else.rs
//! Lint on if expressions with an else if, but without a final else branch. use clippy_utils::diagnostics::span_lint_and_help; use rustc_ast::ast::{Expr, ExprKind}; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_middle::lint::in_external_macro; use rustc_session::{declare_lint_pass, declare_tool_lint}; dec...
while let ExprKind::If(_, _, Some(ref els)) = item.kind { if let ExprKind::If(_, _, None) = els.kind { span_lint_and_help( cx, ELSE_IF_WITHOUT_ELSE, els.span, "`if` expression with an `else if`, but wit...
{ return; }
conditional_block
else_if_without_else.rs
//! Lint on if expressions with an else if, but without a final else branch. use clippy_utils::diagnostics::span_lint_and_help; use rustc_ast::ast::{Expr, ExprKind}; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_middle::lint::in_external_macro; use rustc_session::{declare_lint_pass, declare_tool_lint}; dec...
/// if x.is_positive() { /// a(); /// } else if x.is_negative() { /// b(); /// } /// ``` /// /// Could be written: /// /// ```rust /// # fn a() {} /// # fn b() {} /// # let x: i32 = 1; /// if x.is_positive() { /// a(); /// } else if x.is_negati...
random_line_split
value.rs
use Renderable; use context::Context; use std::collections::HashMap; use std::cmp::Ordering; /// An enum to represent different value types #[derive(Clone, PartialEq, Debug)] pub enum Value{ Num(f32), Str(String), Object(HashMap<String, Value>), Array(Vec<Value>) } // TODO implement for object and arr...
fn ge(&self, other: &Value) -> bool{ match (self, other) { (&Value::Num(x), &Value::Num(y)) => x.ge(&y), (&Value::Str(ref x), &Value::Str(ref y)) => x.ge(y), _ => false } } } impl ToString for Value{ fn to_string(&self) -> String{ match self{ ...
{ match (self, other) { (&Value::Num(x), &Value::Num(y)) => x.gt(&y), (&Value::Str(ref x), &Value::Str(ref y)) => x.gt(y), _ => false } }
identifier_body
value.rs
use Renderable; use context::Context; use std::collections::HashMap; use std::cmp::Ordering; /// An enum to represent different value types #[derive(Clone, PartialEq, Debug)] pub enum
{ Num(f32), Str(String), Object(HashMap<String, Value>), Array(Vec<Value>) } // TODO implement for object and array // TODO clean this up impl PartialOrd<Value> for Value{ fn partial_cmp(&self, other: &Value) -> Option<Ordering>{ match (self, other) { (&Value::Num(x), &Value::Nu...
Value
identifier_name
value.rs
use Renderable; use context::Context; use std::collections::HashMap; use std::cmp::Ordering; /// An enum to represent different value types #[derive(Clone, PartialEq, Debug)] pub enum Value{ Num(f32), Str(String),
// TODO implement for object and array // TODO clean this up impl PartialOrd<Value> for Value{ fn partial_cmp(&self, other: &Value) -> Option<Ordering>{ match (self, other) { (&Value::Num(x), &Value::Num(y)) => x.partial_cmp(&y), (&Value::Str(ref x), &Value::Str(ref y)) => x.partial...
Object(HashMap<String, Value>), Array(Vec<Value>) }
random_line_split
plus_minus.rs
//https://www.hackerrank.com/challenges/plus-minus use std::io; use std::io::prelude::*; fn main()
} } println!("{}", count_positive / count); println!("{}", count_negative / count); println!("{}", count_zeros / count); }
{ let stdin = io::stdin(); let count: f64 = stdin.lock().lines() //iterator over lines in stdin .next().unwrap().unwrap() //finally it's a string .trim().parse().unwrap(); //and then parsing count value... let mut count_positive: f64 = 0.0; let mut count_negative: f64 = 0.0; let mut...
identifier_body
plus_minus.rs
//https://www.hackerrank.com/challenges/plus-minus
fn main() { let stdin = io::stdin(); let count: f64 = stdin.lock().lines() //iterator over lines in stdin .next().unwrap().unwrap() //finally it's a string .trim().parse().unwrap(); //and then parsing count value... let mut count_positive: f64 = 0.0; let mut count_negative: f64 = 0.0; ...
use std::io; use std::io::prelude::*;
random_line_split
plus_minus.rs
//https://www.hackerrank.com/challenges/plus-minus use std::io; use std::io::prelude::*; fn main() { let stdin = io::stdin(); let count: f64 = stdin.lock().lines() //iterator over lines in stdin .next().unwrap().unwrap() //finally it's a string .trim().parse().unwrap(); //and then parsing coun...
else if item < 0.0 { count_negative += 1.0; } else { count_zeros += 1.0; } } } println!("{}", count_positive / count); println!("{}", count_negative / count); println!("{}", count_zeros / count); }
{ count_positive += 1.0; }
conditional_block
plus_minus.rs
//https://www.hackerrank.com/challenges/plus-minus use std::io; use std::io::prelude::*; fn
() { let stdin = io::stdin(); let count: f64 = stdin.lock().lines() //iterator over lines in stdin .next().unwrap().unwrap() //finally it's a string .trim().parse().unwrap(); //and then parsing count value... let mut count_positive: f64 = 0.0; let mut count_negative: f64 = 0.0; let mu...
main
identifier_name
step2.rs
// PART 1 indy::pool::set_protocol_version(PROTOCOL_VERSION).wait().unwrap(); println!("1. Creating a new local pool ledger configuration that can be used later to connect pool nodes"); let pool_config_file = create_genesis_txn_file_for_pool(pool_name); let pool_config = json!({ "genesis_txn" : &pool_config_file }...
let config = json!({ "id" : wallet_name.to_string() }).to_string(); wallet::create_wallet(&config, USEFUL_CREDENTIALS).wait().unwrap(); println!("4. Open wallet and get the wallet handle from libindy"); let wallet_handle: i32 = wallet::open_wallet(&config, USEFUL_CREDENTIALS).wait().unwrap(); println!("5. Generating ...
let pool_handle: i32 = pool::open_pool_ledger(&pool_name, None).wait().unwrap(); println!("3. Creates a new wallet");
random_line_split
it.rs
extern crate unterflow; extern crate tokio_core; use tokio_core::reactor::Core; use unterflow::Client; fn client(core: &mut Core) -> Client { let addr = "127.0.0.1:51015".parse().unwrap(); let client = Client::connect(&addr, &core.handle()); core.run(client).unwrap() } #[test] fn test_topology()
topic.get(&0) }, ) ); assert_eq!( Some(1), topology.topic_leaders.get("internal-system").map(|topic| { topic.len() }) ); assert_eq!( Some(broker), topology.topic_leaders.get("internal-system").and_then( |...
{ let mut core = Core::new().unwrap(); let client = client(&mut core); let topology = core.run(client.topology()).unwrap(); assert_eq!(1, topology.brokers.len()); let broker = &topology.brokers[0]; assert_eq!( Some(1), topology.topic_leaders.get("default-topic").map(|topic| {...
identifier_body
it.rs
extern crate unterflow; extern crate tokio_core; use tokio_core::reactor::Core; use unterflow::Client; fn client(core: &mut Core) -> Client { let addr = "127.0.0.1:51015".parse().unwrap(); let client = Client::connect(&addr, &core.handle()); core.run(client).unwrap() } #[test] fn test_topology() { ...
() { let mut core = Core::new().unwrap(); let client = client(&mut core); let task = client.new_task("foo".to_string()).retires(12).add_header( "foo".to_string(), "bar".to_string(), ); let task = core.run(task.create("default-topic")).unwrap(); assert_eq!("CREATED", task.state...
test_create_task
identifier_name
it.rs
extern crate unterflow; extern crate tokio_core; use tokio_core::reactor::Core; use unterflow::Client;
fn client(core: &mut Core) -> Client { let addr = "127.0.0.1:51015".parse().unwrap(); let client = Client::connect(&addr, &core.handle()); core.run(client).unwrap() } #[test] fn test_topology() { let mut core = Core::new().unwrap(); let client = client(&mut core); let topology = core.run(cli...
random_line_split
cors.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/. */ //! A partial implementation of CORS //! For now this library is XHR-specific. //! For stuff involving `<img>`, `<...
fn match_method(&self, method: &Method) -> bool { match *self { HeaderOrMethod::MethodData(ref m) => m == method, _ => false } } } // An entry in the CORS cache #[derive(Clone)] pub struct CORSCacheEntry { pub origin: Url, pub url: Url, pub max_age: u32, ...
{ match *self { HeaderOrMethod::HeaderData(ref s) => s.eq_ignore_ascii_case(header_name), _ => false } }
identifier_body
cors.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/. */ //! A partial implementation of CORS //! For now this library is XHR-specific. //! For stuff involving `<img>`, `<...
(mut referer: Url, destination: Url, mode: RequestMode, method: Method, headers: Headers) -> CORSRequest { match referer.scheme_data { SchemeData::Relative(ref mut data) => data.path = vec!(), _ => {} }; referer.fragment = None; referer.query = None; ...
new
identifier_name
cors.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/. */ //! A partial implementation of CORS //! For now this library is XHR-specific. //! For stuff involving `<img>`, `<...
let mut req = CORSRequest::new(referer, destination, mode, method, headers); req.preflight_flag =!is_simple_method(&req.method) || mode == RequestMode::ForcedPreflight; if req.headers.iter().all(|h| is_simple_header(&h)) { req.preflight_flag = true; ...
// TODO: If the request's same origin data url flag is set (which isn't the case for XHR) // we can fetch a data URL normally. about:blank can also be fetched by XHR "http" | "https" => {
random_line_split
issue-1451.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 ...
{ f: @fn() }; fn fooS(t: S) { } fn fooT(t: T) { } fn bar() { } fn main() { let x: @fn() = bar; fooS(S {f: x}); fooS(S {f: bar}); let x: @fn() = bar; fooT(T {f: x}); fooT(T {f: bar}); }
S
identifier_name
issue-1451.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 ...
// xfail-test struct T { f: @fn() }; struct S { f: @fn() }; fn fooS(t: S) { } fn fooT(t: T) { } fn bar() { } fn main() { let x: @fn() = bar; fooS(S {f: x}); fooS(S {f: bar}); let x: @fn() = bar; fooT(T {f: x}); fooT(T {f: bar}); }
random_line_split
issue-1451.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 bar() { } fn main() { let x: @fn() = bar; fooS(S {f: x}); fooS(S {f: bar}); let x: @fn() = bar; fooT(T {f: x}); fooT(T {f: bar}); }
{ }
identifier_body
webglshaderprecisionformat.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLSh...
} fn Precision(self) -> i32 { self.precision } }
} fn RangeMax(self) -> i32 { self.range_max
random_line_split
webglshaderprecisionformat.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLSh...
(range_min: i32, range_max: i32, precision: i32) -> WebGLShaderPrecisionFormat { WebGLShaderPrecisionFormat { reflector_: Reflector::new(), range_min: range_min, range_max: range_max, precision: precision, } } pub fn new(global: GlobalRef, ...
new_inherited
identifier_name
webglshaderprecisionformat.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLSh...
pub fn new(global: GlobalRef, range_min: i32, range_max: i32, precision: i32) -> Temporary<WebGLShaderPrecisionFormat> { reflect_dom_object( box WebGLShaderPrecisionFormat::new_inherited(range_min, range_max, precision), global, ...
{ WebGLShaderPrecisionFormat { reflector_: Reflector::new(), range_min: range_min, range_max: range_max, precision: precision, } }
identifier_body
camera.rs
// See LICENSE file for copyright and license details. use std::f32::consts::{PI}; use num::{Float}; use cgmath::{perspective, rad, Matrix4, Vector, Vector3, Rad}; use common::types::{Size2, ZFloat}; use common::misc::{clamp}; use zgl::{Zgl}; use types::{WorldPos}; pub struct
{ x_angle: Rad<ZFloat>, z_angle: Rad<ZFloat>, pos: WorldPos, max_pos: WorldPos, zoom: ZFloat, projection_mat: Matrix4<ZFloat>, } fn get_projection_mat(win_size: &Size2) -> Matrix4<ZFloat> { let fov = rad(PI / 4.0); let ratio = win_size.w as ZFloat / win_size.h as ZFloat; let displa...
Camera
identifier_name
camera.rs
// See LICENSE file for copyright and license details. use std::f32::consts::{PI}; use num::{Float}; use cgmath::{perspective, rad, Matrix4, Vector, Vector3, Rad}; use common::types::{Size2, ZFloat}; use common::misc::{clamp}; use zgl::{Zgl}; use types::{WorldPos}; pub struct Camera { x_angle: Rad<ZFloat>, z_...
pub fn set_max_pos(&mut self, max_pos: WorldPos) { self.max_pos = max_pos; } pub fn change_zoom(&mut self, ratio: ZFloat) { self.zoom *= ratio; self.zoom = clamp(self.zoom, 10.0, 40.0); } pub fn get_z_angle(&self) -> &Rad<ZFloat> { &self.z_angle } pub fn ...
{ self.pos = pos; self.clamp_pos(); }
identifier_body
camera.rs
// See LICENSE file for copyright and license details. use std::f32::consts::{PI}; use num::{Float}; use cgmath::{perspective, rad, Matrix4, Vector, Vector3, Rad}; use common::types::{Size2, ZFloat}; use common::misc::{clamp}; use zgl::{Zgl}; use types::{WorldPos}; pub struct Camera { x_angle: Rad<ZFloat>, z_...
} fn clamp_pos(&mut self) { self.pos.v.x = clamp(self.pos.v.x, self.max_pos.v.x, 0.0); self.pos.v.y = clamp(self.pos.v.y, self.max_pos.v.y, 0.0); } pub fn set_pos(&mut self, pos: WorldPos) { self.pos = pos; self.clamp_pos(); } pub fn set_max_pos(&mut self, max_...
self.x_angle = clamp(self.x_angle, min, max);
random_line_split
borrowable.rs
use std::hash::Hash; use std::borrow::Borrow; use std::collections::HashMap; struct Borrowable<K, V> { table: HashMap<K, V>, } impl<K, V> Borrowable<K, V> where K: Eq + Hash, { fn get<Q:?Sized>(&self, key: &Q) -> Option<&V>
{ self.table.get(key) } fn new() -> Borrowable<K, V> { Borrowable { table: HashMap::<K, V>::new(), } } fn insert<Q:?Sized>(&mut self, key: &Q, value: V) where Q: ToOwned<Owned = K>, K: Borrow<Q>, { self.table.insert(key.to_owned()...
where K: Borrow<Q>, Q: Eq + Hash,
random_line_split
borrowable.rs
use std::hash::Hash; use std::borrow::Borrow; use std::collections::HashMap; struct Borrowable<K, V> { table: HashMap<K, V>, } impl<K, V> Borrowable<K, V> where K: Eq + Hash, { fn get<Q:?Sized>(&self, key: &Q) -> Option<&V> where K: Borrow<Q>, Q: Eq + Hash, { self.table.get...
<Q:?Sized>(&mut self, key: &Q, value: V) where Q: ToOwned<Owned = K>, K: Borrow<Q>, { self.table.insert(key.to_owned(), value); } } pub fn demo_borrowable() { let mut b = Borrowable::<String, &str>::new(); b.insert("name", "Jack"); b.insert("age", "23"); b.insert("se...
insert
identifier_name
borrowable.rs
use std::hash::Hash; use std::borrow::Borrow; use std::collections::HashMap; struct Borrowable<K, V> { table: HashMap<K, V>, } impl<K, V> Borrowable<K, V> where K: Eq + Hash, { fn get<Q:?Sized>(&self, key: &Q) -> Option<&V> where K: Borrow<Q>, Q: Eq + Hash, { self.table.get...
fn insert<Q:?Sized>(&mut self, key: &Q, value: V) where Q: ToOwned<Owned = K>, K: Borrow<Q>, { self.table.insert(key.to_owned(), value); } } pub fn demo_borrowable() { let mut b = Borrowable::<String, &str>::new(); b.insert("name", "Jack"); b.insert("age", "23"); ...
{ Borrowable { table: HashMap::<K, V>::new(), } }
identifier_body
utils.rs
//! Utility functions use std::{ io, time::{Duration, Instant}, }; use futures::{Async, Future, Poll}; use tokio::timer::Delay; use tokio_io::{ io::{copy, Copy}, try_nb, AsyncRead, AsyncWrite, }; use super::BUFFER_SIZE; /// Copies all data from `r` to `w`, abort if timeout reaches pub fn cop...
fn read_or_set_timeout(&mut self) -> io::Result<usize> { // First, return if timeout self.try_poll_timeout()?; // Then, unset the previous timeout self.clear_timer(); match self.r.as_mut().unwrap().read(&mut self.buf) { Ok(n) => Ok(n), Err(e) => { ...
random_line_split
utils.rs
//! Utility functions use std::{ io, time::{Duration, Instant}, }; use futures::{Async, Future, Poll}; use tokio::timer::Delay; use tokio_io::{ io::{copy, Copy}, try_nb, AsyncRead, AsyncWrite, }; use super::BUFFER_SIZE; /// Copies all data from `r` to `w`, abort if timeout reaches pub fn cop...
<R, W>(r: R, w: W, dur: Option<Duration>) -> CopyTimeoutOpt<R, W> where R: AsyncRead, W: AsyncWrite, { match dur { Some(d) => CopyTimeoutOpt::CopyTimeout(copy_timeout(r, w, d)), None => CopyTimeoutOpt::Copy(copy(r, w)), } } /// Copies all data from `R` to `W` pub enum CopyTimeoutOpt<R: ...
copy_timeout_opt
identifier_name
utils.rs
//! Utility functions use std::{ io, time::{Duration, Instant}, }; use futures::{Async, Future, Poll}; use tokio::timer::Delay; use tokio_io::{ io::{copy, Copy}, try_nb, AsyncRead, AsyncWrite, }; use super::BUFFER_SIZE; /// Copies all data from `r` to `w`, abort if timeout reaches pub fn cop...
/// Copies all data from `R` to `W` pub enum CopyTimeoutOpt<R: AsyncRead, W: AsyncWrite> { Copy(Copy<R, W>), CopyTimeout(CopyTimeout<R, W>), } impl<R: AsyncRead, W: AsyncWrite> Future for CopyTimeoutOpt<R, W> { type Error = io::Error; type Item = (u64, R, W); fn poll(&mut self) -> Poll<Self::Ite...
{ match dur { Some(d) => CopyTimeoutOpt::CopyTimeout(copy_timeout(r, w, d)), None => CopyTimeoutOpt::Copy(copy(r, w)), } }
identifier_body
multibyte.rs
0xC1. These 2-byte sequences are disallowed in UTF-8, //! because they would form a duplicate encoding for the the 1-byte //! ASCII range. //! //! Due to these specialties, we cannot treat Emacs strings as Rust //! `&str`, and this module regrettably contains adapted copies of //! stretches of `std::str` function...
if head < 0xC2 { (cp | 0x3F_FF80, 2) } else { (cp, 2) } } else if head & 0x10 == 0 { ( ((head & 0x0F) << 12) | ((slice[1] as Codepoint & 0x3F) << 6) | (slice[2] as Codepoint & 0x3F), 3, ) } else if head & 0x0...
let head = slice[0] as Codepoint; if head & 0x80 == 0 { (head, 1) } else if head & 0x20 == 0 { let cp = ((head & 0x1F) << 6) | (slice[1] as Codepoint & 0x3F);
random_line_split
multibyte.rs
xC1. These 2-byte sequences are disallowed in UTF-8, //! because they would form a duplicate encoding for the the 1-byte //! ASCII range. //! //! Due to these specialties, we cannot treat Emacs strings as Rust //! `&str`, and this module regrettably contains adapted copies of //! stretches of `std::str` functions....
(&self) -> &mut [u8] { unsafe { slice::from_raw_parts_mut(self.data as *mut u8, self.len_bytes() as usize) } } #[inline] pub fn byte_at(&self, index: ptrdiff_t) -> u8 { unsafe { *self.const_data_ptr().offset(index) } } } pub struct LispStringRefIterator<'a> { string_ref: &'a LispSt...
as_mut_slice
identifier_name
multibyte.rs
xC1. These 2-byte sequences are disallowed in UTF-8, //! because they would form a duplicate encoding for the the 1-byte //! ASCII range. //! //! Due to these specialties, we cannot treat Emacs strings as Rust //! `&str`, and this module regrettably contains adapted copies of //! stretches of `std::str` functions....
/// Same as the `BYTE8_TO_CHAR` macro. #[inline] pub fn raw_byte_codepoint(byte: c_uchar) -> Codepoint { if byte >= 0x80 { byte as Codepoint + 0x3F_FF00 } else { byte as Codepoint } } /// Same as the `CHAR_TO_BYTE8` macro. #[inline] pub fn raw_byte_from_codepoint(cp: Codepoint) -> c_uchar...
{ let slice = unsafe { slice::from_raw_parts(ptr, len as usize) }; slice.iter().fold(0, |total, &byte| { let n = if byte < 0x80 { 1 } else { 2 }; total.checked_add(n).unwrap_or_else(|| string_overflow()) }) }
identifier_body
multibyte.rs
xC1. These 2-byte sequences are disallowed in UTF-8, //! because they would form a duplicate encoding for the the 1-byte //! ASCII range. //! //! Due to these specialties, we cannot treat Emacs strings as Rust //! `&str`, and this module regrettably contains adapted copies of //! stretches of `std::str` functions....
else if slice[0] == 0xF8 && slice[1] & 0xF0 == 0x80 { Some(5) } else { None } } /// Same as the `STRING_CHAR_ADVANCE` macro. #[inline] pub fn multibyte_char_at(slice: &[c_uchar]) -> (Codepoint, usize) { let head = slice[0] as Codepoint; if head & 0x80 == 0 { (head, 1) } els...
{ None }
conditional_block
static_mut.rs
/** `Internal variability` for [`Lazystatic`](https://crates.io/crates/lazy_static) ## Example: ### On Cargo.toml: ```toml lazy_static = "^0.2.8" stderr = "0.8.1" ``` ### On Code: ```rust #[macro_use] extern crate lazy_static; extern crate stderr; use stderr::StaticMut; lazy_static!{ static ref STRING : Static...
// read it #[inline] #[allow(unknown_lints,should_implement_trait)] pub fn as_ref(&self) -> &T { unsafe { self.0.get().as_ref().unwrap() } } /// write it #[allow(unknown_lints,mut_from_ref)] #[inline] pub fn as_mut(&self) -> &mut T { unsafe { self.0.get().as_mut().unwrap(...
StaticMut(UnsafeCell::new(value)) } /
identifier_body
static_mut.rs
/** `Internal variability` for [`Lazystatic`](https://crates.io/crates/lazy_static) ## Example: ### On Cargo.toml: ```toml lazy_static = "^0.2.8" stderr = "0.8.1" ``` ### On Code: ```rust #[macro_use] extern crate lazy_static; extern crate stderr; use stderr::StaticMut; lazy_static!{ static ref STRING : Static...
use std::cell::UnsafeCell; unsafe impl<T> Sync for StaticMut<T> {} impl<T> StaticMut<T> { #[inline] pub fn new(value: T) -> Self { StaticMut(UnsafeCell::new(value)) } /// read it #[inline] #[allow(unknown_lints,should_implement_trait)] pub fn as_ref(&self) -> &T { unsafe...
*/ #[derive(Debug)] pub struct StaticMut<T>(UnsafeCell<T>); use std::marker::Sync;
random_line_split
static_mut.rs
/** `Internal variability` for [`Lazystatic`](https://crates.io/crates/lazy_static) ## Example: ### On Cargo.toml: ```toml lazy_static = "^0.2.8" stderr = "0.8.1" ``` ### On Code: ```rust #[macro_use] extern crate lazy_static; extern crate stderr; use stderr::StaticMut; lazy_static!{ static ref STRING : Static...
safeCell<T>); use std::marker::Sync; use std::cell::UnsafeCell; unsafe impl<T> Sync for StaticMut<T> {} impl<T> StaticMut<T> { #[inline] pub fn new(value: T) -> Self { StaticMut(UnsafeCell::new(value)) } /// read it #[inline] #[allow(unknown_lints,should_implement_trait)] pub f...
Mut<T>(Un
identifier_name
compare.rs
#![crate_id="compare#0.1"] #![crate_type="bin"] extern crate bancnova; use std::os; use bancnova::syntax::bscode; use bancnova::syntax::tokenize; use bancnova::syntax::tokenize::Tokenizer; use bancnova::syntax::tree::Tree; use std::io::IoResult; use std::cmp::min; mod util; fn main() { let args = os::args(); ...
(filename1: &str, filename2: &str) -> IoResult<()> { let file1 = match util::open_input(filename1) { Ok(p) => p, Err(e) => { return Err(e); }, }; let file2 = match util::open_input(filename2) { Ok(p) => p, Err(e) => { return Err(e); }, }; let mut tokenizer1 = tokeniz...
compare_files
identifier_name
compare.rs
#![crate_id="compare#0.1"] #![crate_type="bin"] extern crate bancnova; use std::os; use bancnova::syntax::bscode; use bancnova::syntax::tokenize; use bancnova::syntax::tokenize::Tokenizer; use bancnova::syntax::tree::Tree; use std::io::IoResult; use std::cmp::min; mod util; fn main() { let args = os::args(); ...
impl<'a> ComparisonReporter<'a> { fn new(filename1: &'a str, filename2: &'a str) -> ComparisonReporter<'a> { ComparisonReporter::<'a> { filename1: filename1, filename2: filename2, count: 0 } } fn report_general(&mut self, line: uint, message1: &str, message2: &str) { println!("{}:{}: {}", ...
filename2: &'a str, count: uint, }
random_line_split