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 |
|---|---|---|---|---|
perlin_2d_colors.rs | #![feature(old_path)]
extern crate image;
extern crate noise; | use std::num::Float;
fn to_color(value: f64, factor: f64) -> u8 {
let mut v = value.abs();
if v > 255.0 {
v = 255.0
}
(v * factor) as u8
}
fn main() {
let amp = 255.0;
let f = 0.01;
let noise_r = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_g = new_perlin_noise_2d... | extern crate rand;
use image::{ImageBuffer, Rgb};
use noise::Noise;
use noise::blocks::new_perlin_noise_2d; | random_line_split |
perlin_2d_colors.rs | #![feature(old_path)]
extern crate image;
extern crate noise;
extern crate rand;
use image::{ImageBuffer, Rgb};
use noise::Noise;
use noise::blocks::new_perlin_noise_2d;
use std::num::Float;
fn to_color(value: f64, factor: f64) -> u8 {
let mut v = value.abs();
if v > 255.0 {
v = 255.0
}
(v * f... | () {
let amp = 255.0;
let f = 0.01;
let noise_r = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_g = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_b = new_perlin_noise_2d(rand::random(), amp, f, 6);
let image = ImageBuffer::from_fn(128, 128, |x: u32, y: u32| {
le... | main | identifier_name |
perlin_2d_colors.rs | #![feature(old_path)]
extern crate image;
extern crate noise;
extern crate rand;
use image::{ImageBuffer, Rgb};
use noise::Noise;
use noise::blocks::new_perlin_noise_2d;
use std::num::Float;
fn to_color(value: f64, factor: f64) -> u8 |
fn main() {
let amp = 255.0;
let f = 0.01;
let noise_r = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_g = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_b = new_perlin_noise_2d(rand::random(), amp, f, 6);
let image = ImageBuffer::from_fn(128, 128, |x: u32, y: u32| {
... | {
let mut v = value.abs();
if v > 255.0 {
v = 255.0
}
(v * factor) as u8
} | identifier_body |
perlin_2d_colors.rs | #![feature(old_path)]
extern crate image;
extern crate noise;
extern crate rand;
use image::{ImageBuffer, Rgb};
use noise::Noise;
use noise::blocks::new_perlin_noise_2d;
use std::num::Float;
fn to_color(value: f64, factor: f64) -> u8 {
let mut v = value.abs();
if v > 255.0 |
(v * factor) as u8
}
fn main() {
let amp = 255.0;
let f = 0.01;
let noise_r = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_g = new_perlin_noise_2d(rand::random(), amp, f, 6);
let noise_b = new_perlin_noise_2d(rand::random(), amp, f, 6);
let image = ImageBuffer::from_fn(128, ... | {
v = 255.0
} | conditional_block |
main.rs | #![feature(plugin, rustc_private)]
#![plugin(docopt_macros)]
extern crate cargo;
extern crate docopt;
extern crate graphviz;
extern crate rustc_serialize;
use cargo::core::{Resolve, SourceId, PackageId};
use graphviz as dot;
use std::borrow::{Cow};
use std::convert::Into;
use std::env;
use std::io;
use std::io::Write... | cargo dot --help
Options:
-h, --help Show this message
-V, --version Print version info and exit
--lock-file=FILE Specify location of input file, default \"Cargo.lock\"
--dot-file=FILE Output to file, default prints to stdout
--source-labels Use sources for the label ins... |
Usage: cargo dot [options] | random_line_split |
main.rs | #![feature(plugin, rustc_private)]
#![plugin(docopt_macros)]
extern crate cargo;
extern crate docopt;
extern crate graphviz;
extern crate rustc_serialize;
use cargo::core::{Resolve, SourceId, PackageId};
use graphviz as dot;
use std::borrow::{Cow};
use std::convert::Into;
use std::env;
use std::io;
use std::io::Write... |
let proj_dir = lock_path.parent().unwrap(); // TODO: check for None
let src_id = SourceId::for_path(&proj_dir).unwrap();
let resolved = cargo::ops::load_lockfile(&lock_path, &src_id).unwrap()
.expect("Lock file not found.");
let mut graph = Graph::with_root(resolved.root(), source_labels);
... | {
let mut argv: Vec<String> = env::args().collect();
if argv.len() > 0 {
argv[0] = "cargo".to_string();
}
let flags: Flags = Flags::docopt()
// cargo passes the exe name first, so we skip it
.argv(argv.into_iter())
... | identifier_body |
main.rs | #![feature(plugin, rustc_private)]
#![plugin(docopt_macros)]
extern crate cargo;
extern crate docopt;
extern crate graphviz;
extern crate rustc_serialize;
use cargo::core::{Resolve, SourceId, PackageId};
use graphviz as dot;
use std::borrow::{Cow};
use std::convert::Into;
use std::env;
use std::io;
use std::io::Write... | (&self, &(s, _): &Ed) -> Nd { s }
fn target(&self, &(_, t): &Ed) -> Nd { t }
}
| source | identifier_name |
main.rs | extern crate rand;
use rand::Rng;
fn | () {
loop {
let (player_one_score, player_two_score) = roll_for_both_players();
if player_one_score!= player_two_score {
if player_one_score > player_two_score {
println!("Player 1 wins!");
} else {
println!("Player 2 wins!");
}
... | main | identifier_name |
main.rs | extern crate rand;
use rand::Rng;
fn main() {
loop {
let (player_one_score, player_two_score) = roll_for_both_players();
if player_one_score!= player_two_score |
}
}
fn roll_for_both_players() -> (i32, i32) {
let mut player_one_score = 0;
let mut player_two_score = 0;
for _ in 0..3 {
let roll_for_player_one = rand::thread_rng().gen_range(1, 7);
let roll_for_player_two = rand::thread_rng().gen_range(1, 7);
println!("Player one rolled {... | {
if player_one_score > player_two_score {
println!("Player 1 wins!");
} else {
println!("Player 2 wins!");
}
return;
} | conditional_block |
main.rs | extern crate rand;
use rand::Rng;
fn main() {
loop {
let (player_one_score, player_two_score) = roll_for_both_players();
if player_one_score!= player_two_score {
if player_one_score > player_two_score {
println!("Player 1 wins!");
} else { | }
}
}
fn roll_for_both_players() -> (i32, i32) {
let mut player_one_score = 0;
let mut player_two_score = 0;
for _ in 0..3 {
let roll_for_player_one = rand::thread_rng().gen_range(1, 7);
let roll_for_player_two = rand::thread_rng().gen_range(1, 7);
println!("Player one... | println!("Player 2 wins!");
}
return; | random_line_split |
main.rs | extern crate rand;
use rand::Rng;
fn main() |
fn roll_for_both_players() -> (i32, i32) {
let mut player_one_score = 0;
let mut player_two_score = 0;
for _ in 0..3 {
let roll_for_player_one = rand::thread_rng().gen_range(1, 7);
let roll_for_player_two = rand::thread_rng().gen_range(1, 7);
println!("Player one rolled {}", roll... | {
loop {
let (player_one_score, player_two_score) = roll_for_both_players();
if player_one_score != player_two_score {
if player_one_score > player_two_score {
println!("Player 1 wins!");
} else {
println!("Player 2 wins!");
}
... | identifier_body |
graphs.rs | extern crate rand;
extern crate timely;
extern crate differential_dataflow;
use std::rc::Rc;
use rand::{Rng, SeedableRng, StdRng};
use timely::dataflow::*;
use differential_dataflow::input::Input;
use differential_dataflow::Collection;
use differential_dataflow::operators::*;
use differential_dataflow::trace::Trace... |
fn bfs<G: Scope<Timestamp = ()>> (
graph: &mut TraceHandle,
roots: Collection<G, Node>
) -> Collection<G, (Node, u32)> {
let graph = graph.import(&roots.scope());
let roots = roots.map(|r| (r,0));
roots.iterate(|inner| {
let graph = graph.enter(&inner.scope());
let roots = root... | {
let graph = graph.import(&roots.scope());
roots.iterate(|inner| {
let graph = graph.enter(&inner.scope());
let roots = roots.enter(&inner.scope());
// let reach = inner.concat(&roots).distinct_total().arrange_by_self();
// graph.join_core(&reach, |_src,&dst,&()| Some(dst))
... | identifier_body |
graphs.rs | extern crate rand;
extern crate timely;
extern crate differential_dataflow;
use std::rc::Rc;
use rand::{Rng, SeedableRng, StdRng};
use timely::dataflow::*;
use differential_dataflow::input::Input;
use differential_dataflow::Collection;
use differential_dataflow::operators::*;
use differential_dataflow::trace::Trace... | let (graph_input, graph) = scope.new_collection();
let graph_indexed = graph.arrange_by_key();
// let graph_indexed = graph.arrange_by_key();
(graph_input, graph_indexed.trace)
});
let seed: &[_] = &[1, 2, 3, index];
let mut rng1: StdRng = Seedabl... | let index = worker.index();
let peers = worker.peers();
let timer = ::std::time::Instant::now();
let (mut graph, mut trace) = worker.dataflow(|scope| { | random_line_split |
graphs.rs | extern crate rand;
extern crate timely;
extern crate differential_dataflow;
use std::rc::Rc;
use rand::{Rng, SeedableRng, StdRng};
use timely::dataflow::*;
use differential_dataflow::input::Input;
use differential_dataflow::Collection;
use differential_dataflow::operators::*;
use differential_dataflow::trace::Trace... | <G: Scope<Timestamp = ()>> (
graph: &mut TraceHandle,
roots: Collection<G, Node>
) -> Collection<G, Node> {
let graph = graph.import(&roots.scope());
roots.iterate(|inner| {
let graph = graph.enter(&inner.scope());
let roots = roots.enter(&inner.scope());
// let reach = inner... | reach | identifier_name |
graphs.rs | extern crate rand;
extern crate timely;
extern crate differential_dataflow;
use std::rc::Rc;
use rand::{Rng, SeedableRng, StdRng};
use timely::dataflow::*;
use differential_dataflow::input::Input;
use differential_dataflow::Collection;
use differential_dataflow::operators::*;
use differential_dataflow::trace::Trace... |
roots.close();
while worker.step() { }
if index == 0 { println!("{:?}\tbfs complete", timer.elapsed()); }
}).unwrap();
}
// use differential_dataflow::trace::implementations::ord::OrdValSpine;
use differential_dataflow::operators::arrange::TraceAgent;
type TraceHandle = TraceAgent<Node,... | { roots.insert(0); } | conditional_block |
sha256.rs | self) -> (Self, Self);
}
impl ToBits for u64 {
fn to_bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// overflow.
fn add_bytes_to_bits<T: Int + ToBits>(bits: T, bytes: T) -> T {
let (new_h... |
fn sigma1(x: u32) -> u32 {
((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10)
}
let mut a = self.h0;
let mut b = self.h1;
let mut c = self.h2;
let mut d = self.h3;
let mut e = self.h4;
let mut f = self.h5;
let mut g = self.... | random_line_split | |
sha256.rs | ) -> (Self, Self);
}
impl ToBits for u64 {
fn to_bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// overflow.
fn add_bytes_to_bits<T: Int + ToBits>(bits: T, bytes: T) -> T |
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it
/// must be processed. The input() method takes care of processing and then clearing the buffer
/// automatically. However, other methods do not and require the caller to process the buffer. Any
/// method that modifie... | {
let (new_high_bits, new_low_bits) = bytes.to_bits();
if new_high_bits > Int::zero() {
panic!("numeric overflow occurred.")
}
match bits.checked_add(new_low_bits) {
Some(x) => return x,
None => panic!("numeric overflow occurred.")
}
} | identifier_body |
sha256.rs | _idx;
if input.len() >= buffer_remaining {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, size),
&input[0..buffer_remaining]);
self.buffer_idx = 0;
func(&self.buffer);
i += buffer_remaini... | test_1million_random_sha256 | identifier_name | |
test_apt.rs |
extern crate woko;
// use std::io::prelude::*;
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::Read;
use std::path::Path;
//use std::collections::HashMap;
use woko::apt;
fn | () -> String {
let mut f = File::open(Path::new("tests/apt.out")).unwrap();
let mut s = String::new();
f.read_to_string(&mut s).ok();
return s;
}
#[test]
fn test_woko_apt() {
let apts = apt::parse_from_string(&read()).unwrap();
let l122 = apts.get(121).unwrap... | read | identifier_name |
test_apt.rs | extern crate woko; | #[cfg(test)]
mod tests {
use std::fs::File;
use std::io::Read;
use std::path::Path;
//use std::collections::HashMap;
use woko::apt;
fn read() -> String {
let mut f = File::open(Path::new("tests/apt.out")).unwrap();
let mut s = String::new();
f.read_to_string(&mut s).ok()... |
// use std::io::prelude::*;
| random_line_split |
test_apt.rs |
extern crate woko;
// use std::io::prelude::*;
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::Read;
use std::path::Path;
//use std::collections::HashMap;
use woko::apt;
fn read() -> String {
let mut f = File::open(Path::new("tests/apt.out")).unwrap();
let mut s = ... |
}
| {
let apts = apt::parse_from_string(&read()).unwrap();
let l122 = apts.get(121).unwrap();
assert_eq!(132, apts.len());
assert_eq!("http://archive.ubuntu.com/ubuntu/pool/main/r/rename/rename_0.20-4_all.deb", l122.url);
assert_eq!("rename_0.20-4_all.deb", l122.name);
assert... | identifier_body |
to_toml.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | (&self, h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> RenderResult<()> {
let param = h.param(0)
.ok_or_else(|| RenderError::new("Expected 1 parameter for \"toToml\""))?
.value();
let bytes = toml::ser::to_vec(¶m)
.map_err(|e| RenderError::new(format!("Can't ... | call | identifier_name |
to_toml.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | .value();
let bytes = toml::ser::to_vec(¶m)
.map_err(|e| RenderError::new(format!("Can't serialize parameter to TOML: {}", e)))?;
rc.writer.write_all(bytes.as_ref())?;
Ok(())
}
}
pub static TO_TOML: ToTomlHelper = ToTomlHelper; | impl HelperDef for ToTomlHelper {
fn call(&self, h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> RenderResult<()> {
let param = h.param(0)
.ok_or_else(|| RenderError::new("Expected 1 parameter for \"toToml\""))? | random_line_split |
timer.rs | use libc::{uint32_t, c_void};
use std::mem;
use sys::timer as ll;
pub fn get_ticks() -> u32 {
unsafe { ll::SDL_GetTicks() }
}
pub fn get_performance_counter() -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn get_performance_frequency() -> u64 {
unsafe { ll::SDL_GetPerformanceFrequency() }
}
... |
}
}
extern "C" fn c_timer_callback(_interval: u32, param: *const c_void) -> uint32_t {
unsafe {
let f: *const Box<Fn() -> u32> = mem::transmute(param);
(*f)() as uint32_t
}
}
#[cfg(test)] use std::sync::{StaticMutex, MUTEX_INIT};
#[cfg(test)] static TIMER_INIT_LOCK: StaticMutex = MUTEX_... | {
println!("error dropping timer {}, maybe already removed.", self.raw);
} | conditional_block |
timer.rs | use libc::{uint32_t, c_void};
use std::mem;
use sys::timer as ll;
pub fn get_ticks() -> u32 {
unsafe { ll::SDL_GetTicks() }
}
pub fn get_performance_counter() -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn get_performance_frequency() -> u64 {
unsafe { ll::SDL_GetPerformanceFrequency() }
}
... |
#[cfg(test)] use std::sync::{StaticMutex, MUTEX_INIT};
#[cfg(test)] static TIMER_INIT_LOCK: StaticMutex = MUTEX_INIT;
#[test]
fn test_timer_runs_multiple_times() {
use std::sync::{Arc, Mutex};
let _running = TIMER_INIT_LOCK.lock().unwrap();
::sdl::init(::sdl::INIT_TIMER).unwrap();
let local_num = A... | {
unsafe {
let f: *const Box<Fn() -> u32> = mem::transmute(param);
(*f)() as uint32_t
}
} | identifier_body |
timer.rs | use libc::{uint32_t, c_void};
use std::mem;
use sys::timer as ll;
pub fn get_ticks() -> u32 {
unsafe { ll::SDL_GetTicks() }
}
pub fn get_performance_counter() -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn get_performance_frequency() -> u64 {
unsafe { ll::SDL_GetPerformanceFrequency() }
}
... | (&mut self) {
let ret = unsafe { ll::SDL_RemoveTimer(self.raw) };
if ret!= 1 {
println!("error dropping timer {}, maybe already removed.", self.raw);
}
}
}
extern "C" fn c_timer_callback(_interval: u32, param: *const c_void) -> uint32_t {
unsafe {
let f: *const Box<... | drop | identifier_name |
timer.rs | use libc::{uint32_t, c_void};
use std::mem;
use sys::timer as ll;
pub fn get_ticks() -> u32 {
unsafe { ll::SDL_GetTicks() }
}
pub fn get_performance_counter() -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn get_performance_frequency() -> u64 {
unsafe { ll::SDL_GetPerformanceFrequency() }
}
... | impl<'a> Drop for Timer<'a> {
fn drop(&mut self) {
let ret = unsafe { ll::SDL_RemoveTimer(self.raw) };
if ret!= 1 {
println!("error dropping timer {}, maybe already removed.", self.raw);
}
}
}
extern "C" fn c_timer_callback(_interval: u32, param: *const c_void) -> uint32_t {... | #[unsafe_destructor] | random_line_split |
by-move-pattern-binding.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 ... | {
x: E
}
fn f(x: String) {}
fn main() {
let s = S { x: E::Bar("hello".to_string()) };
match &s.x {
&E::Foo => {}
&E::Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move
};
match &s.x {
&E::Foo => {}
&E::Bar(ref identifier) => println!("{}", *identifier)... | S | identifier_name |
by-move-pattern-binding.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 ... | }
struct S {
x: E
}
fn f(x: String) {}
fn main() {
let s = S { x: E::Bar("hello".to_string()) };
match &s.x {
&E::Foo => {}
&E::Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move
};
match &s.x {
&E::Foo => {}
&E::Bar(ref identifier) => println!("{}", *... | enum E {
Foo,
Bar(String) | random_line_split |
by-move-pattern-binding.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 s = S { x: E::Bar("hello".to_string()) };
match &s.x {
&E::Foo => {}
&E::Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move
};
match &s.x {
&E::Foo => {}
&E::Bar(ref identifier) => println!("{}", *identifier)
};
}
| {} | identifier_body |
hgid.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#[cfg(any(test, feature = "for-tests"))]
use std::collections::HashSet;
use std::io::Read;
use std::io::Write;
use std::io::{self};
#[cfg(... | () {
HgId::from_slice(&[0u8; 25]).expect_err("bad slice length");
}
#[test]
fn test_serde_with_using_cbor() {
// Note: this test is for CBOR. Other serializers like mincode
// or Thrift would have different backwards compatibility!
use serde_cbor::de::from_slice as decode;
... | test_incorrect_length | identifier_name |
hgid.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#[cfg(any(test, feature = "for-tests"))]
use std::collections::HashSet;
use std::io::Read;
use std::io::Write;
use std::io::{self};
#[cfg(... |
#[cfg(any(test, feature = "for-tests"))]
pub fn random(rng: &mut dyn RngCore) -> Self {
let mut bytes = [0; HgId::len()];
rng.fill_bytes(&mut bytes);
loop {
let hgid = HgId::from(&bytes);
if!hgid.is_null() {
return hgid;
}
}
... | {
// Parents must be hashed in sorted order.
let (p1, p2) = match parents.into_nodes() {
(p1, p2) if p1 > p2 => (p2, p1),
(p1, p2) => (p1, p2),
};
let mut hasher = Sha1::new();
hasher.input(p1.as_ref());
hasher.input(p2.as_ref());
hasher.i... | identifier_body |
hgid.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#[cfg(any(test, feature = "for-tests"))]
use std::collections::HashSet;
use std::io::Read;
use std::io::Write;
use std::io::{self};
#[cfg(... |
}
nodes
}
}
impl<'a> From<&'a [u8; HgId::len()]> for HgId {
fn from(bytes: &[u8; HgId::len()]) -> HgId {
HgId::from_byte_array(bytes.clone())
}
}
pub trait WriteHgIdExt {
/// Write a ``HgId`` directly to a stream.
///
/// # Examples
///
/// ```
/// use type... | {
nodeset.insert(hgid.clone());
nodes.push(hgid);
} | conditional_block |
hgid.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#[cfg(any(test, feature = "for-tests"))]
use std::collections::HashSet;
use std::io::Read;
use std::io::Write;
use std::io::{self};
#[cfg(... |
use super::*;
#[test]
fn test_incorrect_length() {
HgId::from_slice(&[0u8; 25]).expect_err("bad slice length");
}
#[test]
fn test_serde_with_using_cbor() {
// Note: this test is for CBOR. Other serializers like mincode
// or Thrift would have different backwards compat... | mod tests {
use quickcheck::quickcheck;
use serde::Deserialize;
use serde::Serialize; | random_line_split |
matcher.rs | #![feature(test)]
extern crate rff;
extern crate test;
use test::Bencher;
use rff::matcher::matches;
#[bench]
fn bench_matches(b: &mut Bencher) {
b.iter(|| matches("amor", "app/models/order.rb"))
}
#[bench]
fn bench_matches_utf8(b: &mut Bencher) {
b.iter(|| matches("ß", "WEIẞ"))
}
#[bench]
fn bench_matches... | &mut Bencher) {
b.iter(|| matches("app/models", "app/models/order.rb"))
}
#[bench]
fn bench_matches_mixed_case(b: &mut Bencher) {
b.iter(|| matches("AMOr", "App/Models/Order.rb"))
}
#[bench]
fn bench_matches_multiple(b: &mut Bencher) {
b.iter(|| {
matches("amor", "app/models/order.rb");
ma... | h_matches_more_specific(b: | identifier_name |
matcher.rs | #![feature(test)]
extern crate rff;
extern crate test;
use test::Bencher;
use rff::matcher::matches;
#[bench]
fn bench_matches(b: &mut Bencher) {
b.iter(|| matches("amor", "app/models/order.rb"))
} | fn bench_matches_utf8(b: &mut Bencher) {
b.iter(|| matches("ß", "WEIẞ"))
}
#[bench]
fn bench_matches_mixed(b: &mut Bencher) {
b.iter(|| matches("abc", "abØ"))
}
#[bench]
fn bench_matches_more_specific(b: &mut Bencher) {
b.iter(|| matches("app/models", "app/models/order.rb"))
}
#[bench]
fn bench_matches_m... |
#[bench] | random_line_split |
matcher.rs | #![feature(test)]
extern crate rff;
extern crate test;
use test::Bencher;
use rff::matcher::matches;
#[bench]
fn bench_matches(b: &mut Bencher) {
b.iter(|| matches("amor", "app/models/order.rb"))
}
#[bench]
fn bench_matches_utf8(b: &mut Bencher) {
b.iter(|| matches("ß", "WEIẞ"))
}
#[bench]
fn bench_matches... | bench]
fn bench_matches_eq(b: &mut Bencher) {
b.iter(|| {
matches("Gemfile", "Gemfile");
matches("gemfile", "Gemfile")
})
}
| b.iter(|| {
matches("amor", "app/models/order.rb");
matches("amor", "spec/models/order_spec.rb");
matches("amor", "other_garbage.rb");
matches("amor", "Gemfile");
matches("amor", "node_modules/test/a/thing.js");
matches("amor", "vendor/bundle/ruby/gem.rb")
})
}
#[ | identifier_body |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations ───────────────┐
// Std Library Option ──────────────────┘
// An integer division that doesn't `panic!`
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> {
if di | // Failure is represented as the `None` variant
None
} else {
// Result is wrapped in a `Some` variant
Some(dividend / divisor)
}
}
// This function handles a division that may not succeed
fn try_division(dividend: i32, divisor: i32) {
// `Option` values can be pattern matched,... | visor == 0 {
| identifier_name |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations ───────────────┐
// Std Library Option ──────────────────┘
// An integer division that doesn't `panic!`
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> {
if divisor == 0 {
// Failure is r... | // Binding `None` to a variable needs to be type annotated
let none: Option<i32> = None;
let _equivalent_none = None::<i32>;
let optional_float = Some(0f32);
// Unwrapping a `Some` variant will extract the value wrapped.
println!("{:?} unwraps to {:?}", optional_float, optional_float.unwrap())... | },
}
}
fn main() {
try_division(4, 2);
try_division(1, 0);
| conditional_block |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations ───────────────┐
// Std Library Option ──────────────────┘
// An integer division that doesn't `panic!`
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> {
if divisor == 0 {
// Failure is r... | }
}
// This function handles a division that may not succeed
fn try_division(dividend: i32, divisor: i32) {
// `Option` values can be pattern matched, just like other enums
match checked_division(dividend, divisor) {
None => println!("{} / {} failed!", dividend, divisor),
Some(quotient) => ... | // Result is wrapped in a `Some` variant
Some(dividend / divisor) | random_line_split |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations ───────────────┐
// Std Library Option ──────────────────┘
// An integer division that doesn't `panic!`
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> {
if divisor == 0 {
// Failure is r... | nding `None` to a variable needs to be type annotated
let none: Option<i32> = None;
let _equivalent_none = None::<i32>;
let optional_float = Some(0f32);
// Unwrapping a `Some` variant will extract the value wrapped.
println!("{:?} unwraps to {:?}", optional_float, optional_float.unwrap());
//... | match checked_division(dividend, divisor) {
None => println!("{} / {} failed!", dividend, divisor),
Some(quotient) => {
println!("{} / {} = {}", dividend, divisor, quotient)
},
}
}
fn main() {
try_division(4, 2);
try_division(1, 0);
// Bi | identifier_body |
regions-early-bound-used-in-bound-method.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
pub fn main() {
let b1 = Box { t: &3 };
assert_eq!(b1.add(b1), 6);
}
| {
*self.t + *g2.get()
} | identifier_body |
regions-early-bound-used-in-bound-method.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that you can use a fn lifetime parameter as part of
// the value for a type parameter in a bound.
trait GetRef<'a> {
fn get(&self) -> &'a in... | // 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 | random_line_split |
regions-early-bound-used-in-bound-method.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 ... | <'a> {
t: &'a int
}
impl<'a> Copy for Box<'a> {}
impl<'a> GetRef<'a> for Box<'a> {
fn get(&self) -> &'a int {
self.t
}
}
impl<'a> Box<'a> {
fn add<'b,G:GetRef<'b>>(&self, g2: G) -> int {
*self.t + *g2.get()
}
}
pub fn main() {
let b1 = Box { t: &3 };
assert_eq!(b1.add(b1)... | Box | identifier_name |
lib.rs | //! # r2d2-mysql
//! MySQL support for the r2d2 connection pool (Rust). see [`r2d2`](http://github.com/sfackler/r2d2.git) .
//!
//! #### Install
//! Just include another `[dependencies.*]` section into your Cargo.toml:
//!
//! ```toml
//! [dependencies.r2d2_mysql]
//! git = "https://github.com/outersky/r2d2-mysql"
//! ... | () {
let url = env::var("DATABASE_URL").unwrap();
let opts = Opts::from_url(&url).unwrap();
let builder = OptsBuilder::from_opts(opts);
let manager = MysqlConnectionManager::new(builder);
let pool = Arc::new(r2d2::Pool::builder().max_size(4).build(manager).unwrap());
let... | query_pool | identifier_name |
lib.rs | //! # r2d2-mysql
//! MySQL support for the r2d2 connection pool (Rust). see [`r2d2`](http://github.com/sfackler/r2d2.git) .
//!
//! #### Install
//! Just include another `[dependencies.*]` section into your Cargo.toml:
//!
//! ```toml
//! [dependencies.r2d2_mysql]
//! git = "https://github.com/outersky/r2d2-mysql"
//! ... | .unwrap();
let _ = conn.query("SELECT version()").map(|_: Vec<String>| ()).map_err(|err| {
println!("execute query error in line:{}! error: {:?}", line!(), err)
});
});
tasks.push(th);
}
for th in tasks {
... | {
let url = env::var("DATABASE_URL").unwrap();
let opts = Opts::from_url(&url).unwrap();
let builder = OptsBuilder::from_opts(opts);
let manager = MysqlConnectionManager::new(builder);
let pool = Arc::new(r2d2::Pool::builder().max_size(4).build(manager).unwrap());
let mu... | identifier_body |
lib.rs | //! # r2d2-mysql
//! MySQL support for the r2d2 connection pool (Rust). see [`r2d2`](http://github.com/sfackler/r2d2.git) .
//!
//! #### Install
//! Just include another `[dependencies.*]` section into your Cargo.toml:
//!
//! ```toml
//! [dependencies.r2d2_mysql]
//! git = "https://github.com/outersky/r2d2-mysql"
//! ... | //! ```
//!
#![doc(html_root_url = "http://outersky.github.io/r2d2-mysql/doc/v0.2.0/r2d2_mysql/")]
#![crate_name = "r2d2_mysql"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
pub extern crate mysql;
pub extern crate r2d2;
pub mod pool;
pub use pool::MysqlConnectionManager;
#[cfg(test)]
mod test {
use mysql::... | random_line_split | |
build.rs | #[cfg(feature = "with-syntex")]
mod inner {
extern crate syntex;
extern crate syntex_syntax as syntax;
use std::env;
use std::path::Path;
use self::syntax::codemap::Span;
use self::syntax::ext::base::{self, ExtCtxt};
use self::syntax::tokenstream::TokenTree;
pub fn main() {
le... | ($macro_name: ident, $name: ident) => {
fn $name<'cx>(
cx: &'cx mut ExtCtxt,
sp: Span,
tts: &[TokenTree],
) -> Box<base::MacResult + 'cx> {
syntax::ext::quote::$name(cx, sp, tts)
}... |
macro_rules! register_quote_macro { | random_line_split |
build.rs | #[cfg(feature = "with-syntex")]
mod inner {
extern crate syntex;
extern crate syntex_syntax as syntax;
use std::env;
use std::path::Path;
use self::syntax::codemap::Span;
use self::syntax::ext::base::{self, ExtCtxt};
use self::syntax::tokenstream::TokenTree;
pub fn main() {
le... |
}
fn main() {
inner::main();
}
| {} | identifier_body |
build.rs | #[cfg(feature = "with-syntex")]
mod inner {
extern crate syntex;
extern crate syntex_syntax as syntax;
use std::env;
use std::path::Path;
use self::syntax::codemap::Span;
use self::syntax::ext::base::{self, ExtCtxt};
use self::syntax::tokenstream::TokenTree;
pub fn | () {
let out_dir = env::var_os("OUT_DIR").unwrap();
let mut registry = syntex::Registry::new();
macro_rules! register_quote_macro {
($macro_name: ident, $name: ident) => {
fn $name<'cx>(
cx: &'cx mut ExtCtxt,
sp: Span,
... | main | identifier_name |
config.rs | //! Utilities for managing the configuration of the website.
//!
//! The configuration should contain values that I expect to change. This way, I can edit them all
//! in a single human-readable file instead of having to track down the values in the code.
use std::fs::File;
use std::io::prelude::*;
use std::path::Path... |
}
| {
let test_config = String::from(
r#"
---
resume_link: http://google.com
"#,
);
let expected_config = Config {
resume_link: Url::parse("http://google.com").unwrap(),
};
assert_eq!(
expected_config,
super::parse_config(test_config.as... | identifier_body |
config.rs | //! Utilities for managing the configuration of the website.
//!
//! The configuration should contain values that I expect to change. This way, I can edit them all
//! in a single human-readable file instead of having to track down the values in the code.
use std::fs::File;
use std::io::prelude::*;
use std::path::Path... | () {
let test_config = String::from(
r#"
---
resume_link: http://google.com
"#,
);
let expected_config = Config {
resume_link: Url::parse("http://google.com").unwrap(),
};
assert_eq!(
expected_config,
super::parse_config(test_config... | load_config | identifier_name |
config.rs | //! Utilities for managing the configuration of the website.
//!
//! The configuration should contain values that I expect to change. This way, I can edit them all
//! in a single human-readable file instead of having to track down the values in the code.
use std::fs::File; | use serde_yaml;
use url::Url;
use url_serde;
use crate::errors::*;
/// Configuration values for the website.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Config {
/// A link to a PDF copy of my Resume.
#[serde(with = "url_serde")]
pub resume_link: Url,
}
fn parse_config<R>(reader: R) -> Result<Con... | use std::io::prelude::*;
use std::path::Path;
use log::*;
use serde::Deserialize; | random_line_split |
os.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 ... | () -> u32 {
unsafe { c::GetCurrentProcessId() as u32 }
}
#[cfg(test)]
mod tests {
use io::Error;
use sys::c;
// tests `error_string` above
#[test]
fn ntstatus_error() {
const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001;
assert!(!Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FAC... | getpid | identifier_name |
os.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 ... | else {
joined.extend_from_slice(&v[..]);
}
}
Ok(OsStringExt::from_wide(&joined[..]))
}
impl fmt::Display for JoinPathsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"path segment contains `\"`".fmt(f)
}
}
impl StdError for JoinPathsError {
fn descripti... | {
joined.push(b'"' as u16);
joined.extend_from_slice(&v[..]);
joined.push(b'"' as u16);
} | conditional_block |
os.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 ... | };
return Some((
OsStringExt::from_wide(&s[..pos]),
OsStringExt::from_wide(&s[pos+1..]),
))
}
}
}
}
impl Drop for Env {
fn drop(&mut self) {
unsafe { c::FreeEnvironmentStringsW(self.base); }
... | {
loop {
unsafe {
if *self.cur == 0 { return None }
let p = &*self.cur as *const u16;
let mut len = 0;
while *p.offset(len) != 0 {
len += 1;
}
let s = slice::from_raw_parts(p, len as u... | identifier_body |
os.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 ... |
if!must_yield && in_progress.is_empty() {
None
} else {
Some(super::os2path(&in_progress))
}
}
}
#[derive(Debug)]
pub struct JoinPathsError;
pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
where I: Iterator<Item=T>, T: AsRef<OsStr>
{
l... | } else {
in_progress.push(b)
}
} | random_line_split |
base_props.rs | use crate::core::{Directedness, Graph};
use num_traits::{One, PrimInt, Unsigned, Zero};
use std::borrow::Borrow;
/// A graph where new vertices can be added
pub trait NewVertex: Graph
{
/// Adds a new vertex with the given weight to the graph.
/// Returns the id of the new vertex.
fn new_vertex_weighted(&mut self, ... |
}
rest_iter = iter.clone();
}
count
}
}
| {
self.edges_between(v2.borrow(), v.borrow())
.for_each(|_| inc());
} | conditional_block |
base_props.rs | use crate::core::{Directedness, Graph};
use num_traits::{One, PrimInt, Unsigned, Zero};
use std::borrow::Borrow;
/// A graph where new vertices can be added
pub trait NewVertex: Graph
{
/// Adds a new vertex with the given weight to the graph.
/// Returns the id of the new vertex.
fn new_vertex_weighted(&mut self, ... | /// - No vertices are introduced or removed.
///
/// ###`Err` properties:
///
/// - The graph is unchanged.
fn add_edge(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
) -> Result<(), ()>
where
Self::EdgeWeight: Default,
{
self.add_edge_weighted(source, sink, Self::Edg... | /// - Only the given edge is added to the graph.
/// - Existing edges are unchanged. | random_line_split |
base_props.rs | use crate::core::{Directedness, Graph};
use num_traits::{One, PrimInt, Unsigned, Zero};
use std::borrow::Borrow;
/// A graph where new vertices can be added
pub trait NewVertex: Graph
{
/// Adds a new vertex with the given weight to the graph.
/// Returns the id of the new vertex.
fn new_vertex_weighted(&mut self, ... |
}
/// A graph where vertices can be removed.
///
/// Removing a vertex may invalidate existing vertices.
pub trait RemoveVertex: Graph
{
/// Removes the given vertex from the graph, returning its weight.
/// If the vertex still has edges incident on it, they are also removed,
/// dropping their weights.
fn remove... | {
self.new_vertex_weighted(Self::VertexWeight::default())
} | identifier_body |
base_props.rs | use crate::core::{Directedness, Graph};
use num_traits::{One, PrimInt, Unsigned, Zero};
use std::borrow::Borrow;
/// A graph where new vertices can be added
pub trait NewVertex: Graph
{
/// Adds a new vertex with the given weight to the graph.
/// Returns the id of the new vertex.
fn new_vertex_weighted(&mut self, ... | (
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
) -> Result<(), ()>
where
Self::EdgeWeight: Default,
{
self.add_edge_weighted(source, sink, Self::EdgeWeight::default())
}
}
pub trait RemoveEdge: Graph
{
fn remove_edge_where_weight<F>(
&mut self,
source: impl Borrow<S... | add_edge | identifier_name |
signal-exit-status.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let args = os::args();
let args = args.as_slice();
if args.len() >= 2 && args[1] == "signal".to_owned() {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
} else {
let status = Process::status(args[0], ["signal".to_owned()]).unwrap();
// Windows does not have signa... | identifier_body | |
signal-exit-status.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// copyright 2013-2014 the rust project developers. see the copyright
// file at the top... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
signal-exit-status.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 status = Process::status(args[0], ["signal".to_owned()]).unwrap();
// Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK).
match status {
ExitSignal(_) if cfg!(unix) => {},
ExitStatus(0xC0000028) if cfg!(windows) => {},
_ =>... | conditional_block |
signal-exit-status.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let args = os::args();
let args = args.as_slice();
if args.len() >= 2 && args[1] == "signal".to_owned() {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
} else {
let status = Process::status(args[0], ["signal".to_owned()]).unwrap();
// Windows does not have si... | main | identifier_name |
macros.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 ... | #[cfg(test)]
macro_rules! log {
($lvl:expr, $($args:tt)*) => (
if log_enabled!($lvl) { println!($($args)*) }
)
}
#[cfg(test)]
macro_rules! assert_approx_eq {
($a:expr, $b:expr) => ({
let (a, b) = (&$a, &$b);
assert!((*a - *b).abs() < 1.0e-6,
"{} is not approximately ... | random_line_split | |
metrics.rs | use std::fmt;
use std::time::Duration;
use tic::Receiver;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Metric {
Request,
Processed,
}
impl fmt::Display for Metric {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
pub fn init(listen: Option<String>) -> Receiver<Metric> {
let mut config = Receiver::<Metric>::configure()
.batch_size(1)
.capacity(4096)
.poll_delay(Some(Duration::new(0, 1_000_000)))
.service(true);
if let Some(addr) = listen {
info!("listening STATS {}", addr);
... | {
match *self {
Metric::Request => write!(f, "request"),
Metric::Processed => write!(f, "processed"),
}
} | identifier_body |
metrics.rs | use std::fmt;
use std::time::Duration;
use tic::Receiver;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Metric {
Request,
Processed,
}
impl fmt::Display for Metric {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Metric::Request => write!(f, "request"),
Metric::Processed => write!(f, "processed"),
}
}
}
pub fn init(listen: Option<String>) -> Receiver<Metric> {
let mut config = Receiver::<Metric>::configure()
.b... | fmt | identifier_name |
metrics.rs | use std::fmt;
use std::time::Duration;
use tic::Receiver;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Metric {
Request,
Processed,
}
impl fmt::Display for Metric {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { | }
}
}
pub fn init(listen: Option<String>) -> Receiver<Metric> {
let mut config = Receiver::<Metric>::configure()
.batch_size(1)
.capacity(4096)
.poll_delay(Some(Duration::new(0, 1_000_000)))
.service(true);
if let Some(addr) = listen {
info!("listening STATS {}"... | Metric::Request => write!(f, "request"),
Metric::Processed => write!(f, "processed"), | random_line_split |
permissionstatus.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::PermissionStatusBinding::{self, PermissionDescriptor, PermissionName};
use d... |
impl Display for PermissionName {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
} | } | random_line_split |
permissionstatus.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::PermissionStatusBinding::{self, PermissionDescriptor, PermissionName};
use d... |
}
| {
write!(f, "{}", self.as_str())
} | identifier_body |
permissionstatus.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::PermissionStatusBinding::{self, PermissionDescriptor, PermissionName};
use d... | (global: &GlobalScope, query: &PermissionDescriptor) -> DomRoot<PermissionStatus> {
reflect_dom_object(Box::new(PermissionStatus::new_inherited(query.name)),
global,
PermissionStatusBinding::Wrap)
}
pub fn set_state(&self, state: PermissionState) {
... | new | identifier_name |
unused-macro.rs | // Copyright 2017 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 ... | {} | identifier_body | |
unused-macro.rs | // Copyright 2017 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 ... | () {}
| main | identifier_name |
unused-macro.rs | // Copyright 2017 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 ... | // Test that putting the #[deny] close to the macro's definition
// works.
#[deny(unused_macros)]
macro unused { //~ ERROR: unused macro definition
() => {}
}
}
mod boo {
pub(crate) macro unused { //~ ERROR: unused macro definition
() => {}
}
}
fn main() {} | mod bar { | random_line_split |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot:... | for next step() call.
var.wait(&mut ready);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_register_bar() {
let registry = Registry::default();
let topic = "fetching files";
// Add 2 progress bars.
let bar1 = {
let bar = ProgressBar::ne... | We've come around to the next iteration's wait() call -
// notify step() that we finished an iteration.
*ready = false;
var.notify_one();
}
// Wait | conditional_block |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot:... | }
}
}
};
}
impl_model! {
cache_stats: CacheStats,
io_time_series: IoTimeSeries,
progress_bar: ProgressBar,
}
impl Registry {
/// The "main" progress registry in this process.
pub fn main() -> &'static Self {
static REGISTRY: Lazy<Registry> = Lazy::ne... | /// Remove all registered models that are dropped externally.
pub fn remove_orphan_models(&self) {
$( self.[< remove_orphan_ $field >](); )* | random_line_split |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot:... | assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 50/100 files, [fetching files 100/200 bytes a.txt]"
);
// Dropping a bar marks it as "completed" and affects aggregated_bars.
drop(bar1);
assert_eq!(registry.remove_orphan_progre... | gistry = Registry::default();
let topic = "fetching files";
// Add 2 progress bars.
let bar1 = {
let bar = ProgressBar::new(topic.to_string(), 100, "files");
bar.set_position(50);
registry.register_progress_bar(&bar);
bar
};
let b... | identifier_body |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot:... | registry = Registry::default();
let series1 = IoTimeSeries::new("Net", "requests");
registry.register_io_time_series(&series1);
let series2 = IoTimeSeries::new("Disk", "files");
series2.populate_test_samples(1, 1, 1);
registry.register_io_time_series(&series2);
assert_eq... | () {
let | identifier_name |
where-clauses-cross-crate.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 ... | println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
} |
fn main() {
println!("{}", equal(&1, &2)); | random_line_split |
where-clauses-cross-crate.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 ... | () {
println!("{}", equal(&1, &2));
println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
}
| main | identifier_name |
where-clauses-cross-crate.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 ... | {
println!("{}", equal(&1, &2));
println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
} | identifier_body | |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Inte... | s1: &CStr, s2: &CStr) -> bool {
s1 == s2
}
for s in &self.vec {
if eq(s, string) {
return s.as_ptr();
}
}
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Inte... | q( | identifier_name |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Inte... | for s in &self.vec {
if eq(s, string) {
return s.as_ptr();
}
}
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Intern;
use std::ffi::CStr;
#[test]
fn intern() {
... |
s1 == s2
}
| identifier_body |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Inte... | }
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Intern;
use std::ffi::CStr;
#[test]
fn intern() {
fn cstr(str: &[u8]) -> &CStr {
CStr::from_bytes_with_nul(str).unwrap()
}
let... |
return s.as_ptr();
}
| conditional_block |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Inte... | assert!(!bar_ptr.is_null());
assert!(foo_ptr!= bar_ptr);
assert!(foo_ptr == intern.add(cstr(b"foo\0")));
assert!(foo_ptr!= intern.add(cstr(b"fo\0")));
assert!(foo_ptr!= intern.add(cstr(b"fool\0")));
assert!(foo_ptr!= intern.add(cstr(b"not foo\0")));
}
} |
let foo_ptr = intern.add(cstr(b"foo\0"));
let bar_ptr = intern.add(cstr(b"bar\0"));
assert!(!foo_ptr.is_null()); | random_line_split |
main.rs | #![feature(associated_consts)]
#![feature(slice_patterns)]
#![feature(const_fn)]
//#![deny(missing_docs)]
//#![deny(warnings)]
extern crate sdl2;
extern crate nuklear_rust as nk;
use nk::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Difficulty {
Easy,
Hard
}
#[derive(Debug, Default, Copy, Clone, Part... | {
std::env::set_var("RUST_BACKTRACE", "1");
let mut app = App::new();
let mut event_pump = app.sdl2.event_pump().unwrap();
'running: loop {
for e in event_pump.poll_iter() {
use AppEventHandling::*;
match app.handle_event(&e) {
Ok(_) => (),
... | in() | identifier_name |
main.rs | #![feature(associated_consts)]
#![feature(slice_patterns)]
#![feature(const_fn)]
//#![deny(missing_docs)]
//#![deny(warnings)]
extern crate sdl2;
extern crate nuklear_rust as nk;
use nk::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Difficulty {
Easy,
Hard
}
#[derive(Debug, Default, Copy, Clone, Part... | self.rdr.set_draw_color(sdl2::pixels::Color::RGBA(r,g,b,a));
self.rdr.draw_point(sdl2::rect::Point::new(x,y)).unwrap();
}
offset += elem_count;
}
*/
for cmd in nk.command_iterator() {
println!("cmd: {:?}", cmd);
}
... | let x = (w as f32*(x+1f32)/2f32) as i32;
let y = -(h as f32*(y+1f32)/2f32) as i32; | random_line_split |
main.rs | #![feature(associated_consts)]
#![feature(slice_patterns)]
#![feature(const_fn)]
//#![deny(missing_docs)]
//#![deny(warnings)]
extern crate sdl2;
extern crate nuklear_rust as nk;
use nk::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Difficulty {
Easy,
Hard
}
#[derive(Debug, Default, Copy, Clone, Part... | ,
&Event::MouseWheel { direction, y,.. } => {
println!("Mouse scroll: {} ({:?})", y, direction);
Ok(())
},
&Event::Window {..} => Ok(()),
&Event::Quit {..} => Err(AppEventHandling::Quit),
_ => Err(AppEventHandling::Unhandled),
... | {
println!("Mouse {:?} is up", mouse_btn);
Ok(())
} | conditional_block |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn new() -> App {
App ... | fn layout_mut(&mut self) -> Option<&mut Layout> {
Some(&mut self.layout)
}
fn reduce(&mut self, id: NodeId, action: &Box<Any>, scene: &mut Scene) {
if let Some(payload) = action.downcast_ref::<WidgetAdded>() {
if payload.0!= id {
return;
}
... | Some(&self.layout)
}
| random_line_split |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn | () -> App {
App {
id: 0,
layout: Layout::fill(),
}
}
}
impl Widget for App {
fn layout(&self) -> Option<&Layout> {
Some(&self.layout)
}
fn layout_mut(&mut self) -> Option<&mut Layout> {
Some(&mut self.layout)
}
fn reduce(&mut self, id: N... | new | identifier_name |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn new() -> App {
App ... | right: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
... | {
if payload.0 != id {
return;
}
scene.add_child(
id,
Panel::new(Layout {
left: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
... | conditional_block |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn new() -> App {
App ... | Panel::new(Layout {
right: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
... | {
if let Some(payload) = action.downcast_ref::<WidgetAdded>() {
if payload.0 != id {
return;
}
scene.add_child(
id,
Panel::new(Layout {
left: Some(0),
top: Some(0),
bo... | identifier_body |
gdk_x11.rs | //! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window... |
/// Wraps a native window in a GdkWindow. The function will try to look up the
/// window using `gdk_x11_window_lookup_for_display()` first. If it does not find
/// it there, it will create a new window.
///
/// This may fail if the window has been destroyed. If the window was already
/// known to GDK, a new referen... | {
unsafe {
return ffi::gdk_x11_get_default_root_xwindow();
}
} | identifier_body |
gdk_x11.rs | //! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window... | gdk_display: &mut gdk::Display,
xwindow: Window,
) -> Option<gdk::Window> {
unsafe {
let display: *mut GdkDisplay =
mut_override(gdk_display.to_glib_none().0);
return from_glib_full(ffi::gdk_x11_window_foreign_new_for_display(
display,
xwindow,
))... | k_x11_window_foreign_new_for_display(
| identifier_name |
gdk_x11.rs | //! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window... |
/// Gets the default GTK+ display.
///
/// # Returns
///
/// the Xlib Display* for the display specified in the `--display`
/// command line option or the `DISPLAY` environment variable.
pub fn gdk_x11_get_default_xdisplay() -> *mut Display {
unsafe {
return ffi::gdk_x11_get_default_xdisplay();
}
}
... | random_line_split | |
access.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> bool {
// See above for why this unsafety is ok, it just applies to the read
// instead of the write.
unsafe { (*self.access.inner.get()).closed }
}
}
impl<'a, T: Send> Deref<T> for Guard<'a, T> {
fn deref<'a>(&'a self) -> &'a T {
// A guard represents exclusive acces... | is_closed | identifier_name |
access.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 ... | use std::cell::UnsafeCell;
use std::mem;
use std::rt::local::Local;
use std::rt::task::{BlockedTask, Task};
use std::sync::Arc;
use homing::HomingMissile;
pub struct Access<T> {
inner: Arc<UnsafeCell<Inner<T>>>,
}
pub struct Guard<'a, T: 'a> {
access: &'a mut Access<T>,
missile: Option<HomingMissile>,
}
... | /// (the uv event loop).
| random_line_split |
overloaded-index-autoderef.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 ... |
impl IndexMut<int> for Foo {
fn index_mut(&mut self, z: &int) -> &mut int {
if *z == 0 {
&mut self.x
} else {
&mut self.y
}
}
}
trait Int {
fn get(self) -> int;
fn get_from_ref(&self) -> int;
fn inc(&mut self);
}
impl Int for int {
fn get(self) ... | }
} | random_line_split |
overloaded-index-autoderef.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 ... | else {
&self.y
}
}
}
impl IndexMut<int> for Foo {
fn index_mut(&mut self, z: &int) -> &mut int {
if *z == 0 {
&mut self.x
} else {
&mut self.y
}
}
}
trait Int {
fn get(self) -> int;
fn get_from_ref(&self) -> int;
fn inc(&mut ... | {
&self.x
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.