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 |
|---|---|---|---|---|
main.rs | // Works under Rust 1.14.0 :)
extern crate rand;
use std::io::prelude::*;
use std::io;
use rand::{thread_rng, Rng};
const MAX_ATTEMPTS:i16 = 5;
fn | (guess:u8, target:u8, remaining_guesses:i16) -> bool {
if guess == target {
// We won!
println!("Noice! You gone done did good, kid.");
return true;
} else {
if guess < target {
// Go lower
println!("Hmm too low, bro.");
} else if guess > target {
// Go higher
println!("Yo too high, guy.");
}
... | play | identifier_name |
main.rs | // Works under Rust 1.14.0 :)
extern crate rand;
use std::io::prelude::*;
use std::io;
use rand::{thread_rng, Rng};
const MAX_ATTEMPTS:i16 = 5;
fn play(guess:u8, target:u8, remaining_guesses:i16) -> bool {
if guess == target {
// We won!
println!("Noice! You gone done did good, kid.");
return true;
} else {
... |
// Get input:
let mut input_text = String::new();
print!("Take a guess: ");
io::stdout().flush().ok(); //.expect("Could not flush stdout");
io::stdin().read_line(&mut input_text).unwrap();
match input_text.trim().parse::<u8>().ok() {
Some(i) => if play(i, _number, position) {
break;
} el... | {
println!("Ouf. Sorry but you're all out of guesses. You lose =(");
println!("The number you were looking for is {}", _number);
break;
} | conditional_block |
main.rs | // Works under Rust 1.14.0 :)
extern crate rand;
use std::io::prelude::*;
use std::io;
use rand::{thread_rng, Rng};
const MAX_ATTEMPTS:i16 = 5;
fn play(guess:u8, target:u8, remaining_guesses:i16) -> bool {
if guess == target {
// We won!
println!("Noice! You gone done did good, kid.");
return true;
} else {
... | println!("Yo too high, guy.");
}
println!("You have {0} guesses left.
", remaining_guesses);
return false;
}
}
fn main() {
println!("
Yo! Welcome to Guess the Number with Rust!
Rust will, like, pick a number between 1 and 100 and, like, you've gotta guess it or whatever.
Oh. And you only get 5 guesses. B... | random_line_split | |
generic-struct.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... | <TKey, TValue> {
key: TKey,
value: TValue
}
fn main() {
let int_int = AGenericStruct { key: 0, value: 1 };
let int_float = AGenericStruct { key: 2, value: 3.5f64 };
let float_int = AGenericStruct { key: 4.5f64, value: 5 };
let float_int_float = AGenericStruct {
key: 6.5f64,
val... | AGenericStruct | identifier_name |
generic-struct.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 | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
// Some versions of the non-rust-enabled LLDB print the wrong generic
// parameter type names in this test.
// rust-lldb
// compile-flags:-g
// === GDB TESTS ===============================... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
protobuf-bin-gen-rust.rs | #![crate_type = "bin"]
#![feature(globs)]
extern crate protobuf;
extern crate getopts;
use std::io::fs::*;
use std::io::Reader;
use std::io::Writer;
use std::path::Path;
use std::os;
use protobuf::parse_from_reader;
use protobuf::descriptor::*;
use protobuf::codegen::*;
fn write_file(bin: &str, gen_options: &GenOp... | () {
let args = os::args();
let opts = vec!();
let matches = getopts::getopts(args.tail(), opts.as_slice()).unwrap();
let pb_bin = match matches.free.as_slice() {
[ref pb_bin] => pb_bin.to_string(),
_ => panic!("must have exactly one argument")
};
let gen_options = GenOptions {
... | main | identifier_name |
protobuf-bin-gen-rust.rs | #![crate_type = "bin"]
#![feature(globs)]
extern crate protobuf;
extern crate getopts;
use std::io::fs::*;
use std::io::Reader;
use std::io::Writer;
use std::path::Path;
use std::os;
use protobuf::parse_from_reader;
use protobuf::descriptor::*;
use protobuf::codegen::*;
fn write_file(bin: &str, gen_options: &GenOp... | }
}
fn main() {
let args = os::args();
let opts = vec!();
let matches = getopts::getopts(args.tail(), opts.as_slice()).unwrap();
let pb_bin = match matches.free.as_slice() {
[ref pb_bin] => pb_bin.to_string(),
_ => panic!("must have exactly one argument")
};
let gen_options ... | for r in results.iter() {
let mut file_writer = File::create(&Path::new(r.name.as_slice())).unwrap();
file_writer.write(r.content.as_slice()).unwrap(); | random_line_split |
protobuf-bin-gen-rust.rs | #![crate_type = "bin"]
#![feature(globs)]
extern crate protobuf;
extern crate getopts;
use std::io::fs::*;
use std::io::Reader;
use std::io::Writer;
use std::path::Path;
use std::os;
use protobuf::parse_from_reader;
use protobuf::descriptor::*;
use protobuf::codegen::*;
fn write_file(bin: &str, gen_options: &GenOp... |
fn main() {
let args = os::args();
let opts = vec!();
let matches = getopts::getopts(args.tail(), opts.as_slice()).unwrap();
let pb_bin = match matches.free.as_slice() {
[ref pb_bin] => pb_bin.to_string(),
_ => panic!("must have exactly one argument")
};
let gen_options = GenOp... | {
let mut is = File::open(&Path::new(bin)).unwrap();
let fds = parse_from_reader::<FileDescriptorSet>(&mut is as &mut Reader).unwrap();
let file_names: Vec<String> = fds.get_file().iter()
.map(|f| f.get_name().to_string())
.collect();
let results = gen(fds.get_file(), file_names.as_slic... | identifier_body |
borrowck-let-suggestion-suffixes.rs | fn id<T>(x: T) -> T { x }
fn f() {
let old = ['o']; // statement 0
let mut v1 = Vec::new(); // statement 1
|
v2.push(&young[0]); // statement 4
//~^ ERROR `young[_]` does not live long enough
//~| NOTE borrowed value does not live long enough
} //~ NOTE `young[_]` dropped here while still borrowed
let mut v3 = Vec::new(); // statement 5
v3.push(&id('x')); // statement 6
... | let mut v2 = Vec::new(); // statement 2
{
let young = ['y']; // statement 3 | random_line_split |
borrowck-let-suggestion-suffixes.rs | fn id<T>(x: T) -> T { x }
fn f() {
let old = ['o']; // statement 0
let mut v1 = Vec::new(); // statement 1
let mut v2 = Vec::new(); // statement 2
{
let young = ['y']; // statement 3
v2.push(&young[0]); // statement 4
//~^ ERROR `young[_]` does not live lon... | (&self) { } }
impl<T> Fake for T { }
| use_ref | identifier_name |
borrowck-let-suggestion-suffixes.rs | fn id<T>(x: T) -> T |
fn f() {
let old = ['o']; // statement 0
let mut v1 = Vec::new(); // statement 1
let mut v2 = Vec::new(); // statement 2
{
let young = ['y']; // statement 3
v2.push(&young[0]); // statement 4
//~^ ERROR `young[_]` does not live long enough
//~| NOT... | { x } | identifier_body |
validations.rs | //! Operations related to UTF-8 validation.
use crate::mem;
use super::Utf8Error;
/// Returns the initial codepoint accumulator for the first byte.
/// The first byte is special, only want bottom 5 bits for width 2, 4 bits
/// for width 3, and 3 bits for width 4.
#[inline]
fn utf8_first_byte(byte: u8, width: u32) ->... | }
// https://tools.ietf.org/html/rfc3629
static UTF8_CHAR_WIDTH: [u8; 256] = [
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x1F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x3F
1, 1, 1, 1, ... |
Ok(()) | random_line_split |
validations.rs | //! Operations related to UTF-8 validation.
use crate::mem;
use super::Utf8Error;
/// Returns the initial codepoint accumulator for the first byte.
/// The first byte is special, only want bottom 5 bits for width 2, 4 bits
/// for width 3, and 3 bits for width 4.
#[inline]
fn utf8_first_byte(byte: u8, width: u32) ->... | <'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
// Decode UTF-8
let x = *bytes.next()?;
if x < 128 {
return Some(x as u32);
}
// Multibyte case follows
// Decode from a byte combination out of: [[[x y] z] w]
// NOTE: Performance is sensitive to the exact formulation... | next_code_point | identifier_name |
validations.rs | //! Operations related to UTF-8 validation.
use crate::mem;
use super::Utf8Error;
/// Returns the initial codepoint accumulator for the first byte.
/// The first byte is special, only want bottom 5 bits for width 2, 4 bits
/// for width 3, and 3 bits for width 4.
#[inline]
fn utf8_first_byte(byte: u8, width: u32) ->... |
/// Reads the next code point out of a byte iterator (assuming a
/// UTF-8-like encoding).
#[unstable(feature = "str_internals", issue = "none")]
#[inline]
pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
// Decode UTF-8
let x = *bytes.next()?;
if x < 128 {
re... | {
match opt {
Some(&byte) => byte,
None => 0,
}
} | identifier_body |
expand.rs | use std::str;
use memchr::memchr;
use bytes::Captures;
pub fn expand(caps: &Captures, mut replacement: &[u8], dst: &mut Vec<u8>) {
while!replacement.is_empty() {
match memchr(b'$', replacement) {
None => break,
Some(i) => {
dst.extend(&replacement[..i]);
... | (b: &u8) -> bool {
match *b {
b'0'... b'9' | b'a'... b'z' | b'A'... b'Z' | b'_' => true,
_ => false,
}
}
| is_valid_cap_letter | identifier_name |
expand.rs | use std::str;
use memchr::memchr;
use bytes::Captures;
pub fn expand(caps: &Captures, mut replacement: &[u8], dst: &mut Vec<u8>) {
while!replacement.is_empty() {
match memchr(b'$', replacement) {
None => break,
Some(i) => {
dst.extend(&replacement[..i]);
... | if!replacement.get(cap_end).map_or(false, |&b| b == b'}') {
return None;
}
cap_end += 1;
}
Some(CaptureRef {
rest: &replacement[cap_end..],
cap: match cap.parse::<u32>() {
Ok(i) => Ref::Number(i as usize),
Err(_) => Ref::Named(cap),
... | random_line_split | |
borrowck-borrow-overloaded-deref-mut.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: Own<int>) {
let _i = &mut *x; //~ ERROR cannot borrow
}
fn deref_mut2(mut x: Own<int>) {
let _i = &mut *x;
}
fn deref_extend<'a>(x: &'a Own<int>) -> &'a int {
&**x
}
fn deref_extend_mut1<'a>(x: &'a Own<int>) -> &'a mut int {
&mut **x //~ ERROR cannot borrow
}
fn deref_extend_mut2<'a>(x: &'a mut ... | deref_mut1 | identifier_name |
borrowck-borrow-overloaded-deref-mut.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 ... | value: *mut T
}
impl<T> Deref for Own<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*self.value }
}
}
impl<T> DerefMut for Own<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *self.value }
}
}
fn deref_imm(x: Own<int>) {
let _i = &*x;
... |
struct Own<T> { | random_line_split |
borrowck-borrow-overloaded-deref-mut.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 assign1<'a>(x: Own<int>) {
*x = 3; //~ ERROR cannot borrow
}
fn assign2<'a>(x: &'a Own<int>) {
**x = 3; //~ ERROR cannot borrow
}
fn assign3<'a>(x: &'a mut Own<int>) {
**x = 3;
}
pub fn main() {}
| {
&mut **x
} | identifier_body |
timer.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::{
AsRawDescriptor, FakeClock, FromRawDescriptor, IntoRawDescriptor, RawDescriptor, Result,
};
use std::os::unix::io::{AsRawFd, FromRawF... | (pub TimerFd);
impl Timer {
pub fn new() -> Result<Timer> {
TimerFd::new().map(Timer)
}
}
/// See [FakeTimerFd](sys_util::FakeTimerFd) for struct- and method-level
/// documentation.
pub struct FakeTimer(FakeTimerFd);
impl FakeTimer {
pub fn new(clock: Arc<Mutex<FakeClock>>) -> Self {
FakeT... | Timer | identifier_name |
timer.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::{
AsRawDescriptor, FakeClock, FromRawDescriptor, IntoRawDescriptor, RawDescriptor, Result,
};
use std::os::unix::io::{AsRawFd, FromRawF... | pub fn wait(&mut self) -> Result<()> {
self.0.wait().map(|_| ())
}
pub fn is_armed(&self) -> Result<bool> {
self.0.is_armed()
}
pub fn clear(&mut self) -> Result<()> {
self.0.clear()
}
... | self.0.reset(dur, interval)
}
| random_line_split |
test_rotation.rs | extern crate mp4parse_capi;
use std::io::Read;
use mp4parse_capi::*;
extern fn buf_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize {
let input: &mut std::fs::File = unsafe { &mut *(userdata as *mut _) };
let mut buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
match... |
let mut counts: u32 = 0;
rv = mp4parse_get_track_count(parser, &mut counts);
assert_eq!(rv, Mp4parseStatus::Ok);
assert_eq!(counts, 1);
let mut video = Mp4parseTrackVideoInfo::default();
let rv = mp4parse_get_track_video_info(parser, 0, &mut video);
assert_eq!(... | assert_eq!(rv, Mp4parseStatus::Ok); | random_line_split |
test_rotation.rs | extern crate mp4parse_capi;
use std::io::Read;
use mp4parse_capi::*;
extern fn buf_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize |
#[test]
fn parse_rotation() {
let mut file = std::fs::File::open("tests/video_rotation_90.mp4").expect("Unknown file");
let io = Mp4parseIo {
read: Some(buf_read),
userdata: &mut file as *mut _ as *mut std::os::raw::c_void
};
unsafe {
let parser = mp4parse_new(&io);
l... | {
let input: &mut std::fs::File = unsafe { &mut *(userdata as *mut _) };
let mut buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
match input.read(&mut buf) {
Ok(n) => n as isize,
Err(_) => -1,
}
} | identifier_body |
test_rotation.rs | extern crate mp4parse_capi;
use std::io::Read;
use mp4parse_capi::*;
extern fn buf_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize {
let input: &mut std::fs::File = unsafe { &mut *(userdata as *mut _) };
let mut buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
match... | () {
let mut file = std::fs::File::open("tests/video_rotation_90.mp4").expect("Unknown file");
let io = Mp4parseIo {
read: Some(buf_read),
userdata: &mut file as *mut _ as *mut std::os::raw::c_void
};
unsafe {
let parser = mp4parse_new(&io);
let mut rv = mp4parse_read(p... | parse_rotation | identifier_name |
typeid-intrinsic.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... | () {
unsafe {
assert_eq!(TypeId::of::<other1::A>(), other1::id_A());
assert_eq!(TypeId::of::<other1::B>(), other1::id_B());
assert_eq!(TypeId::of::<other1::C>(), other1::id_C());
assert_eq!(TypeId::of::<other1::D>(), other1::id_D());
assert_eq!(TypeId::of::<other1::E>(), othe... | main | identifier_name |
typeid-intrinsic.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... | hash::hash::<TypeId, SipHasher>(&b));
} | random_line_split | |
typeid-intrinsic.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... | assert_eq!(other1::id_F(), other2::id_F());
assert_eq!(other1::id_G(), other2::id_G());
assert_eq!(other1::id_H(), other2::id_H());
assert_eq!(TypeId::of::<int>(), other2::foo::<int>());
assert_eq!(TypeId::of::<int>(), other1::foo::<int>());
assert_eq!(other2::foo::<int>... | {
unsafe {
assert_eq!(TypeId::of::<other1::A>(), other1::id_A());
assert_eq!(TypeId::of::<other1::B>(), other1::id_B());
assert_eq!(TypeId::of::<other1::C>(), other1::id_C());
assert_eq!(TypeId::of::<other1::D>(), other1::id_D());
assert_eq!(TypeId::of::<other1::E>(), other1:... | identifier_body |
abi.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 static slice_elt_base: uint = 0u;
pub static slice_elt_len: uint = 1u; | random_line_split | |
with_nom_result.rs | use m3u8_rs::Playlist;
use std::io::Read; | fn main() {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
let playlist = match parsed {
Result::Ok((_i, playlist)) => playlist,
Result::Err(e) =... | random_line_split | |
with_nom_result.rs | use m3u8_rs::Playlist;
use std::io::Read;
fn | () {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
let playlist = match parsed {
Result::Ok((_i, playlist)) => playlist,
Result::Err(e) => panic... | main | identifier_name |
with_nom_result.rs | use m3u8_rs::Playlist;
use std::io::Read;
fn main() {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
let playlist = match parsed {
Result::Ok((_i, playl... | {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
match parsed {
Result::Ok((_i, Playlist::MasterPlaylist(pl))) => println!("Master playlist:\n{:?}", pl),... | identifier_body | |
main.rs | extern crate http;
extern crate iron;
extern crate staticfile;
extern crate time;
use time::now;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, Chain, Alloy, Request, Response, Server, Status, Continue, FromFn,};
use iron::mixin::Serve;
use staticfile::Static;
fn come_again(_req: &mut Request, res: &mut Response... |
else
{
server.chain.link(FromFn::new(come_again));
}
server.listen(Ipv4Addr(0, 0, 0, 0), 3000);
}
}
| {
if time::now().tm_min <= 1
{
server.chain.link(Static::new(Path::new("./")));
}
} | conditional_block |
main.rs | extern crate http;
extern crate iron;
extern crate staticfile;
extern crate time;
use time::now;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, Chain, Alloy, Request, Response, Server, Status, Continue, FromFn,};
use iron::mixin::Serve;
use staticfile::Static;
fn come_again(_req: &mut Request, res: &mut Response... | {
loop
{
let mut server: Server = Iron::new();
if time::now().tm_hour == 17
{
if time::now().tm_min <= 1
{
server.chain.link(Static::new(Path::new("./")));
}
}
else
{
server.chain.link(FromFn::new(come_again));
}
server.listen(Ipv4Ad... | identifier_body | |
main.rs | extern crate http;
extern crate iron;
extern crate staticfile;
extern crate time;
use time::now;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, Chain, Alloy, Request, Response, Server, Status, Continue, FromFn,};
use iron::mixin::Serve;
use staticfile::Static;
fn | (_req: &mut Request, res: &mut Response, _alloy: &mut Alloy) -> Status
{
let _ = res.serve(::http::status::Ok, "Wrong time, come back later.");
Continue
}
fn main()
{
loop
{
let mut server: Server = Iron::new();
if time::now().tm_hour == 17
{
if time::now().tm_min <= 1
{... | come_again | identifier_name |
main.rs | extern crate http;
extern crate iron;
extern crate staticfile;
extern crate time;
use time::now;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, Chain, Alloy, Request, Response, Server, Status, Continue, FromFn,};
use iron::mixin::Serve;
use staticfile::Static;
fn come_again(_req: &mut Request, res: &mut Response... | {
server.chain.link(FromFn::new(come_again));
}
server.listen(Ipv4Addr(0, 0, 0, 0), 3000);
}
} | else | random_line_split |
frame_reader.rs | //! This reader composes frames of bytes started with a 4 byte frame header indicating the size of
//! the buffer. An exact size buffer will be allocated once the 4 byte frame header is received.
use std::io::{self, Read, Error, ErrorKind};
use std::collections::VecDeque;
use std::mem;
#[derive(Debug)]
pub struct Fra... |
fn read_value<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
let bytes_read = try!(reader.read(&mut self.current[self.bytes_read..]));
self.bytes_read += bytes_read;
if self.bytes_read == self.current.len() {
self.completed_frames.push_back(mem::replace(&mut self.cur... | {
let bytes_read = try!(reader.read(&mut self.header[self.bytes_read..]));
self.bytes_read += bytes_read;
if self.bytes_read == 4 {
let len = unsafe { u32::from_be(mem::transmute(self.header)) };
self.bytes_read = 0;
self.reading_header = false;
self.c... | identifier_body |
frame_reader.rs | //! This reader composes frames of bytes started with a 4 byte frame header indicating the size of
//! the buffer. An exact size buffer will be allocated once the 4 byte frame header is received.
use std::io::{self, Read, Error, ErrorKind};
use std::collections::VecDeque;
use std::mem;
#[derive(Debug)]
pub struct Fra... |
// Write a partial value
let mut data = Cursor::new(&buf1[0..5]);
let bytes_read = reader.read(&mut data).unwrap();
assert_eq!(5, bytes_read);
assert_eq!(None, reader.iter_mut().next());
// Complete writing the first value
let mut data = Cursor::new(&buf1[5..]);... | assert_eq!(None, reader.iter_mut().next()); | random_line_split |
frame_reader.rs | //! This reader composes frames of bytes started with a 4 byte frame header indicating the size of
//! the buffer. An exact size buffer will be allocated once the 4 byte frame header is received.
use std::io::{self, Read, Error, ErrorKind};
use std::collections::VecDeque;
use std::mem;
#[derive(Debug)]
pub struct Fra... | <T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
if self.reading_header {
self.read_header(reader)
} else {
self.read_value(reader)
}
}
// TODO: Return an error if size is greater than max_frame_size
fn read_header<T: Read>(&mut self, reader: &mut ... | do_read | identifier_name |
fullscreen.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = ... | () {
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
}
print!("Please write the number of the monitor to use: ");
let mut num = String::new();
... | main | identifier_name |
fullscreen.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = ... | .with_title("Hello world!".to_string())
.with_fullscreen(monitor)
.build()
.unwrap();
unsafe { window.make_current() };
let context = support::load(&window);
while!window.is_closed() {
context.draw_frame((0.0, 1.0, 0.0, 1.0));
window.swap_buffers();
... | {
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
}
print!("Please write the number of the monitor to use: ");
let mut num = String::new();
i... | identifier_body |
fullscreen.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = ... |
unsafe { window.make_current() };
let context = support::load(&window);
while!window.is_closed() {
context.draw_frame((0.0, 1.0, 0.0, 1.0));
window.swap_buffers();
println!("{:?}", window.wait_events().next());
}
} | .with_fullscreen(monitor)
.build()
.unwrap(); | random_line_split |
entry.rs | use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;
use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;
#[derive(Debug)]
pub struct Entry {
name: String,
self_size: u64,
children: Vec<Entry>,
is_file: bool,
}
impl Entry {
pub fn for_path(path: &Path) -> Result<Entry,... | else if metadata.is_file() {
vec![]
} else {
return Err("not a file or directory".to_string());
};
children.sort_by(
// Note: We change the ordering to get in descending order
|a, b| b.size().cmp(&a.size())
);
Ok(Entry {
... | {
Entry::in_directory(path)
} | conditional_block |
entry.rs | use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;
use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;
#[derive(Debug)]
pub struct Entry {
name: String,
self_size: u64,
children: Vec<Entry>,
is_file: bool,
}
impl Entry {
pub fn for_path(path: &Path) -> Result<Entry,... | (&self) -> bool {
self.is_file
}
}
impl fmt::Display for Entry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", self.name(), self.size().as_size_display())
}
}
#[cfg(test)]
mod test {
use super::*;
use modes::DisplayableEntry;
use std::path::Path;
... | is_file | identifier_name |
entry.rs | use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;
use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;
#[derive(Debug)]
pub struct Entry {
name: String,
self_size: u64,
children: Vec<Entry>,
is_file: bool,
}
impl Entry {
pub fn for_path(path: &Path) -> Result<Entry,... |
#[test]
fn it_can_be_displayed() {
use utils::SizeDisplay;
let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(format!("{}", file), format!("LICENSE {}", file.size().as_size_display()));
}
#[test]
fn it_calculates_size_from_children() {
let ent... | {
let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(file.children_iter().count(), 0);
} | identifier_body |
entry.rs | use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;
use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;
#[derive(Debug)]
pub struct Entry {
name: String,
self_size: u64,
children: Vec<Entry>,
is_file: bool,
}
impl Entry {
pub fn for_path(path: &Path) -> Result<Entry,... | let mut children = if metadata.is_dir() {
Entry::in_directory(path)
} else if metadata.is_file() {
vec![]
} else {
return Err("not a file or directory".to_string());
};
children.sort_by(
// Note: We change the ordering to get in de... | random_line_split | |
toggle_button.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
fn set_inconsistent(&mut self, setting: bool) {
unsafe { ffi::gtk_toggle_button_set_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(setting)); }
}
fn get_inconsistent(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_wi... | {
unsafe { to_bool(ffi::gtk_toggle_button_get_active(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
} | identifier_body |
toggle_button.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | fn set_inconsistent(&mut self, setting: bool) {
unsafe { ffi::gtk_toggle_button_set_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(setting)); }
}
fn get_inconsistent(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widg... | fn get_active(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_active(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
| random_line_split |
toggle_button.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | (&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_active(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
fn set_inconsistent(&mut self, setting: bool) {
unsafe { ffi::gtk_toggle_button_set_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(setting)); }
}
fn get_i... | get_active | identifier_name |
parsed.rs | //! Parsed domain names.
use std::borrow::Cow;
use std::cmp;
use std::fmt;
use std::hash;
use super::super::{Parser, ParseError, ParseResult};
use super::{DName, DNameBuf, DNameSlice, Label, NameLabels, NameLabelettes};
use super::plain::slice_from_bytes_unsafe;
//------------ ParsedDName ---------------------------... | other: &N) -> bool {
let self_iter = self.labelettes();
let other_iter = other.labelettes();
self_iter.eq(other_iter)
}
}
impl<'a> PartialEq<str> for ParsedDName<'a> {
fn eq(&self, other: &str) -> bool {
use std::str::FromStr;
let other = match DNameBuf::from_str(other)... | , | identifier_name |
parsed.rs | //! Parsed domain names.
use std::borrow::Cow;
use std::cmp;
use std::fmt;
use std::hash;
use super::super::{Parser, ParseError, ParseResult};
use super::{DName, DNameBuf, DNameSlice, Label, NameLabels, NameLabelettes};
use super::plain::slice_from_bytes_unsafe;
//------------ ParsedDName ---------------------------... | }
}
/// Splits off the part that is uncompressed.
fn split_uncompressed(&self) -> (Option<&'a DNameSlice>, Option<Self>) {
let mut name = self.clone();
loop {
name = match name.split_label() {
Ok((_, Some(new_name))) => new_name,
Ok((label, None)... | Ok((label, Some(ParsedDName{message: self.message,
start: start})))
}
| conditional_block |
parsed.rs | //! Parsed domain names.
use std::borrow::Cow;
use std::cmp;
use std::fmt;
use std::hash;
use super::super::{Parser, ParseError, ParseResult};
use super::{DName, DNameBuf, DNameSlice, Label, NameLabels, NameLabelettes};
use super::plain::slice_from_bytes_unsafe;
//------------ ParsedDName ---------------------------... |
impl<'a> fmt::UpperHex for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:X}", label));
}
for label in labels {
try!(write!(f, ".{:X}", label))
... | }
Ok(())
}
} | random_line_split |
parsed.rs | //! Parsed domain names.
use std::borrow::Cow;
use std::cmp;
use std::fmt;
use std::hash;
use super::super::{Parser, ParseError, ParseResult};
use super::{DName, DNameBuf, DNameSlice, Label, NameLabels, NameLabelettes};
use super::plain::slice_from_bytes_unsafe;
//------------ ParsedDName ---------------------------... | -- PartialEq and Eq
impl<'a, N: DName> PartialEq<N> for ParsedDName<'a> {
fn eq(&self, other: &N) -> bool {
let self_iter = self.labelettes();
let other_iter = other.labelettes();
self_iter.eq(other_iter)
}
}
impl<'a> PartialEq<str> for ParsedDName<'a> {
fn eq(&self, other: &str) -... | NameLabels::from_parsed(self.clone())
}
}
//- | identifier_body |
misc.rs | //! Miscellaneous builder routines that are not specific to building any particular
//! kind of thing.
use crate::build::Builder;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty}; | use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Adds a new temporary value of type `ty` storing the result of
/// evaluating `expr`.
///
/// N.B., **No cleanup is scheduled for this temporary.** You should
/// call `schedule_d... | random_line_split | |
misc.rs | //! Miscellaneous builder routines that are not specific to building any particular
//! kind of thing.
use crate::build::Builder;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Ad... |
}
| {
let tcx = self.tcx;
let ty = place.ty(&self.local_decls, tcx).ty;
if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, DUMMY_SP) {
Operand::Move(place)
} else {
Operand::Copy(place)
}
} | identifier_body |
misc.rs | //! Miscellaneous builder routines that are not specific to building any particular
//! kind of thing.
use crate::build::Builder;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Ad... |
}
}
| {
Operand::Copy(place)
} | conditional_block |
misc.rs | //! Miscellaneous builder routines that are not specific to building any particular
//! kind of thing.
use crate::build::Builder;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Ad... | (
&mut self,
block: BasicBlock,
source_info: SourceInfo,
value: u64,
) -> Place<'tcx> {
let usize_ty = self.tcx.types.usize;
let temp = self.temp(usize_ty, source_info.span);
self.cfg.push_assign_constant(
block,
source_info,
... | push_usize | identifier_name |
build.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | fn main() {
pyo3_build_config::add_extension_module_link_args();
// NB: The native extension only works with the Python interpreter version it was built with
// (e.g. Python 3.7 vs 3.8).
println!("cargo:rerun-if-env-changed=PY");
} | // Arc<Mutex> can be more clear than needing to grok Orderings:
#![allow(clippy::mutex_atomic)]
| random_line_split |
build.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | () {
pyo3_build_config::add_extension_module_link_args();
// NB: The native extension only works with the Python interpreter version it was built with
// (e.g. Python 3.7 vs 3.8).
println!("cargo:rerun-if-env-changed=PY");
}
| main | identifier_name |
build.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | {
pyo3_build_config::add_extension_module_link_args();
// NB: The native extension only works with the Python interpreter version it was built with
// (e.g. Python 3.7 vs 3.8).
println!("cargo:rerun-if-env-changed=PY");
} | identifier_body | |
db.rs | use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use rocket::http::Status;
use rocket::request::{self, FromRequest};
use rocket::{Outcome, Request, State};
use std::ops::Deref;
type PgPool = Pool<ConnectionManager<PgConnection>>;
pub struct DbConn(pub PooledConnection<Conne... |
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let pool = request.guard::<State<PgPool>>()?;
match pool.get() {
Ok(conn) => Outcome::Success(DbConn(conn)),
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())),
}
}
}
im... | impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
type Error = (); | random_line_split |
db.rs | use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use rocket::http::Status;
use rocket::request::{self, FromRequest};
use rocket::{Outcome, Request, State};
use std::ops::Deref;
type PgPool = Pool<ConnectionManager<PgConnection>>;
pub struct DbConn(pub PooledConnection<Conne... | () -> PgPool {
let manager = ConnectionManager::<PgConnection>::new(env!("DATABASE_URL"));
Pool::new(manager).expect("db pool")
}
| init_pool | identifier_name |
events.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
let tx = &mut self.transactions[len - 1];
tx.set_event(event);
//sc_app_layer_decoder_events_set_event_raw(&mut tx.events, event as u8);
}
}
| {
return;
} | conditional_block |
events.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | * You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use crate::core::*;
use crate::smb::smb::*;
#[derive(AppLayerEvent)]
pub enum SMBEvent ... | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* | random_line_split |
events.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
/// Set events from vector of events.
pub fn set_events(&mut self, events: Vec<SMBEvent>) {
for e in events {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
}
}
}
impl SMBState {
/// Set an event. The event is set on the most recent transaction.
... | {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
} | identifier_body |
events.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | (&mut self, event: SMBEvent) {
let len = self.transactions.len();
if len == 0 {
return;
}
let tx = &mut self.transactions[len - 1];
tx.set_event(event);
//sc_app_layer_decoder_events_set_event_raw(&mut tx.events, event as u8);
}
}
| set_event | identifier_name |
counters.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Counters", inherited=False, gecko... |
${helpers.predefined_type(
"counter-reset",
"CounterReset",
initial_value="Default::default()",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-lists-3/#propdef-counter-reset",
servo_restyle_damage="rebuild_and_reflow",
)} | servo_restyle_damage="rebuild_and_reflow",
)} | random_line_split |
20.rs | /* Problem 20: Factorial digit sum
*
* n! means n × (n − 1) ×... × 3 × 2 × 1
*
* For example, 10! = 10 × 9 ×... × 3 × 2 × 1 = 3628800,
* and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
*
* Find the sum of the digits in the number 100! */
use num::bigint::{BigUint, ToBigUint};
use ... | -> u32 {
chr.to_digit(10).unwrap()
}
| ar) | identifier_name |
20.rs | /* Problem 20: Factorial digit sum
*
* n! means n × (n − 1) ×... × 3 × 2 × 1
*
* For example, 10! = 10 × 9 ×... × 3 × 2 × 1 = 3628800,
* and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
*
* Find the sum of the digits in the number 100! */
use num::bigint::{BigUint, ToBigUint};
use ... | remaining -= 1;
}
result
}
fn to_i(chr: char) -> u32 {
chr.to_digit(10).unwrap()
} | let mut result: BigUint = One::one();
let mut remaining: u32 = n;
while remaining > 0 {
result = result * remaining.to_biguint().unwrap(); | random_line_split |
20.rs | /* Problem 20: Factorial digit sum
*
* n! means n × (n − 1) ×... × 3 × 2 × 1
*
* For example, 10! = 10 × 9 ×... × 3 × 2 × 1 = 3628800,
* and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
*
* Find the sum of the digits in the number 100! */
use num::bigint::{BigUint, ToBigUint};
use ... | al(n: u32) -> BigUint {
let mut result: BigUint = One::one();
let mut remaining: u32 = n;
while remaining > 0 {
result = result * remaining.to_biguint().unwrap();
remaining -= 1;
}
result
}
fn to_i(chr: char) -> u32 {
chr.to_digit(10).unwrap()
}
| rnum = factorial(100).to_string();
let result = strnum.chars().fold(0, |digit, sum| digit + to_i(sum));
println!("{}", result);
}
fn factori | identifier_body |
issue-32995.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 ... |
fn foo<X:Default>() {
let d : X() = Default::default();
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
} | } | random_line_split |
issue-32995.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 ... |
let o : Box<Send + ::std::marker()::Sync> = Box::new(1);
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
}
fn foo<X:Default>() {
let d : X() = Default::default();
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previo... | {
let x: usize() = 1;
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let b: ::std::boxed()::Box<_> = Box::new(1);
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let p = ::std::str::()::from_ut... | identifier_body |
issue-32995.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 ... | () {
let x: usize() = 1;
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let b: ::std::boxed()::Box<_> = Box::new(1);
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let p = ::std::str::()::from... | main | identifier_name |
lib.rs | //! Compile-time generated maps and sets.
//!
//! The `phf::Map` and `phf::Set` types have roughly comparable performance to
//! a standard hash table, but can be generated as compile-time static values.
//!
//! # Usage
//!
//! If the `macros` Cargo feature is enabled, the `phf_map`, `phf_set`,
//! `phf_ordered_map`, a... | #[doc(inline)]
pub use self::map::Map;
#[doc(inline)]
pub use self::set::Set;
#[doc(inline)]
pub use self::ordered_map::OrderedMap;
#[doc(inline)]
pub use self::ordered_set::OrderedSet;
pub mod map;
pub mod set;
pub mod ordered_map;
pub mod ordered_set;
// WARNING: this is not considered part of phf's public API and ... |
pub use phf_shared::PhfHash; | random_line_split |
lib.rs | //! Compile-time generated maps and sets.
//!
//! The `phf::Map` and `phf::Set` types have roughly comparable performance to
//! a standard hash table, but can be generated as compile-time static values.
//!
//! # Usage
//!
//! If the `macros` Cargo feature is enabled, the `phf_map`, `phf_set`,
//! `phf_ordered_map`, a... | (&self) -> &[T] {
match *self {
Slice::Static(t) => t,
#[cfg(feature = "std")]
Slice::Dynamic(ref t) => t,
}
}
}
| deref | identifier_name |
mod.rs | pub use self::{
bit_board::BitBoard,
board::Board,
player::{AiPlayer, PlayerKind},
};
mod bit_board;
mod board;
mod multi_direction;
mod player;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Point(pub u32, pub u32);
impl Point {
fn from_offset(off: u32, size: Size) -> Point {
Point(... | Side::White => Side::Black,
}
}
} | random_line_split | |
mod.rs | pub use self::{
bit_board::BitBoard,
board::Board,
player::{AiPlayer, PlayerKind},
};
mod bit_board;
mod board;
mod multi_direction;
mod player;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Point(pub u32, pub u32);
impl Point {
fn from_offset(off: u32, size: Size) -> Point {
Point(... | {
Black,
White,
}
impl Side {
pub fn flip(self) -> Side {
match self {
Side::Black => Side::White,
Side::White => Side::Black,
}
}
}
| Side | identifier_name |
types.rs | //! Holmes Language Types
//!
//! The types defined in this module are used to define the parts of the Holmes
//! language itself, and are used for writing rules, facts, etc.
use pg::dyn::{Type, Value};
/// A `Predicate` is a name combined with a list of typed slots, e.g.
///
/// ```c
/// foo(uint64, string)
/// ```
/... | (&self, other: &MatchExpr) -> bool {
use self::MatchExpr::*;
match (self, other) {
(&Unbound, &Unbound) => true,
(&Var(x), &Var(y)) => x == y,
(&Const(ref v), &Const(ref vv)) => v == vv,
_ => false,
}
}
}
/// A `BindExpr` is what appears on th... | eq | identifier_name |
types.rs | //! Holmes Language Types
//!
//! The types defined in this module are used to define the parts of the Holmes
//! language itself, and are used for writing rules, facts, etc.
use pg::dyn::{Type, Value};
/// A `Predicate` is a name combined with a list of typed slots, e.g.
///
/// ```c
/// foo(uint64, string)
/// ```
/... | /// use std::sync::Arc;
/// Predicate {
/// name: "foo".to_string(),
/// description: None,
/// fields: vec![Field {
/// name: None,
/// description: None,
/// type_: Arc::new(types::UInt64)
/// }, Field {
/// name: None,
/// description: None,
/// type_: ... | /// ```
/// use holmes::pg::dyn::types;
/// use holmes::engine::types::{Predicate, Field}; | random_line_split |
lib.rs | #[macro_use]
extern crate log;
use special_fun::FloatSpecial;
use std::collections::VecDeque;
use std::f64;
#[derive(Clone, Debug)]
pub struct PhiFailureDetector {
min_stddev: f64,
history_size: usize,
buf: VecDeque<u64>,
prev_heartbeat: Option<u64>,
}
impl PhiFailureDetector {
pub fn new() -> Ph... | /// Returns the time t (within epsilon) at which phi will be >= val.
pub fn next_crossing_at(&self, now: u64, threshold: f64) -> u64 {
let phappened = 1.0 - (10.0f64).powf(-threshold);
let x = phappened.norm_inv();
let mean = stats::mean(self.buf.iter().cloned());
let stddev = s... | None => 0.0,
}
}
| random_line_split |
lib.rs | #[macro_use]
extern crate log;
use special_fun::FloatSpecial;
use std::collections::VecDeque;
use std::f64;
#[derive(Clone, Debug)]
pub struct PhiFailureDetector {
min_stddev: f64,
history_size: usize,
buf: VecDeque<u64>,
prev_heartbeat: Option<u64>,
}
impl PhiFailureDetector {
pub fn | () -> PhiFailureDetector {
Self::default()
}
pub fn min_stddev(self, min_stddev: f64) -> PhiFailureDetector {
assert!(min_stddev > 0.0, "min_stddev must be > 0.0");
PhiFailureDetector { min_stddev,..self }
}
pub fn history_size(self, count: usize) -> PhiFailureDetector {
... | new | identifier_name |
lib.rs | #[macro_use]
extern crate log;
use special_fun::FloatSpecial;
use std::collections::VecDeque;
use std::f64;
#[derive(Clone, Debug)]
pub struct PhiFailureDetector {
min_stddev: f64,
history_size: usize,
buf: VecDeque<u64>,
prev_heartbeat: Option<u64>,
}
impl PhiFailureDetector {
pub fn new() -> Ph... |
}
}
/// def ϕ(Tnow ) = − log10(Plater (Tnow − Tlast))
pub fn phi(&self, now: u64) -> f64 {
match &self.prev_heartbeat {
Some(prev_time) if now > *prev_time => {
trace!(
"now:{} - prev_heartbeat:{} = {:?}",
now,
... | {
if t < *prev {
return;
};
let delta = t - *prev;
self.buf.push_back(delta);
*prev = t;
if self.buf.len() > self.history_size {
let _ = self.buf.pop_front();
}
... | conditional_block |
lib.rs | #[macro_use]
extern crate log;
use special_fun::FloatSpecial;
use std::collections::VecDeque;
use std::f64;
#[derive(Clone, Debug)]
pub struct PhiFailureDetector {
min_stddev: f64,
history_size: usize,
buf: VecDeque<u64>,
prev_heartbeat: Option<u64>,
}
impl PhiFailureDetector {
pub fn new() -> Ph... | }
#[test]
fn should_recover() {
env_logger::try_init().unwrap_or_default();
let mut detector = PhiFailureDetector::new().history_size(3);
for t in 0..10 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t,... | env_logger::try_init().unwrap_or_default();
let mut detector = PhiFailureDetector::new();
for t in 0..100 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
if t > 10 {
assert... | identifier_body |
latex.rs | use std::io::IoResult;
use collections::HashMap;
use backend::Backend;
use colors;
pub struct LatexBackend {
contexts: Vec<~str>,
}
impl LatexBackend {
pub fn new() -> LatexBackend {
LatexBackend {
contexts: Vec::new(),
}
}
}
static HEADER: &'static str = "\
\\usepackage{xco... |
fn start(&mut self, w: &mut Writer, ty: &str) -> IoResult<()> {
if ty!= "comment" {
if colors::get_types().contains(&ty.to_owned()) {
try!(write!(w, "\\\\textcolor\\{{}\\}\\{", ty));
}
if ty == "attribute" {
try!(w.write_str("#"));
... | {
try!(w.write_line("\\end{Highlighting}"));
try!(w.write_line("\\end{Shaded}"));
Ok(())
} | identifier_body |
latex.rs | use std::io::IoResult;
use collections::HashMap;
use backend::Backend;
use colors;
pub struct LatexBackend {
contexts: Vec<~str>,
}
impl LatexBackend {
pub fn new() -> LatexBackend {
LatexBackend {
contexts: Vec::new(),
}
}
}
static HEADER: &'static str = "\
\\usepackage{xco... | (&mut self, w: &mut Writer, ty: &str) -> IoResult<()> {
if ty!= "comment" {
if colors::get_types().contains(&ty.to_owned()) {
try!(write!(w, "\\\\textcolor\\{{}\\}\\{", ty));
}
if ty == "attribute" {
try!(w.write_str("#"));
}
... | start | identifier_name |
latex.rs | use std::io::IoResult;
use collections::HashMap;
use backend::Backend;
use colors;
pub struct LatexBackend {
contexts: Vec<~str>,
}
impl LatexBackend {
pub fn new() -> LatexBackend {
LatexBackend {
contexts: Vec::new(),
}
}
}
static HEADER: &'static str = "\
\\usepackage{xco... | }
first = false;
}
let old_len = text.len();
let text = text.trim_right_chars('\n').to_owned();
let new_len = text.len();
range(0, old_len - new_len).advance(|_| {
result.push_char('\n');
true... | result.push_str("}"); | random_line_split |
latex.rs | use std::io::IoResult;
use collections::HashMap;
use backend::Backend;
use colors;
pub struct LatexBackend {
contexts: Vec<~str>,
}
impl LatexBackend {
pub fn new() -> LatexBackend {
LatexBackend {
contexts: Vec::new(),
}
}
}
static HEADER: &'static str = "\
\\usepackage{xco... |
self.contexts.pop();
Ok(())
}
fn text(&mut self, w: &mut Writer, text: &str) -> IoResult<()> {
fn escape_latex(text: &str) -> ~str {
let mut result = StrBuf::new();
let mut escape = false;
for c in text.chars() {
if escape {
... | {
if ty == "attribute" {
try!(w.write_str("]"));
}
if colors::get_types().contains(&ty.to_owned()) {
try!(w.write_str("}"));
}
} | conditional_block |
raft_client.rs | BUF` is reserved for errors.
if self.size > 0
&& (self.size + msg_size + GRPC_SEND_MSG_BUF >= self.cfg.max_grpc_send_msg_len as usize
|| self.batch.get_msgs().len() >= RAFT_MSG_MAX_BATCH_SIZE)
{
self.overflowing = Some(msg);
return;
}
s... |
#[inline]
fn flush(&mut self, sender: &mut ClientCStreamSender<RaftMessage>) -> grpcio::Result<()> {
if let Some(msg) = self.batch.pop_front() {
Pin::new(sender).start_send((
msg,
WriteFlags::default().buffer_hint(!self.batch.is_empty()),
))
... | {
self.batch.is_empty()
} | identifier_body |
raft_client.rs | (&self) {
self.connected.store(false, Ordering::SeqCst);
}
/// Wakes up consumer to retrive message.
fn notify(&self) {
if!self.buf.is_empty() {
let t = self.waker.lock().unwrap().take();
if let Some(t) = t {
t.wake();
}
}
}
... | disconnect | identifier_name | |
raft_client.rs | _BUF` is reserved for errors.
if self.size > 0
&& (self.size + msg_size + GRPC_SEND_MSG_BUF >= self.cfg.max_grpc_send_msg_len as usize
|| self.batch.get_msgs().len() >= RAFT_MSG_MAX_BATCH_SIZE)
{
self.overflowing = Some(msg);
return;
}
... | }
let router = &self.router;
router.broadcast_unreachable(self.store_id);
}
}
impl<R, M, B, E> Future for RaftCall<R, M, B, E>
where
R: RaftStoreRouter<E> + Unpin +'static,
B: Buffer<OutputMessage = M> + Unpin,
E: KvEngine,
{
type Output = ();
fn poll(mut self: Pin<&mut... | let _ = tx.send(());
return;
} | random_line_split |
into_stream.rs | use core::pin::Pin;
use futures_core::stream::{FusedStream, Stream, TryStream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_utils::unsafe_pinned;
/// Stream for the [`into_stream`](super::TryStreamExt::into_stream) method.
#[derive(Debug)]
#[must_use = "streams do ... |
fn size_hint(&self) -> (usize, Option<usize>) {
self.stream.size_hint()
}
}
// Forwarding impl of Sink from the underlying stream
#[cfg(feature = "sink")]
impl<S: Sink<Item>, Item> Sink<Item> for IntoStream<S> {
type Error = S::Error;
delegate_sink!(stream, Item);
}
| {
self.stream().try_poll_next(cx)
} | identifier_body |
into_stream.rs | use core::pin::Pin;
use futures_core::stream::{FusedStream, Stream, TryStream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_utils::unsafe_pinned;
/// Stream for the [`into_stream`](super::TryStreamExt::into_stream) method.
#[derive(Debug)]
#[must_use = "streams do ... | <St> {
stream: St,
}
impl<St> IntoStream<St> {
unsafe_pinned!(stream: St);
#[inline]
pub(super) fn new(stream: St) -> Self {
IntoStream { stream }
}
/// Acquires a reference to the underlying stream that this combinator is
/// pulling from.
pub fn get_ref(&self) -> &St {
... | IntoStream | identifier_name |
into_stream.rs | use core::pin::Pin;
use futures_core::stream::{FusedStream, Stream, TryStream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_utils::unsafe_pinned;
/// Stream for the [`into_stream`](super::TryStreamExt::into_stream) method.
#[derive(Debug)]
#[must_use = "streams do ... | fn size_hint(&self) -> (usize, Option<usize>) {
self.stream.size_hint()
}
}
// Forwarding impl of Sink from the underlying stream
#[cfg(feature = "sink")]
impl<S: Sink<Item>, Item> Sink<Item> for IntoStream<S> {
type Error = S::Error;
delegate_sink!(stream, Item);
} | cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
self.stream().try_poll_next(cx)
}
| random_line_split |
basic_shape.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/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts... | <W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("ellipse(")?;
if (self.semiaxis_x, self.semiaxis_y)!= Default::default() {
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
... | to_css | identifier_name |
basic_shape.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/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts... | fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("circle(")?;
self.radius.to_css(dest)?;
dest.write_str(" at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
impl ToCss for Ellipse {
fn to_css<W>(&s... | impl ToCss for Circle { | random_line_split |
basic_shape.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/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts... |
dest.write_str("at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
| {
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
dest.write_str(" ")?;
} | conditional_block |
basic_shape.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/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts... |
}
| {
dest.write_str("ellipse(")?;
if (self.semiaxis_x, self.semiaxis_y) != Default::default() {
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
dest.write_str(" ")?;
}
dest.write_str("at ")?;
self.po... | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![comment = "The Servo Parallel Browser Project"]
#![license = "MPL"]
#![feature(globs, macro_rules)]
#![deny(u... | extern crate string_cache_macros;
#[phase(plugin)]
extern crate lazy_static;
extern crate "util" as servo_util;
// Public API
pub use media_queries::{Device, Screen};
pub use stylesheets::{Stylesheet, iter_font_face_rules};
pub use selector_matching::{Stylist, StylesheetOrigin, UserAgentOrigin, AuthorOrigin, UserOr... | random_line_split | |
trace.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/. */
//! Utilities for tracing JS-managed values.
//!
//! The lifetime of DOM objects is managed by the SpiderMonkey Ga... |
}
no_jsmanaged_fields!(bool, f32, f64, String, Url);
no_jsmanaged_fields!(usize, u8, u16, u32, u64);
no_jsmanaged_fields!(isize, i8, i16, i32, i64);
no_jsmanaged_fields!(Sender<T>);
no_jsmanaged_fields!(Receiver<T>);
no_jsmanaged_fields!(Rect<T>);
no_jsmanaged_fields!(ImageCacheTask, ScriptControlChan);
no_jsmanaged... | {
let (ref a, ref b) = *self;
a.trace(trc);
b.trace(trc);
} | identifier_body |
trace.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/. */
//! Utilities for tracing JS-managed values.
//!
//! The lifetime of DOM objects is managed by the SpiderMonkey Ga... |
unsafe {
let name = CString::from_slice(description.as_bytes());
(*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
debug!("tracing value {}", description);
JS_CallTracer(tracer, val.to_gcth... | {
return;
} | conditional_block |
trace.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/. */
//! Utilities for tracing JS-managed values.
//!
//! The lifetime of DOM objects is managed by the SpiderMonkey Ga... | (&self, trc: *mut JSTracer) {
self.get().trace(trc)
}
}
impl JSTraceable for *mut JSObject {
fn trace(&self, trc: *mut JSTracer) {
trace_object(trc, "object", *self);
}
}
impl JSTraceable for JSVal {
fn trace(&self, trc: *mut JSTracer) {
trace_jsval(trc, "val", *self);
}
}
... | trace | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.