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 |
|---|---|---|---|---|
single-line-if-else.rs | // rustfmt-single_line_if_else_max_width: 100
// Format if-else expressions on a single line, when possible.
fn main() {
let a = if 1 > 2 {
unreachable!()
} else {
10
};
let a = if x { 1 } else if y | else { 3 };
let b = if cond() {
5
} else {
// Brief comment.
10
};
let c = if cond() {
statement();
5
} else {
10
};
let d = if let Some(val) = turbo
{ "cool" } else {
"beans" };
if cond() { statement(); } else { other... | { 2 } | conditional_block |
invalid-punct-ident-2.rs | // aux-build:invalid-punct-ident.rs
// rustc-env:RUST_BACKTRACE=0
// FIXME https://github.com/rust-lang/rust/issues/59998
// normalize-stderr-test "thread.*panicked.*proc_macro_server.rs.*\n" -> ""
// normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> ""
// normalize-stderr-test "\nerror: internal compiler error.*... | {} | identifier_body | |
invalid-punct-ident-2.rs | // aux-build:invalid-punct-ident.rs
// rustc-env:RUST_BACKTRACE=0
// FIXME https://github.com/rust-lang/rust/issues/59998
// normalize-stderr-test "thread.*panicked.*proc_macro_server.rs.*\n" -> ""
// normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> ""
// normalize-stderr-test "\nerror: internal compiler error.*... | () {}
| main | identifier_name |
invalid-punct-ident-2.rs | // aux-build:invalid-punct-ident.rs
// rustc-env:RUST_BACKTRACE=0
// FIXME https://github.com/rust-lang/rust/issues/59998
// normalize-stderr-test "thread.*panicked.*proc_macro_server.rs.*\n" -> ""
// normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> ""
// normalize-stderr-test "\nerror: internal compiler error.*... | // normalize-stderr-test "end of query stack\n" -> ""
#[macro_use]
extern crate invalid_punct_ident;
invalid_ident!(); //~ ERROR proc macro panicked
fn main() {} | // normalize-stderr-test "note: rustc.*running on.*\n\n" -> ""
// normalize-stderr-test "query stack during panic:\n" -> ""
// normalize-stderr-test "we're just showing a limited slice of the query stack\n" -> "" | random_line_split |
texture_draw.rs | #[macro_use]
extern crate glium;
use glium::Surface;
mod support;
macro_rules! texture_draw_test {
($test_name:ident, $tex_ty:ident, [$($dims:expr),+], $glsl_ty:expr, $glsl_value:expr,
$rust_value:expr) => (
#[test] |
let program = glium::Program::from_source(&display,
"
#version 110
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
",
&f... | fn $test_name() {
let display = support::build_display();
let (vb, ib) = support::build_rectangle_vb_ib(&display); | random_line_split |
main.rs | extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
use piston::window::WindowSettings;
use piston::event_loop::*;
use piston::input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{ GlGraphics, OpenGL };
pub struct App {
gl: GlGraphics, // Ope... | let square = rectangle::square(0.0, 0.0, 50.0);
let rotation = self.rotation;
let (x, y) = ((args.width / 2) as f64,
(args.height / 2) as f64);
self.gl.draw(args.viewport(), |c, gl| {
// Clear the screen.
clear(GREEN, gl);
let t... | const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
| random_line_split |
main.rs | extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
use piston::window::WindowSettings;
use piston::event_loop::*;
use piston::input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{ GlGraphics, OpenGL };
pub struct | {
gl: GlGraphics, // OpenGL drawing backend.
rotation: f64 // Rotation for the square.
}
impl App {
fn render(&mut self, args: &RenderArgs) {
use graphics::*;
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
let square = rectan... | App | identifier_name |
main.rs | extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
use piston::window::WindowSettings;
use piston::event_loop::*;
use piston::input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{ GlGraphics, OpenGL };
pub struct App {
gl: GlGraphics, // Ope... |
if let Some(u) = e.update_args() {
app.update(&u);
}
}
}
| {
app.render(&r);
} | conditional_block |
import-crate-with-invalid-spans.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
// The AST of `exported_generic` stored in crate_with_invalid_spans's
// metadata should contain an invalid span where span.lo > span.hi.
// Let's make sure the compiler doesn't crash when encountering this.
let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32);
} | identifier_body | |
import-crate-with-invalid-spans.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
// The AST of `exported_generic` stored in crate_with_invalid_spans's
// metadata should contain an invalid span where span.lo > span.hi.
// Let's make sure the compiler doesn't crash when encountering this.
let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32);
}
| main | identifier_name |
import-crate-with-invalid-spans.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | // aux-build:crate_with_invalid_spans.rs
// pretty-expanded FIXME #23616
extern crate crate_with_invalid_spans;
fn main() {
// The AST of `exported_generic` stored in crate_with_invalid_spans's
// metadata should contain an invalid span where span.lo > span.hi.
// Let's make sure the compiler doesn't cra... | // 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.
| random_line_split |
mod.rs | //! Simple Rust AST. This is what the various code generators create,
//! which then gets serialized.
use grammar::repr::Grammar;
use grammar::parse_tree::Visibility;
use tls::Tls;
use std::fmt;
use std::io::{self, Write};
macro_rules! rust {
($w:expr, $($args:tt)*) => {
try!(($w).writeln(&::std::fmt::for... | try!(write!(self.write, " "));
}
try!(write!(self.write, "{},", i));
first = false;
}
}
writeln!(self.write, "")
}
pub fn writeln(&mut self, out: &str) -> io::Result<()> {
let buf = out.as_bytes();
... | for (i, _comment) in iterable {
if !first { | random_line_split |
mod.rs | //! Simple Rust AST. This is what the various code generators create,
//! which then gets serialized.
use grammar::repr::Grammar;
use grammar::parse_tree::Visibility;
use tls::Tls;
use std::fmt;
use std::io::{self, Write};
macro_rules! rust {
($w:expr, $($args:tt)*) => {
try!(($w).writeln(&::std::fmt::for... |
}
| {
// Stuff that we plan to use.
// Occasionally we happen to not use it after all, hence the allow.
rust!(self, "#[allow(unused_extern_crates)]");
rust!(self, "extern crate lalrpop_util as {}lalrpop_util;", prefix);
Ok(())
} | identifier_body |
mod.rs | //! Simple Rust AST. This is what the various code generators create,
//! which then gets serialized.
use grammar::repr::Grammar;
use grammar::parse_tree::Visibility;
use tls::Tls;
use std::fmt;
use std::io::{self, Write};
macro_rules! rust {
($w:expr, $($args:tt)*) => {
try!(($w).writeln(&::std::fmt::for... |
Ok(())
}
pub fn write_module_attributes(&mut self, grammar: &Grammar) -> io::Result<()> {
for attribute in grammar.module_attributes.iter() {
rust!(self, "{}", attribute);
}
Ok(())
}
pub fn write_uses(&mut self, super_prefix: &str, grammar: &Grammar) -> io... | {
rust!(self, ") -> {}", return_type);
} | conditional_block |
mod.rs | //! Simple Rust AST. This is what the various code generators create,
//! which then gets serialized.
use grammar::repr::Grammar;
use grammar::parse_tree::Visibility;
use tls::Tls;
use std::fmt;
use std::io::{self, Write};
macro_rules! rust {
($w:expr, $($args:tt)*) => {
try!(($w).writeln(&::std::fmt::for... | (&mut self, grammar: &Grammar) -> io::Result<()> {
for attribute in grammar.module_attributes.iter() {
rust!(self, "{}", attribute);
}
Ok(())
}
pub fn write_uses(&mut self, super_prefix: &str, grammar: &Grammar) -> io::Result<()> {
// things the user wrote
fo... | write_module_attributes | identifier_name |
create.rs | static LOREM_IPSUM: &'static str =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate... | () {
let path = Path::new("out/lorem_ipsum.txt");
let display = path.display();
// 以只写模式打开文件,返回 `io::Result<File>`
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}: {}",
display,
why.description()),
O... | main | identifier_name |
create.rs | static LOREM_IPSUM: &'static str =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate... | }
| {
let path = Path::new("out/lorem_ipsum.txt");
let display = path.display();
// 以只写模式打开文件,返回 `io::Result<File>`
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}: {}",
display,
why.description()),
Ok(f... | identifier_body |
create.rs | static LOREM_IPSUM: &'static str =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate... | } | random_line_split | |
linear-for-loop.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 ... | () {
let x = vec!(1, 2, 3);
let mut y = 0;
for i in x.iter() { println!("{:?}", *i); y += *i; }
println!("{:?}", y);
assert_eq!(y, 6);
let s = "hello there".to_owned();
let mut i: int = 0;
for c in s.bytes() {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((... | main | identifier_name |
linear-for-loop.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 ... |
if i == 2 { assert!((c == 'l' as u8)); }
if i == 3 { assert!((c == 'l' as u8)); }
if i == 4 { assert!((c == 'o' as u8)); }
//...
i += 1;
println!("{:?}", i);
println!("{:?}", c);
}
assert_eq!(i, 11);
}
| { assert!((c == 'e' as u8)); } | conditional_block |
linear-for-loop.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 ... | assert_eq!(i, 11);
}
| {
let x = vec!(1, 2, 3);
let mut y = 0;
for i in x.iter() { println!("{:?}", *i); y += *i; }
println!("{:?}", y);
assert_eq!(y, 6);
let s = "hello there".to_owned();
let mut i: int = 0;
for c in s.bytes() {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((c =... | identifier_body |
linear-for-loop.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 | let x = vec!(1, 2, 3);
let mut y = 0;
for i in x.iter() { println!("{:?}", *i); y += *i; }
println!("{:?}", y);
assert_eq!(y, 6);
let s = "hello there".to_owned();
let mut i: int = 0;
for c in s.bytes() {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((c == ... | // <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.
pub fn main() { | random_line_split |
serv.rs | // Copyright 2021 The Grin Developers
//
// 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 required by applicable law or agree... | (&self, _h: Hash) -> Option<core::Transaction> {
None
}
fn tx_kernel_received(&self, _h: Hash, _peer_info: &PeerInfo) -> Result<bool, chain::Error> {
Ok(true)
}
fn transaction_received(
&self,
_: core::Transaction,
_stem: bool,
) -> Result<bool, chain::Error> {
Ok(true)
}
fn compact_block_received(
... | get_transaction | identifier_name |
serv.rs | // Copyright 2021 The Grin Developers
//
// 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 required by applicable law or agree... |
}
| {
false
} | identifier_body |
serv.rs | // Copyright 2021 The Grin Developers
//
// 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 required by applicable law or agree... | peers: Arc::new(Peers::new(PeerStore::new(db_root)?, adapter, config)),
stop_state,
})
}
/// Starts a new TCP server and listen to incoming connections. This is a
/// blocking call until the TCP server stops.
pub fn listen(&self) -> Result<(), Error> {
// start TCP listener and handle incoming connection... | ) -> Result<Server, Error> {
Ok(Server {
config: config.clone(),
capabilities,
handshake: Arc::new(Handshake::new(genesis, config.clone())), | random_line_split |
serv.rs | // Copyright 2021 The Grin Developers
//
// 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 required by applicable law or agree... |
if let Some(p) = self.peers.get_connected_peer(addr) {
// if we're already connected to the addr, just return the peer
trace!("connect_peer: already connected {}", addr);
return Ok(p);
}
trace!(
"connect_peer: on {}:{}. connecting to {}",
self.config.host,
self.config.port,
addr
);
mat... | {
let hs = self.handshake.clone();
let addrs = hs.addrs.read();
if addrs.contains(&addr) {
debug!("connect: ignore connecting to PeerWithSelf, addr: {}", addr);
return Err(Error::PeerWithSelf);
}
} | conditional_block |
lib.rs | extern crate regex;
macro_rules! regex(
($s:expr) => (regex::Regex::new($s).unwrap());
);
pub fn is_valid(kennitala : &str) -> bool {
let constants = [3, 2, 7, 6, 5, 4, 3, 2];
let re = regex!(r"^\d{6}-?\d{4}$");
if re.is_match(kennitala) |
false
}
| {
let sanitized = kennitala.replace("-","");
let check_digit = (sanitized.as_bytes()[8] as char).to_digit(10).unwrap();
let c = constants
.iter()
.zip(sanitized.bytes())
.fold(0,
|sum : u32, (x, y) : (&u32, u8)|
sum + ... | conditional_block |
lib.rs | extern crate regex;
macro_rules! regex(
($s:expr) => (regex::Regex::new($s).unwrap());
);
pub fn is_valid(kennitala : &str) -> bool {
let constants = [3, 2, 7, 6, 5, 4, 3, 2];
let re = regex!(r"^\d{6}-?\d{4}$");
if re.is_match(kennitala) {
let sanitized = kennitala.replace("-","");
... | } | }
}
false | random_line_split |
lib.rs | extern crate regex;
macro_rules! regex(
($s:expr) => (regex::Regex::new($s).unwrap());
);
pub fn is_valid(kennitala : &str) -> bool | return true
}
}
false
}
| {
let constants = [3, 2, 7, 6, 5, 4, 3, 2];
let re = regex!(r"^\d{6}-?\d{4}$");
if re.is_match(kennitala) {
let sanitized = kennitala.replace("-","");
let check_digit = (sanitized.as_bytes()[8] as char).to_digit(10).unwrap();
let c = constants
.iter()
... | identifier_body |
lib.rs | extern crate regex;
macro_rules! regex(
($s:expr) => (regex::Regex::new($s).unwrap());
);
pub fn | (kennitala : &str) -> bool {
let constants = [3, 2, 7, 6, 5, 4, 3, 2];
let re = regex!(r"^\d{6}-?\d{4}$");
if re.is_match(kennitala) {
let sanitized = kennitala.replace("-","");
let check_digit = (sanitized.as_bytes()[8] as char).to_digit(10).unwrap();
let c = constants
... | is_valid | identifier_name |
cpp.rs | //! Enables the generation of header and source files for using intercom
//! libraries from C++ projects.
extern crate std;
use std::borrow::Cow;
use std::io::Write;
use super::GeneratorError;
use super::{pascal_case, LibraryContext, ModelOptions, TypeSystemOptions};
use intercom::typelib::{
Arg, CoClass, Direc... | (lib: TypeLib, opts: &ModelOptions) -> Result<Self, GeneratorError>
{
let ctx = LibraryContext::try_from(&lib)?;
let mut interfaces = vec![];
let mut coclasses = vec![];
for t in &lib.types {
match t {
TypeInfo::Class(cls) => {
coclass... | try_from | identifier_name |
cpp.rs | //! Enables the generation of header and source files for using intercom
//! libraries from C++ projects.
extern crate std;
use std::borrow::Cow;
use std::io::Write;
use super::GeneratorError;
use super::{pascal_case, LibraryContext, ModelOptions, TypeSystemOptions};
use intercom::typelib::{
Arg, CoClass, Direc... | }
}
/// Generates the manifest content.
///
/// - `out` - The writer to use for output.
pub fn write(
lib: intercom::typelib::TypeLib,
opts: ModelOptions,
out_header: Option<&mut dyn Write>,
out_source: Option<&mut dyn Write>,
) -> Result<(), GeneratorError>
{
let mut reg = Handlebars::new();
... | {
let interfaces = cls
.interfaces
.iter()
.flat_map(|itf_ref| {
opts.type_systems
.iter()
.map(|opt| {
let itf = ctx.itfs_by_ref[itf_ref.name.as_ref()];
CppInterface::fina... | identifier_body |
cpp.rs | //! Enables the generation of header and source files for using intercom
//! libraries from C++ projects.
extern crate std;
use std::borrow::Cow;
use std::io::Write;
use super::GeneratorError;
use super::{pascal_case, LibraryContext, ModelOptions, TypeSystemOptions};
use intercom::typelib::{
Arg, CoClass, Direc... | other => other.to_string(),
};
format!("{}{}", base_name, "*".repeat(indirection as usize))
}
}
impl CppClass
{
fn try_from(
cls: &CoClass,
opts: &ModelOptions,
ctx: &LibraryContext,
) -> Result<Self, GeneratorError>
{
let interfaces = cls
... | random_line_split | |
bigint_extensions.rs | use ramp::int::Int;
use core::convert::From;
const DEFAULT_BUCKET_SIZE: usize = 5;
pub trait ModPow<T, K> {
fn mod_pow(&self, exp: &T, m: &K) -> Self;
fn mod_pow_k(&self, exp: &T, m: &K, k: usize) -> Self;
}
impl ModPow<Int, Int> for Int {
fn mod_pow(&self, exp: &Int, m: &Int) -> Int {
self.mod_... |
pub trait ModInverse<T> : Sized {
fn mod_inverse(&self, n: &T) -> Option<Self>;
}
impl ModInverse<Int> for Int {
fn mod_inverse(&self, n: &Int) -> Option<Int> {
let mut u1 = Int::one();
let mut u3 = (*self).clone();
let mut v1 = Int::zero();
let mut v3 = (*n).clone();
... | {
let mut digits = Vec::new();
let mut n = (*e).clone();
let base = Int::from(b);
while n > Int::zero() {
digits.push(usize::from(&(&n % &base)));
n = &n / &base;
}
digits
} | identifier_body |
bigint_extensions.rs | use ramp::int::Int;
use core::convert::From;
const DEFAULT_BUCKET_SIZE: usize = 5;
pub trait ModPow<T, K> {
fn mod_pow(&self, exp: &T, m: &K) -> Self;
fn mod_pow_k(&self, exp: &T, m: &K, k: usize) -> Self;
}
impl ModPow<Int, Int> for Int {
fn mod_pow(&self, exp: &Int, m: &Int) -> Int {
self.mod_... | (a: i64, b: i64) {
let big_a = Int::from(a);
let big_b = Int::from(b);
assert_eq!(big_a.mod_inverse(&big_b), None);
}
check(7, 26, 15);
check(37, 216, 181);
check(17, 3120, 2753);
check(7, -72, 31);
check_none(0, 21);
check_n... | check_none | identifier_name |
bigint_extensions.rs | use ramp::int::Int;
use core::convert::From;
const DEFAULT_BUCKET_SIZE: usize = 5;
pub trait ModPow<T, K> {
fn mod_pow(&self, exp: &T, m: &K) -> Self;
fn mod_pow_k(&self, exp: &T, m: &K, k: usize) -> Self;
}
impl ModPow<Int, Int> for Int {
fn mod_pow(&self, exp: &Int, m: &Int) -> Int {
self.mod_... | #[test]
fn test_bigint_mod_pow() {
fn check(b: &Int, e: &Int, m: &Int, r: &Int) {
assert_eq!(b.mod_pow(&e, &m), *r);
}
fn check_i64(b: i64, e: i64, m: i64, r: i64) {
let big_b = Int::from(b);
let big_e = Int::from(e);
let big_m = Int::from... |
use rand;
use test::Bencher;
| random_line_split |
bigint_extensions.rs | use ramp::int::Int;
use core::convert::From;
const DEFAULT_BUCKET_SIZE: usize = 5;
pub trait ModPow<T, K> {
fn mod_pow(&self, exp: &T, m: &K) -> Self;
fn mod_pow_k(&self, exp: &T, m: &K, k: usize) -> Self;
}
impl ModPow<Int, Int> for Int {
fn mod_pow(&self, exp: &Int, m: &Int) -> Int {
self.mod_... | else {
u1
};
Some(inv)
}
}
#[cfg(test)]
mod tests {
use super::*;
use ramp::{ Int, RandomInt };
use rand;
use test::Bencher;
#[test]
fn test_bigint_mod_pow() {
fn check(b: &Int, e: &Int, m: &Int, r: &Int) {
assert_eq!(b.mod_pow(&e, &m), ... | {
n - u1
} | conditional_block |
file_info.rs | extern crate libc;
use std::mem;
use crate::libproc::helpers;
use crate::libproc::proc_pid::{ListPIDInfo, PidInfoFlavor};
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
// this extern block links to the libproc library
// Original signatures of functions can be found at http://opensource.apple.com/sou... | <T: PIDFDInfo>(pid: i32, fd: i32) -> Result<T, String> {
let flavor = T::flavor() as i32;
let buffer_size = mem::size_of::<T>() as i32;
let mut pidinfo = T::default();
let buffer_ptr = &mut pidinfo as *mut _ as *mut c_void;
let ret: i32;
unsafe {
ret = proc_pidfdinfo(pid, fd, flavor, bu... | pidfdinfo | identifier_name |
file_info.rs | extern crate libc;
use std::mem;
use crate::libproc::helpers;
use crate::libproc::proc_pid::{ListPIDInfo, PidInfoFlavor};
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
// this extern block links to the libproc library
// Original signatures of functions can be found at http://opensource.apple.com/sou... | else {
Ok(pidinfo)
}
}
#[cfg(not(target_os = "macos"))]
pub fn pidfdinfo<T: PIDFDInfo>(_pid: i32, _fd: i32) -> Result<T, String> {
unimplemented!()
}
#[cfg(all(test, target_os = "macos"))]
mod test {
use crate::libproc::bsd_info::BSDInfo;
use crate::libproc::file_info::{ListFDs, ProcFDType};
... | {
Err(helpers::get_errno_with_message(ret))
} | conditional_block |
file_info.rs | extern crate libc;
use std::mem;
use crate::libproc::helpers;
use crate::libproc::proc_pid::{ListPIDInfo, PidInfoFlavor};
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
// this extern block links to the libproc library
// Original signatures of functions can be found at http://opensource.apple.com/sou... |
#[cfg(all(test, target_os = "macos"))]
mod test {
use crate::libproc::bsd_info::BSDInfo;
use crate::libproc::file_info::{ListFDs, ProcFDType};
use crate::libproc::net_info::{SocketFDInfo, SocketInfoKind};
use crate::libproc::proc_pid::{listpidinfo, pidinfo};
use super::pidfdinfo;
#[test]
... | {
unimplemented!()
} | identifier_body |
file_info.rs | use std::mem;
use crate::libproc::helpers;
use crate::libproc::proc_pid::{ListPIDInfo, PidInfoFlavor};
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
// this extern block links to the libproc library
// Original signatures of functions can be found at http://opensource.apple.com/source/Libc/Libc-594.9.... | extern crate libc;
| random_line_split | |
errors.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... | /// The device name is invalid
BadDeviceName(String),
/// The number of fuses was incorrect for the device
WrongFuseCount,
/// An unknown value was used in the `Oe` field
UnsupportedOeConfiguration([bool; 4]),
/// An unknown value was used in the ZIA selection bits
UnsupportedZIAConfigur... | random_line_split | |
errors.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... | (_: ()) -> Self {
// FIXME
unreachable!();
}
}
impl error::Error for XC2BitError {
fn source(&self) -> Option<&(dyn error::Error +'static)> {
match self {
&XC2BitError::JedParseError(ref err) => Some(err),
&XC2BitError::BadDeviceName(_) => None,
&XC2B... | from | identifier_name |
errors.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... | ,
}
}
}
| {
write!(f, "unknown ZIA selection bit pattern ")?;
for &bit in bits {
write!(f, "{}", b2s(bit))?;
}
Ok(())
} | conditional_block |
errors.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... |
}
impl fmt::Display for XC2BitError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&XC2BitError::JedParseError(err) => {
write!(f, ".jed parsing failed: {}", err)
},
&XC2BitError::BadDeviceName(ref devname) => {
wri... | {
match self {
&XC2BitError::JedParseError(ref err) => Some(err),
&XC2BitError::BadDeviceName(_) => None,
&XC2BitError::WrongFuseCount => None,
&XC2BitError::UnsupportedOeConfiguration(_) => None,
&XC2BitError::UnsupportedZIAConfiguration(_) => None,
... | identifier_body |
stack_switcher.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use Box;
use Buildable;
use Container;
use Orientable;
#[cfg(feature = "3.10")]
use Stack;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::translate::*;
glib_wrapper! {
pub struct StackSwitcher(Object<ffi::GtkStackSwitc... |
}
| {
unsafe {
ffi::gtk_stack_switcher_set_stack(self.to_glib_none().0, stack.to_glib_none().0);
}
} | identifier_body |
stack_switcher.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use Box;
use Buildable;
use Container;
use Orientable;
#[cfg(feature = "3.10")]
use Stack;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::translate::*;
glib_wrapper! {
pub struct StackSwitcher(Object<ffi::GtkStackSwitc... | (&self) -> Option<Stack> {
unsafe {
from_glib_none(ffi::gtk_stack_switcher_get_stack(self.to_glib_none().0))
}
}
#[cfg(feature = "3.10")]
pub fn set_stack(&self, stack: Option<&Stack>) {
unsafe {
ffi::gtk_stack_switcher_set_stack(self.to_glib_none().0, stack.... | get_stack | identifier_name |
stack_switcher.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use Box;
use Buildable;
use Container;
use Orientable;
#[cfg(feature = "3.10")]
use Stack;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::translate::*;
glib_wrapper! {
pub struct StackSwitcher(Object<ffi::GtkStackSwitc... | }
}
impl StackSwitcher {
#[cfg(feature = "3.10")]
pub fn new() -> StackSwitcher {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_stack_switcher_new()).downcast_unchecked()
}
}
#[cfg(feature = "3.10")]
pub fn get_stack(&self) -> O... | get_type => || ffi::gtk_stack_switcher_get_type(), | random_line_split |
paths.rs | use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::io;
use std::io::prelude::*;
use std::iter;
use std::path::{Component, Path, PathBuf};
use filetime::FileTime;
use crate::util::errors::{CargoResult, CargoResultExt};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &... | (path: &Path) -> PathAncestors<'_> {
PathAncestors {
current: Some(path),
//HACK: avoid reading `~/.cargo/config` when testing Cargo itself.
stop_at: env::var("__CARGO_TEST_ROOT").ok().map(PathBuf::from),
}
}
}
impl<'a> Iterator for PathAncestors<'a> {
type I... | new | identifier_name |
paths.rs | use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::io;
use std::io::prelude::*;
use std::iter;
use std::path::{Component, Path, PathBuf};
use filetime::FileTime;
use crate::util::errors::{CargoResult, CargoResultExt};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &... |
#[cfg(unix)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
use std::os::unix::prelude::*;
Ok(path.as_os_str().as_bytes())
}
#[cfg(windows)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
match path.as_os_str().to_str() {
Some(s) => Ok(s.as_bytes()),
None => Err(anyhow::for... | {
// note that if `FileTime::from_system_time(SystemTime::now());` is determined to be sufficient,
// then this can be removed.
let timestamp = path.join("invoked.timestamp");
write(
×tamp,
b"This file has an mtime of when this was started.",
)?;
let ft = mtime(×tamp)?;... | identifier_body |
paths.rs | use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::io;
use std::io::prelude::*;
use std::iter;
use std::path::{Component, Path, PathBuf};
use filetime::FileTime;
use crate::util::errors::{CargoResult, CargoResultExt};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &... | .chain_err(|| format!("failed to write `{}`", path.as_ref().display()))?;
Ok(())
}
pub fn append(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
let mut f = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(path)... | f.seek(io::SeekFrom::Start(0))?;
f.write_all(contents)?;
}
Ok(())
})() | random_line_split |
trait-implementations.rs | // compile-flags:-Zprint-mono-items=eager
#![deny(dead_code)]
#![feature(start)]
pub trait SomeTrait {
fn foo(&self);
fn bar<T>(&self, x: T);
}
impl SomeTrait for i64 {
//~ MONO_ITEM fn <i64 as SomeTrait>::foo
fn foo(&self) {}
fn bar<T>(&self, _: T) {}
} |
fn bar<T>(&self, _: T) {}
}
pub trait SomeGenericTrait<T> {
fn foo(&self, x: T);
fn bar<T2>(&self, x: T, y: T2);
}
// Concrete impl of generic trait
impl SomeGenericTrait<u32> for f64 {
//~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::foo
fn foo(&self, _: u32) {}
fn bar<T2>(&self, _: u32, _... |
impl SomeTrait for i32 {
//~ MONO_ITEM fn <i32 as SomeTrait>::foo
fn foo(&self) {} | random_line_split |
trait-implementations.rs | // compile-flags:-Zprint-mono-items=eager
#![deny(dead_code)]
#![feature(start)]
pub trait SomeTrait {
fn foo(&self);
fn bar<T>(&self, x: T);
}
impl SomeTrait for i64 {
//~ MONO_ITEM fn <i64 as SomeTrait>::foo
fn foo(&self) {}
fn bar<T>(&self, _: T) {}
}
impl SomeTrait for i32 {
//~ MONO_... | <T>(&self, _: T) {}
}
pub trait SomeGenericTrait<T> {
fn foo(&self, x: T);
fn bar<T2>(&self, x: T, y: T2);
}
// Concrete impl of generic trait
impl SomeGenericTrait<u32> for f64 {
//~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::foo
fn foo(&self, _: u32) {}
fn bar<T2>(&self, _: u32, _: T2) {}
}
... | bar | identifier_name |
trait-implementations.rs | // compile-flags:-Zprint-mono-items=eager
#![deny(dead_code)]
#![feature(start)]
pub trait SomeTrait {
fn foo(&self);
fn bar<T>(&self, x: T);
}
impl SomeTrait for i64 {
//~ MONO_ITEM fn <i64 as SomeTrait>::foo
fn foo(&self) |
fn bar<T>(&self, _: T) {}
}
impl SomeTrait for i32 {
//~ MONO_ITEM fn <i32 as SomeTrait>::foo
fn foo(&self) {}
fn bar<T>(&self, _: T) {}
}
pub trait SomeGenericTrait<T> {
fn foo(&self, x: T);
fn bar<T2>(&self, x: T, y: T2);
}
// Concrete impl of generic trait
impl SomeGenericTrait<u32> fo... | {} | identifier_body |
drop_flag_effects.rs | // Copyright 2012-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-MI... | <'a, 'gcx, 'tcx>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
path: MovePathIndex) -> bool
{
place_contents_drop_state_cannot_differ(
tcx, mir, &move_data.move_paths[path].place)
}
fn on_all_children_bits<'a, 'gcx, 'tcx, F>(
... | is_terminal_path | identifier_name |
drop_flag_effects.rs | // Copyright 2012-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-MI... |
ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true",
place, ty);
true
}
ty::Adt(def, _) if (def.has_dtor(tcx) &&!def.is_box()) || def.is_union() => {
debug!("p... | {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false",
place, ty);
false
} | conditional_block |
drop_flag_effects.rs | // Copyright 2012-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-MI... | }
}
}
pub(crate) fn on_lookup_result_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
lookup_result: LookupResult,
each_child: F)
where F: FnMut(MovePathIndex)
{
match lookup_result {
LookupResult::Parent(..) => {
... | {
let ty = place.ty(mir, tcx).to_ty(tcx);
match ty.sty {
ty::Array(..) => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false",
place, ty);
false
}
ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => {
debug!(... | identifier_body |
drop_flag_effects.rs | // Copyright 2012-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-MI... | use super::move_paths::{MoveData, LookupResult, InitKind};
pub fn move_path_children_matching<'tcx, F>(move_data: &MoveData<'tcx>,
path: MovePathIndex,
mut cond: F)
-> Option<MovePathIndex>
where... | random_line_split | |
context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public |
//! Data needed by the layout thread.
use fnv::FnvHasher;
use gfx::display_list::{WebRenderImageInfo, OpaqueNode};
use gfx::font_cache_thread::FontCacheThread;
use gfx::font_context::FontContext;
use heapsize::HeapSizeOf;
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::{CanRequestImages, ImageCac... | * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | random_line_split |
context.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/. */
//! Data needed by the layout thread.
use fnv::FnvHasher;
use gfx::display_list::{WebRenderImageInfo, OpaqueNode}... |
}
}
}
impl<'a> LayoutContext<'a> {
#[inline(always)]
pub fn shared_context(&self) -> &SharedStyleContext {
&self.style_context
}
pub fn get_or_request_image_or_meta(&self,
node: OpaqueNode,
url: ServoU... | {
assert!(pending_images.lock().unwrap().is_empty());
} | conditional_block |
context.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/. */
//! Data needed by the layout thread.
use fnv::FnvHasher;
use gfx::display_list::{WebRenderImageInfo, OpaqueNode}... | (&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<WebRenderImageInfo> {
if let Some(existing_webrender_image) = self.webre... | get_webrender_image_for_url | identifier_name |
context.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/. */
//! Data needed by the layout thread.
use fnv::FnvHasher;
use gfx::display_list::{WebRenderImageInfo, OpaqueNode}... |
pub fn heap_size_of_persistent_local_context() -> usize {
FONT_CONTEXT_KEY.with(|r| {
if let Some(ref context) = *r.borrow() {
context.heap_size_of_children()
} else {
0
}
})
}
/// Layout information shared among all workers. This must be thread-safe.
pub struc... | {
FONT_CONTEXT_KEY.with(|k| {
let mut font_context = k.borrow_mut();
if font_context.is_none() {
let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone();
*font_context = Some(FontContext::new(font_cache_thread));
}
f(&mut RefMut::map(f... | identifier_body |
lib.rs | //! # bittrex-api
//!
//! **bittrex-api** provides a wrapper for the [Bittrex API](https://bittrex.com/home/api).
//! This crate makes it easy to consume the **Bittrex API** in Rust.
//!
//! ##Example
//!
//! ```no_run
//! extern crate bittrex_api;
//!
//! use bittrex_api::BittrexClient;
//! # fn main() { | //! # }
//! ```
extern crate time;
extern crate hmac;
extern crate sha2;
extern crate generic_array;
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
pub mod error;
pub mod values;
mod client;
pub use client::BittrexClient; | //! let bittrex_client = BittrexClient::new("KEY".to_string(), "SECRET".to_string()); // Initialize the Bittrex Client with your API Key and Secret
//! let markets = bittrex_client.get_markets().unwrap(); //Get all available markets of Bittrex | random_line_split |
str.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 geometry::Au;
use cssparser::{self, RGBA, Color};
use libc::c_char;
use num_lib::ToPrimitive;
use std::ascii... | &split: &&str) -> bool {!split.is_empty() }
s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool)
}
/// Shared implementation to parse an integer according to
/// <https://html.spec.whatwg.org/#rules-for-parsing-integers> or
/// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers... | ot_empty( | identifier_name |
str.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 geometry::Au;
use cssparser::{self, RGBA, Color};
use libc::c_char;
use num_lib::ToPrimitive;
use std::ascii... | fn hex_string(string: &[u8]) -> Result<u8, ()> {
match string.len() {
0 => Err(()),
1 => hex(string[0] as char),
_ => {
let upper = try!(hex(string[0] as char));
let lower = try!(hex(string[1] as char));
Ok((upper << 4) | low... | match ch {
'0'...'9' => Ok((ch as u8) - b'0'),
'a'...'f' => Ok((ch as u8) - b'a' + 10),
'A'...'F' => Ok((ch as u8) - b'A' + 10),
_ => Err(()),
}
}
| identifier_body |
str.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 geometry::Au;
use cssparser::{self, RGBA, Color};
use libc::c_char;
use num_lib::ToPrimitive;
use std::ascii... | '\u{000d}',
];
pub fn split_html_space_chars<'a>(s: &'a str) ->
Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> {
fn not_empty(&split: &&str) -> bool {!split.is_empty() }
s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool)
}
/// Shared implementation... | '\u{0020}',
'\u{0009}',
'\u{000a}',
'\u{000c}', | random_line_split |
issue-5554.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
constants!();
} | identifier_body | |
issue-5554.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T> {
a: T,
}
// reordering these bounds stops the ICE
//
// nmatsakis: This test used to have the bounds Default + PartialEq +
// Default, but having duplicate bounds became illegal.
impl<T: Default + PartialEq> Default for X<T> {
fn default() -> X<T> {
X { a: Default::default() }
}
}
macro_rules... | X | identifier_name |
issue-5554.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
pub struct X<T> {
a: T,
}
// reordering these bounds stops the ICE
//
// nmatsakis: This test used to have the bounds Default + PartialEq +
// Default, but having duplicate bounds became illegal.
impl<T: Default + PartialEq> Default for X<T> {
fn default() -> X<T> {
X { a: Default::default() }
}
}... | // <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.
use std::default::Default; | random_line_split |
inefficient_to_string.rs | // run-rustfix
#![deny(clippy::inefficient_to_string)]
use std::borrow::Cow;
fn | () {
let rstr: &str = "hello";
let rrstr: &&str = &rstr;
let rrrstr: &&&str = &rrstr;
let _: String = rstr.to_string();
let _: String = rrstr.to_string();
let _: String = rrrstr.to_string();
let string: String = String::from("hello");
let rstring: &String = &string;
let rrstring: &&... | main | identifier_name |
inefficient_to_string.rs | // run-rustfix
#![deny(clippy::inefficient_to_string)]
use std::borrow::Cow;
fn main() {
let rstr: &str = "hello";
let rrstr: &&str = &rstr;
let rrrstr: &&&str = &rrstr; | let rstring: &String = &string;
let rrstring: &&String = &rstring;
let rrrstring: &&&String = &rrstring;
let _: String = string.to_string();
let _: String = rstring.to_string();
let _: String = rrstring.to_string();
let _: String = rrrstring.to_string();
let cow: Cow<'_, str> = Cow::Bor... | let _: String = rstr.to_string();
let _: String = rrstr.to_string();
let _: String = rrrstr.to_string();
let string: String = String::from("hello"); | random_line_split |
inefficient_to_string.rs | // run-rustfix
#![deny(clippy::inefficient_to_string)]
use std::borrow::Cow;
fn main() | let rrrcow: &&&Cow<'_, str> = &rrcow;
let _: String = cow.to_string();
let _: String = rcow.to_string();
let _: String = rrcow.to_string();
let _: String = rrrcow.to_string();
}
| {
let rstr: &str = "hello";
let rrstr: &&str = &rstr;
let rrrstr: &&&str = &rrstr;
let _: String = rstr.to_string();
let _: String = rrstr.to_string();
let _: String = rrrstr.to_string();
let string: String = String::from("hello");
let rstring: &String = &string;
let rrstring: &&Str... | identifier_body |
lib.rs |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The arena, a f... |
let ptr: &mut T = unsafe {
let ptr: &mut T = mem::transmute(self.ptr);
ptr::write(ptr, object);
self.ptr.set(self.ptr.get().offset(1));
ptr
};
ptr
}
/// Grows the arena.
#[inline(never)]
fn grow(&self) {
unsafe {
... | {
self.grow()
} | conditional_block |
lib.rs |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The arena, a f... | <T> {
/// Pointer to the next arena segment.
next: *mut TypedArenaChunk<T>,
/// The number of elements that this chunk can hold.
capacity: uint,
// Objects follow here, suitably aligned.
}
fn calculate_size<T>(capacity: uint) -> uint {
let mut size = mem::size_of::<TypedArenaChunk<T>>();
... | TypedArenaChunk | identifier_name |
lib.rs |
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The arena, ... | }
/// Allocates a new Arena with `initial_size` bytes preallocated.
pub fn new_with_size(initial_size: uint) -> Arena {
Arena {
head: RefCell::new(chunk(initial_size, false)),
copy_head: RefCell::new(chunk(initial_size, true)),
chunks: RefCell::new(Vec::new()),
... |
impl Arena {
/// Allocates a new Arena with 32 bytes preallocated.
pub fn new() -> Arena {
Arena::new_with_size(32u) | random_line_split |
lib.rs |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The arena, a f... |
/// Allocates an object in the `TypedArena`, returning a reference to it.
#[inline]
pub fn alloc(&self, object: T) -> &mut T {
if self.ptr == self.end {
self.grow()
}
let ptr: &mut T = unsafe {
let ptr: &mut T = mem::transmute(self.ptr);
ptr::wr... | {
unsafe {
let chunk = TypedArenaChunk::<T>::new(ptr::null_mut(), capacity);
TypedArena {
ptr: Cell::new((*chunk).start() as *const T),
end: Cell::new((*chunk).end() as *const T),
first: RefCell::new(chunk),
}
}
} | identifier_body |
cpu_timing.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use zinc64_core::{Addressable, Cpu, IoPort, IrqLine, Pin, Ram, TickFn};
use z... |
}
}
| {
let clock = Rc::new(Cell::new(0u8));
let clock_clone = clock.clone();
let tick_fn: TickFn = Rc::new(move || {
clock_clone.set(clock_clone.get().wrapping_add(1));
});
cpu.write(0x1000, opcode as u8);
cpu.write(0x1001, 0x00);
... | conditional_block |
cpu_timing.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use zinc64_core::{Addressable, Cpu, IoPort, IrqLine, Pin, Ram, TickFn};
use z... | (ram: Ram) -> Self {
MockMemory { ram }
}
}
impl Addressable for MockMemory {
fn read(&self, address: u16) -> u8 {
self.ram.read(address)
}
fn write(&mut self, address: u16, value: u8) {
self.ram.write(address, value);
}
}
fn setup_cpu() -> Cpu6510 {
let ba_line = Rc::... | new | identifier_name |
cpu_timing.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use zinc64_core::{Addressable, Cpu, IoPort, IrqLine, Pin, Ram, TickFn};
use z... | 4, // BE LDX $abcd,Y
4, // BF LAX* $abcd,Y
2, // C0 CPY #$ab
6, // C1 CMP ($ab,X)
0, // C2 SKB* #$ab
0, // C3 DCM* ($ab,X)
3, // C4 CPY $ab
3, // C5 CMP $ab
5, // C6 DEC $ab
0, // C7 DCM* $ab
2, // C8 INY
2, // C9 CMP #$ab
2, // CA DEX
2, // CB SBX* #$ab
4, //... | 4, // BC LDY $abcd,X
4, // BD LDA $abcd,X | random_line_split |
cpu_timing.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use zinc64_core::{Addressable, Cpu, IoPort, IrqLine, Pin, Ram, TickFn};
use z... |
fn write(&mut self, address: u16, value: u8) {
self.ram.write(address, value);
}
}
fn setup_cpu() -> Cpu6510 {
let ba_line = Rc::new(RefCell::new(Pin::new_high()));
let cpu_io_port = Rc::new(RefCell::new(IoPort::new(0x00, 0xff)));
let cpu_irq = Rc::new(RefCell::new(IrqLine::new("irq")));
... | {
self.ram.read(address)
} | identifier_body |
decodable.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
Named(ref fields) => {
// use the field's span to get nicer error messages.
let fields = fields.iter().enumerate().map(|(i, &(name, span))| {
cx.field_imm(span, name, getarg(span, cx.str_of(name), i))
}).collect();
cx.expr_struct_ident(o... | {
let fields = fields.iter().enumerate().map(|(i, &span)| {
getarg(span, format!("_field{}", i).to_managed(), i)
}).collect();
cx.expr_call_ident(outer_span, outer_pat_ident, fields)
} | conditional_block |
decodable.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (cx: &ExtCtxt, span: Span,
substr: &Substructure) -> @Expr {
let decoder = substr.nonself_args[0];
let recurse = ~[cx.ident_of("extra"),
cx.ident_of("serialize"),
cx.ident_of("Decodable"),
cx.ident_of("decode")];
// throw ... | decodable_substructure | identifier_name |
decodable.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | const_nonmatching: true,
combine_substructure: decodable_substructure,
},
]
};
trait_def.expand(mitem, in_items)
}
fn decodable_substructure(cx: &ExtCtxt, span: Span,
substr: &Substructure) -> @Expr {
let decoder = substr.nonse... | {
let trait_def = TraitDef {
cx: cx, span: span,
path: Path::new_(~["extra", "serialize", "Decodable"], None,
~[~Literal(Path::new_local("__D"))], true),
additional_bounds: ~[],
generics: LifetimeBounds {
lifetimes: ~[],
bounds: ~[("_... | identifier_body |
decodable.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | cx.expr_method_call(span, decoder, cx.ident_of("read_struct"),
~[cx.expr_str(span, cx.str_of(substr.type_ident)),
cx.expr_uint(span, nfields),
cx.lambda_expr_1(span, result, blkarg)])
}
Static... | cx.expr_method_call(span, blkdecoder, read_struct_field,
~[cx.expr_str(span, name),
cx.expr_uint(span, field),
lambdadecode])
}); | random_line_split |
evaluator.rs | //
// This file is part of zero_sum.
//
// zero_sum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// zero_sum is distributed in... |
}
/// Implement arithmetic operators (`Add`, `Sub`, `Mul`, `Neg`, `Div`) and `Display` for a tuple
/// struct in terms of the enclosed type.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate zero_sum;
/// # use zero_sum::analysis::Evaluation;
/// # use std::fmt;
/// use std::i32;
/// use std::ops::{... | {
let mut state = state.clone();
if let Err(error) = state.execute_plies(plies) {
panic!("Error calculating evaluation: {}", error);
}
if plies.len() % 2 == 0 {
self.evaluate(&state)
} else {
-self.evaluate(&state)
}
} | identifier_body |
evaluator.rs | //
// This file is part of zero_sum.
//
// zero_sum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// zero_sum is distributed in... | /// This is usually a tuple around a signed numeric type.
///
/// # Example
///
/// There is a [helper macro](../macro.prepare_evaluation_tuple.html) to facilitate the implementation of tuple structs:
///
/// ```rust
/// #[macro_use]
/// extern crate zero_sum;
/// # use zero_sum::analysis::Evaluation;
/// # use std::fm... | random_line_split | |
evaluator.rs | //
// This file is part of zero_sum.
//
// zero_sum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// zero_sum is distributed in... | () -> Self { -Self::win() }
/// The maximum value representable. This must be safely negatable.
fn max() -> Self;
/// The minimum value representable.
fn min() -> Self { -Self::max() }
/// Returns `true` if this evaluation contains a win. This is usually a check to
/// see if the value is abov... | lose | identifier_name |
evaluator.rs | //
// This file is part of zero_sum.
//
// zero_sum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// zero_sum is distributed in... |
}
}
/// Implement arithmetic operators (`Add`, `Sub`, `Mul`, `Neg`, `Div`) and `Display` for a tuple
/// struct in terms of the enclosed type.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate zero_sum;
/// # use zero_sum::analysis::Evaluation;
/// # use std::fmt;
/// use std::i32;
/// use std::... | {
-self.evaluate(&state)
} | conditional_block |
main.rs | extern crate clap;
extern crate yaml_rust;
extern crate lxd;
use std::env;
use std::fs::File;
use std::io::Read;
use clap::{App, Arg, ArgMatches, SubCommand};
use yaml_rust::YamlLoader;
use lxd::{Container,LxdServer};
fn create_dividing_line(widths: &Vec<usize>) -> String {
let mut dividing_line = String::new(... |
fn list(matches: &ArgMatches) {
let home_dir = env::var("HOME").unwrap();
let mut config_file = File::open(home_dir.clone() + "/.config/lxc/config.yml").unwrap();
let mut file_contents = String::new();
config_file.read_to_string(&mut file_contents).unwrap();
let lxd_config = YamlLoader::load_from_... | {
let mut ipv4_address = String::new();
let mut ipv6_address = String::new();
for ip in &c.status.ips {
if ip.protocol == "IPV4" && ip.address != "127.0.0.1" {
ipv4_address = ip.address.clone();
}
if ip.protocol == "IPV6" && ip.address != "::1" {
ipv6_address ... | identifier_body |
main.rs | extern crate clap;
extern crate yaml_rust;
extern crate lxd;
use std::env;
use std::fs::File;
use std::io::Read;
use clap::{App, Arg, ArgMatches, SubCommand};
use yaml_rust::YamlLoader;
use lxd::{Container,LxdServer};
fn create_dividing_line(widths: &Vec<usize>) -> String {
let mut dividing_line = String::new(... | (item: &Vec<String>, widths: &Vec<usize>) -> String {
let mut content_line = String::new();
content_line.push_str("|");
for (n, column_content) in item.iter().enumerate() {
content_line.push_str(" ");
content_line.push_str(&format!("{:1$}", &column_content, widths[n] + 1));
content_l... | create_content_line | identifier_name |
main.rs | extern crate clap;
extern crate yaml_rust;
extern crate lxd;
use std::env;
use std::fs::File;
use std::io::Read;
use clap::{App, Arg, ArgMatches, SubCommand};
use yaml_rust::YamlLoader;
use lxd::{Container,LxdServer};
fn create_dividing_line(widths: &Vec<usize>) -> String {
let mut dividing_line = String::new(... |
match matches.subcommand_name() {
Some("list") => list(matches.subcommand_matches("list").unwrap()),
_ => println!("{}", matches.usage()),
}
} | .index(1)))
.get_matches(); | random_line_split |
main.rs | extern crate clap;
extern crate yaml_rust;
extern crate lxd;
use std::env;
use std::fs::File;
use std::io::Read;
use clap::{App, Arg, ArgMatches, SubCommand};
use yaml_rust::YamlLoader;
use lxd::{Container,LxdServer};
fn create_dividing_line(widths: &Vec<usize>) -> String {
let mut dividing_line = String::new(... |
if ip.protocol == "IPV6" && ip.address!= "::1" {
ipv6_address = ip.address.clone();
}
}
let ephemeral = if c.ephemeral { "YES" } else { "NO" };
vec![c.name.clone(), c.status.status.clone().to_uppercase(), ipv4_address.to_string(), ipv6_address.to_string(), ephemeral.to_string(),... | {
ipv4_address = ip.address.clone();
} | conditional_block |
string.rs | /*
* Copyright (c) 2016 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... | }
result.push_str(&string);
}
result
} | result.push('-'); | random_line_split |
string.rs | /*
* Copyright (c) 2016 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... | underscore = false;
}
}
camel
}
/// Transform a camel case command name to its dashed version.
/// WinOpen is transformed to win-open.
pub fn to_dash_name(name: &str) -> String {
let mut result = String::new();
for (index, character) in name.chars().enumerate() {
let string... | {
let mut chars = string.chars();
let string =
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
};
let mut camel = String::new();
let mut underscore = false;
for character in string.chars() {... | identifier_body |
string.rs | /*
* Copyright (c) 2016 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... | (name: &str) -> String {
let mut result = String::new();
for (index, character) in name.chars().enumerate() {
let string: String = character.to_lowercase().collect();
if character.is_uppercase() && index > 0 {
result.push('-');
}
result.push_str(&string);
}
re... | to_dash_name | identifier_name |
histogram.rs | /*
* Copyright (C) 2013 The Android Open Source Project
*
* 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 required by app... | return gClear;
} | return 0xff;
} | random_line_split |
project-fn-ret-contravariant.rs | #![feature(unboxed_closures)]
#![feature(rustc_attrs)]
// Test for projection cache. We should be able to project distinct
// lifetimes from `foo` as we reinstantiate it multiple times, but not
// if we do it just once. In this variant, the region `'a` is used in
// an contravariant position, which affects the results... | <T>(t: T, x: T::Output) -> T::Output
where T: FnOnce<()>
{
t()
}
#[cfg(ok)] // two instantiations: OK
fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let a = bar(foo, x);
let b = bar(foo, y);
(a, b)
}
#[cfg(oneuse)] // one instantiation: OK (surprisingly)
fn baz<'a,'b>(x: &'a u32, y:... | bar | identifier_name |
project-fn-ret-contravariant.rs | #![feature(unboxed_closures)]
#![feature(rustc_attrs)]
// Test for projection cache. We should be able to project distinct
// lifetimes from `foo` as we reinstantiate it multiple times, but not
// if we do it just once. In this variant, the region `'a` is used in
// an contravariant position, which affects the results... |
#[cfg(transmute)] // one instantiations: BAD
fn baz<'a,'b>(x: &'a u32) -> &'static u32 {
bar(foo, x) //[transmute]~ ERROR E0759
}
#[cfg(krisskross)] // two instantiations, mixing and matching: BAD
fn transmute<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let a = bar(foo, y);
let b = bar(foo, x);
... | (a, b)
} | random_line_split |
project-fn-ret-contravariant.rs | #![feature(unboxed_closures)]
#![feature(rustc_attrs)]
// Test for projection cache. We should be able to project distinct
// lifetimes from `foo` as we reinstantiate it multiple times, but not
// if we do it just once. In this variant, the region `'a` is used in
// an contravariant position, which affects the results... |
#[cfg(oneuse)] // one instantiation: OK (surprisingly)
fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let f /* : fn() -> &'static u32 */ = foo; // <-- inferred type annotated
let a = bar(f, x); // this is considered ok because fn args are contravariant...
let b = bar(f, y); //...and hence w... | {
let a = bar(foo, x);
let b = bar(foo, y);
(a, b)
} | identifier_body |
glue.rs | <'blk, 'tcx>(cx: Block<'blk, 'tcx>,
v: ValueRef,
size: ValueRef,
align: ValueRef,
debug_loc: DebugLoc)
->... | trans_exchange_free_dyn | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.