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 |
|---|---|---|---|---|
to_twos_complement_limbs.rs | use malachite_base::num::arithmetic::traits::WrappingNegAssign;
use malachite_nz::natural::arithmetic::sub::limbs_sub_limb_in_place;
use malachite_nz::natural::logic::not::limbs_not_in_place;
use malachite_nz::platform::Limb;
pub fn limbs_twos_complement_in_place_alt_1(limbs: &mut [Limb]) -> bool {
let i = limbs.i... | } | random_line_split | |
to_twos_complement_limbs.rs | use malachite_base::num::arithmetic::traits::WrappingNegAssign;
use malachite_nz::natural::arithmetic::sub::limbs_sub_limb_in_place;
use malachite_nz::natural::logic::not::limbs_not_in_place;
use malachite_nz::platform::Limb;
pub fn | (limbs: &mut [Limb]) -> bool {
let i = limbs.iter().cloned().take_while(|&x| x == 0).count();
let len = limbs.len();
if i == len {
return true;
}
limbs[i].wrapping_neg_assign();
let j = i + 1;
if j!= len {
limbs_not_in_place(&mut limbs[j..]);
}
false
}
pub fn limbs_t... | limbs_twos_complement_in_place_alt_1 | identifier_name |
to_twos_complement_limbs.rs | use malachite_base::num::arithmetic::traits::WrappingNegAssign;
use malachite_nz::natural::arithmetic::sub::limbs_sub_limb_in_place;
use malachite_nz::natural::logic::not::limbs_not_in_place;
use malachite_nz::platform::Limb;
pub fn limbs_twos_complement_in_place_alt_1(limbs: &mut [Limb]) -> bool {
let i = limbs.i... | {
let carry = limbs_sub_limb_in_place(limbs, 1);
limbs_not_in_place(limbs);
carry
} | identifier_body | |
packed-struct-layout.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 ... |
pub fn main() {
unsafe {
let s4 = S4 { a: 1, b: [2,3,4] };
let transd : [u8; 4] = mem::transmute(s4);
assert_eq!(transd, [1, 2, 3, 4]);
let s5 = S5 { a: 1, b: 0xff_00_00_ff };
let transd : [u8; 5] = mem::transmute(s5);
// Don't worry about endianness, the u32 is pal... | a: u8,
b: u32
} | random_line_split |
packed-struct-layout.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 ... | () {
unsafe {
let s4 = S4 { a: 1, b: [2,3,4] };
let transd : [u8; 4] = mem::transmute(s4);
assert_eq!(transd, [1, 2, 3, 4]);
let s5 = S5 { a: 1, b: 0xff_00_00_ff };
let transd : [u8; 5] = mem::transmute(s5);
// Don't worry about endianness, the u32 is palindromic.
... | main | identifier_name |
light.rs | use ::types::Vec3f;
use ::types::Color;
pub trait Light {
/// Light direction
/// v: Point to illuminate
/// Returns the direction of light rays pointing from v
fn direction(&self, v: Vec3f) -> Vec3f;
/// Light illumincation
/// v: Point to illuminate
/// Returns the color of the ligh... | }
pub struct PointLight {
position: Vec3f,
color: Color,
}
impl PointLight {
pub fn new(position: Vec3f, color: Color) -> Self {
Self {
position,
color
}
}
pub fn set_position(&mut self, position: Vec3f) {
self.position = position;
}
fn pos... | /// Line index of the closest shadow ray intesection
/// Where the point is in shadow
fn shadow(&self, t: f64) -> bool; | random_line_split |
light.rs | use ::types::Vec3f;
use ::types::Color;
pub trait Light {
/// Light direction
/// v: Point to illuminate
/// Returns the direction of light rays pointing from v
fn direction(&self, v: Vec3f) -> Vec3f;
/// Light illumincation
/// v: Point to illuminate
/// Returns the color of the ligh... | (&self, t: f64) -> bool {
t < 1.0
}
} | shadow | identifier_name |
light.rs | use ::types::Vec3f;
use ::types::Color;
pub trait Light {
/// Light direction
/// v: Point to illuminate
/// Returns the direction of light rays pointing from v
fn direction(&self, v: Vec3f) -> Vec3f;
/// Light illumincation
/// v: Point to illuminate
/// Returns the color of the ligh... |
fn position(&self) -> &Vec3f {
&self.position
}
}
impl Light for PointLight {
fn direction(&self, v: Vec3f) -> Vec3f {
self.position - v
}
fn illumination(&self, v: Vec3f) -> Color {
self.color
}
fn shadow(&self, t: f64) -> bool {
t < 1.0
}
} | {
self.position = position;
} | identifier_body |
encoding.rs | // Copyright 2013-2014 Simon Sapin.
//
// 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 accordi... | .and_then(encoding_from_whatwg_label)
.map(EncodingOverride::from_encoding)
}
pub fn is_utf8(&self) -> bool {
self.encoding.is_none()
}
pub fn decode(&self, input: &[u8]) -> String {
match self.encoding {
Some(encoding) => encoding.decode(input, DecoderTrap::R... | random_line_split | |
encoding.rs | // Copyright 2013-2014 Simon Sapin.
//
// 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 accordi... | ;
#[cfg(not(feature = "query_encoding"))]
impl EncodingOverride {
pub fn utf8() -> EncodingOverride {
EncodingOverride
}
pub fn lookup(_label: &[u8]) -> Option<EncodingOverride> {
None
}
pub fn is_utf8(&self) -> bool {
true
}
pub fn decode(&self, input: &[u8]) -> ... | EncodingOverride | 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() |
#[cfg(feature = "window")]
fn main() {
// 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: ");
... | { println!("This example requires glutin to be compiled with the `window` feature"); } | identifier_body |
fullscreen.rs | #[cfg(target_os = "android")]
#[macro_use] | 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 = "window")]
fn main() {
// enumerating monitors
let monitor = {
... | extern crate android_glue;
| random_line_split |
user.rs | import_controller_generic_requeriments!();
use dal::models::user::{User, UpdateUser};
use dal::models::post::{Post};
pub fn get(req: &mut Request) -> IronResult<Response>{
let connection = req.get_db_conn();
let logger = req.get_logger();
let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("U... | {
let connection = req.get_db_conn();
let logger = req.get_logger();
let user_id = req.get_user_data().id;
let posts = Post::get_post_from_user(user_id, &connection, &logger);
response_ok(&posts)
} | identifier_body | |
user.rs | import_controller_generic_requeriments!();
use dal::models::user::{User, UpdateUser};
use dal::models::post::{Post};
pub fn get(req: &mut Request) -> IronResult<Response>{
let connection = req.get_db_conn();
let logger = req.get_logger();
let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("U... | (req: &mut Request) -> IronResult<Response> {
response_ok(&req.get_user_data())
}
pub fn delete(req: &mut Request) -> IronResult<Response> {
let connection = req.get_db_conn();
let logger = req.get_logger();
let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found"));
let quatity... | get_me | identifier_name |
user.rs | import_controller_generic_requeriments!();
use dal::models::user::{User, UpdateUser}; | pub fn get(req: &mut Request) -> IronResult<Response>{
let connection = req.get_db_conn();
let logger = req.get_logger();
let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found"));
let user_data = some_or_return!(
User::get_by_id(user_id, &connection, &logger),
response_not_... | use dal::models::post::{Post};
| random_line_split |
dyn.rs | use rstest::*;
#[fixture]
fn dyn_box() -> Box<dyn Iterator<Item=i32>> {
Box::new(std::iter::once(42))
}
#[fixture]
fn dyn_ref() -> &'static dyn ToString {
&42
}
#[fixture]
fn dyn_box_resolve(mut dyn_box: Box<dyn Iterator<Item=i32>>) -> i32 {
dyn_box.next().unwrap()
}
#[fixture]
fn dyn_ref_resolve(dyn_re... |
#[rstest]
fn test_dyn_box_resolve(dyn_box_resolve: i32) {
assert_eq!(42, dyn_box_resolve)
}
#[rstest]
fn test_dyn_ref_resolve(dyn_ref_resolve: String) {
assert_eq!("42", dyn_ref_resolve)
}
| {
assert_eq!("42", dyn_ref.to_string())
} | identifier_body |
dyn.rs | use rstest::*;
#[fixture]
fn dyn_box() -> Box<dyn Iterator<Item=i32>> {
Box::new(std::iter::once(42))
}
#[fixture]
fn dyn_ref() -> &'static dyn ToString {
&42
}
#[fixture]
fn dyn_box_resolve(mut dyn_box: Box<dyn Iterator<Item=i32>>) -> i32 {
dyn_box.next().unwrap()
}
#[fixture]
fn dyn_ref_resolve(dyn_re... | (dyn_box_resolve: i32) {
assert_eq!(42, dyn_box_resolve)
}
#[rstest]
fn test_dyn_ref_resolve(dyn_ref_resolve: String) {
assert_eq!("42", dyn_ref_resolve)
}
| test_dyn_box_resolve | identifier_name |
dyn.rs | use rstest::*;
#[fixture]
fn dyn_box() -> Box<dyn Iterator<Item=i32>> {
Box::new(std::iter::once(42))
}
#[fixture]
fn dyn_ref() -> &'static dyn ToString {
&42
}
#[fixture]
fn dyn_box_resolve(mut dyn_box: Box<dyn Iterator<Item=i32>>) -> i32 {
dyn_box.next().unwrap()
}
#[fixture]
fn dyn_ref_resolve(dyn_re... | } | assert_eq!("42", dyn_ref_resolve) | random_line_split |
mod.rs | //! Provide helpers for making ioctl system calls
//!
//! Currently supports Linux on all architectures. Other platforms welcome!
//!
//! This library is pretty low-level and messy. `ioctl` is not fun.
//!
//! What is an `ioctl`?
//! ===================
//!
//! The `ioctl` syscall is the grab-bag syscall on POSIX syste... | mod platform;
pub use self::platform::*;
// liblibc has the wrong decl for linux :| hack until #26809 lands.
extern "C" {
#[doc(hidden)]
pub fn ioctl(fd: libc::c_int, req: libc::c_ulong,...) -> libc::c_int;
}
/// A hack to get the macros to work nicely.
#[doc(hidden)]
pub use ::libc as libc; | #[path = "platform/dragonfly.rs"]
#[macro_use] | random_line_split |
tournament.rs | #![feature(slice_patterns)]
#![feature(convert)]
use std::fs::File;
use std::path::Path;
use std::io::Read;
extern crate tournament;
fn file_equal(output_file: &str, expected_file: &str) {
let output = match File::open(&Path::new(output_file)) {
Err(e) => panic!("Couldn't open {}: {}", output_file, e),
... | {
assert_eq!(tournament::tally(&Path::new("tests/input3.txt"), &Path::new("tests/output3.txt")), Ok(4));
file_equal("tests/output3.txt", "tests/expected3.txt");
} | identifier_body | |
tournament.rs | #![feature(slice_patterns)]
#![feature(convert)]
use std::fs::File;
use std::path::Path;
use std::io::Read;
extern crate tournament;
fn file_equal(output_file: &str, expected_file: &str) {
let output = match File::open(&Path::new(output_file)) {
Err(e) => panic!("Couldn't open {}: {}", output_file, e),
... | () {
assert_eq!(tournament::tally(&Path::new("tests/input3.txt"), &Path::new("tests/output3.txt")), Ok(4));
file_equal("tests/output3.txt", "tests/expected3.txt");
}
| test_incomplete_competition | identifier_name |
tournament.rs | #![feature(slice_patterns)]
#![feature(convert)]
use std::fs::File;
use std::path::Path;
use std::io::Read;
extern crate tournament;
fn file_equal(output_file: &str, expected_file: &str) {
let output = match File::open(&Path::new(output_file)) {
Err(e) => panic!("Couldn't open {}: {}", output_file, e),
... | file_equal("tests/output3.txt", "tests/expected3.txt");
} | fn test_incomplete_competition() {
assert_eq!(tournament::tally(&Path::new("tests/input3.txt"), &Path::new("tests/output3.txt")), Ok(4)); | random_line_split |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
};
let s = match expr.node {
// expression is a literal
ast::ExprLit(ref lit) => match lit.node {
// string literal
ast::LitStr(ref s, _) => {
s.clone()
}
_ => {
cx.span_err(expr.span, "unsupported litera... | {
cx.span_err(span, "invalid floating point type in hexfloat!");
None
} | conditional_block |
lib.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 ... | () { }
| dummy_test | identifier_name |
lib.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 ... |
//Check if the literal is valid (as LLVM expects),
//and return a descriptive error if not.
fn hex_float_lit_err(s: &str) -> Option<(uint, String)> {
let mut chars = s.chars().peekable();
let mut i = 0;
if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
if chars.next()!= Some('0') {
return ... | {
reg.register_macro("hexfloat", expand_syntax_ext);
} | identifier_body |
lib.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 ... | "f32" => Some(ast::TyF32),
"f64" => Some(ast::TyF64),
_ => {
cx.span_err(span, "invalid floating point type in hexfloat!");
None
}
}
};
let s = match expr.node {
// expression is a literal
ast::ExprLit(ref l... | let ty = match ty_lit {
None => None,
Some(Ident{ident, span}) => match token::get_ident(ident).get() { | random_line_split |
function-arguments.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 ... |
// CHECK: @mutable_unsafe_borrow(%UnsafeInner* noalias dereferenceable(2))
//... unless this is a mutable borrow, those never alias
#[no_mangle]
pub fn mutable_unsafe_borrow(_: &mut UnsafeInner) {
}
// CHECK: @mutable_borrow(i32* noalias dereferenceable(4))
// FIXME #25759 This should also have `nocapture`
#[no_mang... | {
} | identifier_body |
function-arguments.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 ... | () -> S {
S {
_field: [0, 0, 0, 0]
}
}
// CHECK: noalias i8* @allocator()
#[no_mangle]
#[allocator]
pub fn allocator() -> *const i8 {
std::ptr::null()
}
| struct_return | identifier_name |
function-arguments.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 ... | }
}
// CHECK: noalias i8* @allocator()
#[no_mangle]
#[allocator]
pub fn allocator() -> *const i8 {
std::ptr::null()
} | // CHECK: @struct_return(%S* noalias nocapture sret dereferenceable(32))
#[no_mangle]
pub fn struct_return() -> S {
S {
_field: [0, 0, 0, 0] | random_line_split |
expr-match-generic.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() { test_bool(); test_rec(); }
| {
fn compare_rec(t1: Pair, t2: Pair) -> bool {
t1.a == t2.a && t1.b == t2.b
}
test_generic::<Pair>(Pair {a: 1, b: 2}, compare_rec);
} | identifier_body |
expr-match-generic.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 ... | , _ => fail!("wat") };
assert!((eq(expected, actual)));
}
fn test_bool() {
fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; }
test_generic::<bool>(true, compare_bool);
}
#[deriving(Clone)]
struct Pair {
a: int,
b: int,
}
fn test_rec() {
fn compare_rec(t1: Pair, t2: Pair) -> bool... | { expected.clone() } | conditional_block |
expr-match-generic.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T:Clone>(expected: T, eq: compare<T>) {
let actual: T = match true { true => { expected.clone() }, _ => fail!("wat") };
assert!((eq(expected, actual)));
}
fn test_bool() {
fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; }
test_generic::<bool>(true, compare_bool);
}
#[deriving(Clone)]
str... | test_generic | identifier_name |
expr-match-generic.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 ... |
#[deriving(Clone)]
struct Pair {
a: int,
b: int,
}
fn test_rec() {
fn compare_rec(t1: Pair, t2: Pair) -> bool {
t1.a == t2.a && t1.b == t2.b
}
test_generic::<Pair>(Pair {a: 1, b: 2}, compare_rec);
}
pub fn main() { test_bool(); test_rec(); } |
fn test_bool() {
fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; }
test_generic::<bool>(true, compare_bool);
} | random_line_split |
upload.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::str::{self, FromStr};
use anyhow::{Context, Error};
use bytes::Bytes;
use futures::{
channel::... |
let oid = Sha256::from_str(&oid).map_err(HttpError::e400)?;
let size = size.parse().map_err(Error::from).map_err(HttpError::e400)?;
let content_length: Option<u64> = read_header_value(state, CONTENT_LENGTH)
.transpose()
.map_err(HttpError::e400)?;
if let Some(content_length) = content_le... | } = state.take();
let ctx =
RepositoryRequestContext::instantiate(state, repository.clone(), LfsMethod::Upload).await?; | random_line_split |
upload.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::str::{self, FromStr};
use anyhow::{Context, Error};
use bytes::Bytes;
use futures::{
channel::... | <S>(
ctx: &RepositoryRequestContext,
oid: Sha256,
size: u64,
body: S,
scuba: &mut Option<&mut ScubaMiddlewareState>,
) -> Result<(), Error>
where
S: Stream<Item = Result<Bytes, ()>> + Unpin + Send +'static,
{
let (internal_send, internal_recv) = channel::<Result<Bytes, ()>>(BUFFER_SIZE);
... | upload_from_client | identifier_name |
example-uncommented.rs | #![feature(custom_attribute,plugin)]
#![plugin(tag_safe)]
#![allow(dead_code)]
/// RAII primitive spinlock
struct Spinlock;
/// Handle to said spinlock
struct HeldSpinlock(&'static Spinlock);
/// RAII IRQ hold
struct IRQLock;
/// Spinlock that also disables IRQs
struct | (Spinlock);
static S_NON_IRQ_SPINLOCK: Spinlock = Spinlock;
static S_IRQ_SPINLOCK: IrqSpinlock = IrqSpinlock(Spinlock);
#[deny(not_tagged_safe)] // Make the lint an error
#[req_safe(irq)] // Require this method be IRQ safe
fn irq_handler()
{
let _lock = acquire_non_irq_spinlock(&S_NON_IRQ_SPINLOCK);
//... | IrqSpinlock | identifier_name |
example-uncommented.rs | #![feature(custom_attribute,plugin)]
#![plugin(tag_safe)]
#![allow(dead_code)]
/// RAII primitive spinlock
struct Spinlock;
/// Handle to said spinlock
struct HeldSpinlock(&'static Spinlock);
/// RAII IRQ hold
struct IRQLock;
/// Spinlock that also disables IRQs
struct IrqSpinlock(Spinlock);
static S_NON_IRQ_SPINLOC... |
// vim: ts=4 sw=4 expandtab
| {
irq_handler();
} | identifier_body |
example-uncommented.rs | #![feature(custom_attribute,plugin)]
#![plugin(tag_safe)]
#![allow(dead_code)]
/// RAII primitive spinlock
struct Spinlock;
/// Handle to said spinlock
struct HeldSpinlock(&'static Spinlock);
/// RAII IRQ hold
struct IRQLock;
/// Spinlock that also disables IRQs
struct IrqSpinlock(Spinlock);
static S_NON_IRQ_SPINLOC... | irq_handler();
}
// vim: ts=4 sw=4 expandtab | {
HeldSpinlock(l)
}
fn main() { | random_line_split |
reader.rs | //! This module allows you to read from a CDB.
use helpers::{hash, unpack};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use types::{Error, Result};
use writer::Writer;
/// Allows you to read from CDB.
///
/// #Example
///
/// Given a file stored at `filename` with the following contents:
///
/// ```text
/... | (mut self) -> Result<Writer<'a, File>> {
match self.file.seek(SeekFrom::Start(self.table_start as u64)) {
Ok(_) => {
let mut index: Vec<Vec<(u32, u32)>> = vec![Vec::new(); 256];
let mut buf = &mut [0 as u8; 8];
// Read hash table until end of file to ... | as_writer | identifier_name |
reader.rs | //! This module allows you to read from a CDB.
use helpers::{hash, unpack};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use types::{Error, Result};
use writer::Writer;
/// Allows you to read from CDB.
///
/// #Example
///
/// Given a file stored at `filename` with the following contents:
///
/// ```text
/... | /// # // Do it again to make sure the iterator doesn't consume and lifetimes
/// # // work as expected.
/// # i = 0;
/// # for (_, v) in cdb_reader.into_iter() {
/// # i += 1;
/// # let s = &i.to_string();
/// # let val = s.as_bytes();
/// # assert_eq!(&v[..], &val[..]);
/// # }
/// # assert_eq!(len, i)... | /// # assert_eq!(len, i);
/// # | random_line_split |
reader.rs | //! This module allows you to read from a CDB.
use helpers::{hash, unpack};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use types::{Error, Result};
use writer::Writer;
/// Allows you to read from CDB.
///
/// #Example
///
/// Given a file stored at `filename` with the following contents:
///
/// ```text
/... |
/// Return a `Vec` of all the keys in this Read Only CDB.
///
/// Keep in mind that if there're duplicated keys, they will appear
/// multiple times in the resulting `Vec`.
pub fn keys(&mut self) -> Vec<Vec<u8>> {
let mut keys: Vec<Vec<u8>> = vec![];
for item in self.into_iter() {
... | {
let mut i = 0;
let mut values: Vec<Vec<u8>> = vec![];
loop {
match self.get_from_pos(key, i) {
Ok(v) => values.push(v),
Err(_) => break,
}
i += 1;
}
values
} | identifier_body |
path.rs | use ::inflector::Inflector;
use ::regex::Regex;
use ::syn::Ident;
use ::quote::Tokens;
use ::yaml_rust::Yaml;
use infer::method;
use infer::TokensResult;
fn mod_ident(path: &str) -> Ident {
let rustified = path.replace('/', " ").trim().to_snake_case();
let re = Regex::new(r"\{(?P<resource>[^}]+)_\}").unwrap()... | #(#method_impls)*
}
})
}
#[cfg(tests)]
mod tests {
use super::*;
#[test]
fn leading_slash() {
assert_eq!(mod_ident("/foo"), Ident::new("foo"));
}
#[test]
fn both_slash() {
assert_eq!(mod_ident("/foo/"), Ident::new("foo"));
}
#[test]
fn no_s... | random_line_split | |
path.rs | use ::inflector::Inflector;
use ::regex::Regex;
use ::syn::Ident;
use ::quote::Tokens;
use ::yaml_rust::Yaml;
use infer::method;
use infer::TokensResult;
fn mod_ident(path: &str) -> Ident {
let rustified = path.replace('/', " ").trim().to_snake_case();
let re = Regex::new(r"\{(?P<resource>[^}]+)_\}").unwrap()... |
}
Ok(quote! {
#[allow(non_snake_case)]
pub mod #path_mod {
#[allow(unused_imports)]
use ::tapioca::Body;
use ::tapioca::Client;
use ::tapioca::Url;
use ::tapioca::header;
use ::tapioca::response::Response;
#[al... | {
path_level_structs = param_structs;
} | conditional_block |
path.rs | use ::inflector::Inflector;
use ::regex::Regex;
use ::syn::Ident;
use ::quote::Tokens;
use ::yaml_rust::Yaml;
use infer::method;
use infer::TokensResult;
fn mod_ident(path: &str) -> Ident {
let rustified = path.replace('/', " ").trim().to_snake_case();
let re = Regex::new(r"\{(?P<resource>[^}]+)_\}").unwrap()... |
#[test]
fn multipart_multiresource() {
assert_eq!(mod_ident("/foo/{id}/bar/{bar_id}"), Ident::new("foo__id__bar__bar_id_"));
}
}
| {
assert_eq!(mod_ident("/foo/{id}/bar"), Ident::new("foo__id__bar"));
} | identifier_body |
path.rs | use ::inflector::Inflector;
use ::regex::Regex;
use ::syn::Ident;
use ::quote::Tokens;
use ::yaml_rust::Yaml;
use infer::method;
use infer::TokensResult;
fn mod_ident(path: &str) -> Ident {
let rustified = path.replace('/', " ").trim().to_snake_case();
let re = Regex::new(r"\{(?P<resource>[^}]+)_\}").unwrap()... | () {
assert_eq!(mod_ident("/foo/{id}/bar"), Ident::new("foo__id__bar"));
}
#[test]
fn multipart_multiresource() {
assert_eq!(mod_ident("/foo/{id}/bar/{bar_id}"), Ident::new("foo__id__bar__bar_id_"));
}
}
| multipart_resource | identifier_name |
where-clauses.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self, other: &T) -> bool {
self == other
}
fn equals<U,X>(&self, this: &U, other: &U, x: &X, y: &X) -> bool
where U: Eq, X: Eq {
this == other && x == y
}
}
fn equal<T>(x: &T, y: &T) -> bool where T: Eq {
x == y
}
fn main() {
println!("{}", equal(&1, &2));
println... | equal | identifier_name |
where-clauses.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
println!("{}", equal(&1, &2));
println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
} | identifier_body | |
where-clauses.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
impl<T> Equal for T where T: Eq {
fn equal(&self, other: &T) -> bool {
self == other
}
fn equals<U,X>(&self, this: &U, other: &U, x: &X, y: &X) -> bool
where U: Eq, X: Eq {
this == other && x == y
}
}
fn equal<T>(x: &T, y: &T) -> bool where T: Eq {
x == y
}
fn main() {... | } | random_line_split |
completion.rs | //! Completion API
use std::borrow::Cow::{self, Borrowed, Owned};
use std::fs;
use std::path::{self, Path};
use super::Result;
use line_buffer::LineBuffer;
use memchr::memchr;
// TODO: let the implementers choose/find word boudaries???
// (line, pos) is like (rl_line_buffer, rl_point) to make contextual completion
//... | (
mut input: String,
esc_char: Option<char>,
break_chars: &[u8],
quote: Quote,
) -> String {
if quote == Quote::Single {
return input; // no escape in single quotes
}
let n = input
.bytes()
.filter(|b| memchr(*b, break_chars).is_some())
.count();
if n == 0 {
... | escape | identifier_name |
completion.rs | //! Completion API
use std::borrow::Cow::{self, Borrowed, Owned};
use std::fs;
use std::path::{self, Path};
use super::Result;
use line_buffer::LineBuffer;
use memchr::memchr;
// TODO: let the implementers choose/find word boudaries???
// (line, pos) is like (rl_line_buffer, rl_point) to make contextual completion
//... | );
assert_eq!(
Some((0, super::Quote::Double)),
super::find_unclosed_quote("\"c:\\users\\All Users\\")
)
}
} | random_line_split | |
completion.rs | //! Completion API
use std::borrow::Cow::{self, Borrowed, Owned};
use std::fs;
use std::path::{self, Path};
use super::Result;
use line_buffer::LineBuffer;
use memchr::memchr;
// TODO: let the implementers choose/find word boudaries???
// (line, pos) is like (rl_line_buffer, rl_point) to make contextual completion
//... |
}
impl<'c, C:?Sized + Completer> Completer for &'c C {
type Candidate = C::Candidate;
fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)> {
(**self).complete(line, pos)
}
fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) {
(**self).u... | {
unreachable!()
} | identifier_body |
completion.rs | //! Completion API
use std::borrow::Cow::{self, Borrowed, Owned};
use std::fs;
use std::path::{self, Path};
use super::Result;
use line_buffer::LineBuffer;
use memchr::memchr;
// TODO: let the implementers choose/find word boudaries???
// (line, pos) is like (rl_line_buffer, rl_point) to make contextual completion
//... |
Some(&candidate[0..longest_common_prefix])
}
#[derive(PartialEq)]
enum ScanMode {
DoubleQuote,
Escape,
EscapeInDoubleQuote,
Normal,
SingleQuote,
}
/// try to find an unclosed single/double quote in `s`.
/// Return `None` if no unclosed quote is found.
/// Return the unclosed quote position an... | {
return None;
} | conditional_block |
event_pad_axis.rs | // Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use gdk_sys;
use glib::translate::*;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash... |
pub fn get_mode(&self) -> u32 {
self.as_ref().mode
}
pub fn get_value(&self) -> f64 {
self.as_ref().value
}
}
| {
self.as_ref().index
} | identifier_body |
event_pad_axis.rs | // Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use gdk_sys;
use glib::translate::*;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash... | (&self) -> u32 {
self.as_ref().group
}
pub fn get_index(&self) -> u32 {
self.as_ref().index
}
pub fn get_mode(&self) -> u32 {
self.as_ref().mode
}
pub fn get_value(&self) -> f64 {
self.as_ref().value
}
}
| get_group | identifier_name |
event_pad_axis.rs | // Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use gdk_sys;
use glib::translate::*;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash... | }
pub fn get_value(&self) -> f64 {
self.as_ref().value
}
} | pub fn get_mode(&self) -> u32 {
self.as_ref().mode | random_line_split |
mod.rs | mod serialize;
/// Handle to a dock
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct DockHandle(pub u64);
/// Holds information about the plugin view, data and handle
#[derive(Debug, Clone)]
pub struct Dock {
pub handle: DockHandle,
pub plugin_name: String,
pub plugin_data: Option<Vec<String>>,
}
impl... |
}
#[cfg(test)]
mod test {
extern crate serde_json;
use super::{Dock, DockHandle};
#[test]
fn test_dockhandle_serialize() {
let handle_in = DockHandle(0x1337);
let serialized = serde_json::to_string(&handle_in).unwrap();
let handle_out: DockHandle = serde_json::from_str(&serial... | {
Dock {
handle: dock_handle,
plugin_name: plugin_name.to_owned(),
plugin_data: None,
}
} | identifier_body |
mod.rs | mod serialize;
/// Handle to a dock
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct DockHandle(pub u64);
/// Holds information about the plugin view, data and handle
#[derive(Debug, Clone)]
pub struct Dock {
pub handle: DockHandle,
pub plugin_name: String,
pub plugin_data: Option<Vec<String>>,
}
impl... | let dock_in = Dock {
handle: DockHandle(1),
plugin_name: "disassembly".to_owned(),
plugin_data: None,
};
let serialized = serde_json::to_string(&dock_in).unwrap();
let dock_out: Dock = serde_json::from_str(&serialized).unwrap();
assert_eq!(do... | #[test]
fn test_dock_serialize_0() { | random_line_split |
mod.rs | mod serialize;
/// Handle to a dock
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct DockHandle(pub u64);
/// Holds information about the plugin view, data and handle
#[derive(Debug, Clone)]
pub struct Dock {
pub handle: DockHandle,
pub plugin_name: String,
pub plugin_data: Option<Vec<String>>,
}
impl... | () {
let dock_in = Dock {
handle: DockHandle(1),
plugin_name: "registers".to_owned(),
plugin_data: Some(vec!["some_data".to_owned(), "more_data".to_owned()]),
};
let serialized = serde_json::to_string(&dock_in).unwrap();
let dock_out: Dock = serde_jso... | test_dock_serialize_1 | identifier_name |
smoke.rs | use futures::StreamExt;
use opentelemetry::global::shutdown_tracer_provider;
use opentelemetry::trace::{Span, SpanKind, Tracer};
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_proto::tonic::collector::trace::v1::{
trace_service_server::{TraceService, TraceServiceServer},
ExportTraceServiceRequest, ... | () {
println!("Starting server setup...");
let (addr, mut req_rx) = setup().await;
{
println!("Installing tracer...");
let mut metadata = tonic::metadata::MetadataMap::new();
metadata.insert("x-header-key", "header-value".parse().unwrap());
let tracer = opentelemetry_otlp::n... | smoke_tracer | identifier_name |
smoke.rs | use futures::StreamExt;
use opentelemetry::global::shutdown_tracer_provider;
use opentelemetry::trace::{Span, SpanKind, Tracer};
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_proto::tonic::collector::trace::v1::{
trace_service_server::{TraceService, TraceServiceServer},
ExportTraceServiceRequest, ... |
s
});
let (req_tx, req_rx) = mpsc::channel(10);
let service = TraceServiceServer::new(MockServer::new(req_tx));
tokio::task::spawn(async move {
tonic::transport::Server::builder()
.add_service(service)
.serve_with_incoming(stream)
.await
.exp... | {
println!("Got new conn at {}", s.peer_addr().unwrap());
} | conditional_block |
smoke.rs | use futures::StreamExt;
use opentelemetry::global::shutdown_tracer_provider;
use opentelemetry::trace::{Span, SpanKind, Tracer};
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_proto::tonic::collector::trace::v1::{
trace_service_server::{TraceService, TraceServiceServer},
ExportTraceServiceRequest, ... | .with_metadata(metadata),
)
.install_batch(opentelemetry::runtime::Tokio)
.expect("failed to install");
println!("Sending span...");
let mut span = tracer
.span_builder("my-test-span")
.with_kind(SpanKind::Server)
.st... | random_line_split | |
smoke.rs | use futures::StreamExt;
use opentelemetry::global::shutdown_tracer_provider;
use opentelemetry::trace::{Span, SpanKind, Tracer};
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_proto::tonic::collector::trace::v1::{
trace_service_server::{TraceService, TraceServiceServer},
ExportTraceServiceRequest, ... | let mut span = tracer
.span_builder("my-test-span")
.with_kind(SpanKind::Server)
.start(&tracer);
span.add_event("my-test-event", vec![]);
span.end();
shutdown_tracer_provider();
}
println!("Waiting for request...");
let req = req_rx.recv().... | {
println!("Starting server setup...");
let (addr, mut req_rx) = setup().await;
{
println!("Installing tracer...");
let mut metadata = tonic::metadata::MetadataMap::new();
metadata.insert("x-header-key", "header-value".parse().unwrap());
let tracer = opentelemetry_otlp::new_... | identifier_body |
main.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 ... | () {
remap_path_prefix_aux::some_aux_function();
aux_mod::some_aux_mod_function();
some_aux_mod_function();
}
// Here we check that local debuginfo is mapped correctly.
// CHECK:!DIFile(filename: "/the/src/remap_path_prefix/main.rs", directory: "/the/cwd/")
// And here that debuginfo from other crates are... | main | identifier_name |
main.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 ... | include!("aux_mod.rs");
// Here we check that the expansion of the file!() macro is mapped.
// CHECK: @0 = private unnamed_addr constant <{ [34 x i8] }> <{ [34 x i8] c"/the/src/remap_path_prefix/main.rs" }>, align 1
pub static FILE_PATH: &'static str = file!();
fn main() {
remap_path_prefix_aux::some_aux_function... |
// Here we check that submodules and include files are found using the path without
// remapping. This test requires that rustc is called with an absolute path.
mod aux_mod; | random_line_split |
main.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 ... |
// Here we check that local debuginfo is mapped correctly.
// CHECK:!DIFile(filename: "/the/src/remap_path_prefix/main.rs", directory: "/the/cwd/")
// And here that debuginfo from other crates are expanded to absolute paths.
// CHECK:!DIFile(filename: "/the/aux-src/remap_path_prefix_aux.rs", directory: "")
| {
remap_path_prefix_aux::some_aux_function();
aux_mod::some_aux_mod_function();
some_aux_mod_function();
} | identifier_body |
p011.rs | #![feature(core)]
use euler::*; mod euler;
#[no_mangle]
pub extern "C" fn solution() -> EulerType {
let g = [
[8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, ... | () { print_euler(solution()) }
| main | identifier_name |
p011.rs | #![feature(core)]
use euler::*; mod euler;
#[no_mangle] | [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
[52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66... | pub extern "C" fn solution() -> EulerType {
let g = [
[8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8], | random_line_split |
p011.rs | #![feature(core)]
use euler::*; mod euler;
#[no_mangle]
pub extern "C" fn solution() -> EulerType | [20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
[1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48u64],
];
EulerU(
(0.. 20).map(|j|
(0.. 20 - 4).map(|i|
max(
(0.. 4).map(|k| g[j][i + k]).product(),
(0.. 4).map(|k| g[i + k][j]).produ... | {
let g = [
[8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
[52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32... | identifier_body |
regions-close-over-type-parameter-multiple.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 make_object_good2<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'b> {
// A outlives 'a AND 'b...
box v as Box<SomeTrait+'b> //...hence this type is safe.
}
fn make_object_bad<'a,'b,'c,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'c> {
// A outlives 'a AND 'b...but not 'c.
box v as Box<SomeTrait+'a>... | {
// A outlives 'a AND 'b...
box v as Box<SomeTrait+'a> // ...hence this type is safe.
} | identifier_body |
regions-close-over-type-parameter-multiple.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 ... | // A outlives 'a AND 'b...
box v as Box<SomeTrait+'a> //...hence this type is safe.
}
fn make_object_good2<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'b> {
// A outlives 'a AND 'b...
box v as Box<SomeTrait+'b> //...hence this type is safe.
}
fn make_object_bad<'a,'b,'c,A:SomeTrait+'a+'b>(v: A) ->... | trait SomeTrait { fn get(&self) -> isize; }
fn make_object_good1<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'a> { | random_line_split |
regions-close-over-type-parameter-multiple.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 ... | <'a,'b,'c,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'c> {
// A outlives 'a AND 'b...but not 'c.
box v as Box<SomeTrait+'a> //~ ERROR cannot infer an appropriate lifetime
}
fn main() {
}
| make_object_bad | identifier_name |
generators.rs | // build-fail
// compile-flags:-Zpolymorphize=on
#![feature(generic_const_exprs, generators, generator_trait, rustc_attrs)]
//~^ WARN the feature `generic_const_exprs` is incomplete
use std::marker::Unpin;
use std::ops::{Generator, GeneratorState};
use std::pin::Pin;
enum YieldOrReturn<Y, R> {
Yield(Y),
Retur... | <T>() -> impl Generator<(), Yield = u32, Return = u32> + Unpin {
//~^ ERROR item has unused generic parameters
|| {
//~^ ERROR item has unused generic parameters
yield 1;
2
}
}
#[rustc_polymorphize_error]
pub fn used_type_in_yield<Y: Default>() -> impl Generator<(), Yield = Y, Retur... | unused_type | identifier_name |
generators.rs | // build-fail
// compile-flags:-Zpolymorphize=on
#![feature(generic_const_exprs, generators, generator_trait, rustc_attrs)]
//~^ WARN the feature `generic_const_exprs` is incomplete
use std::marker::Unpin;
use std::ops::{Generator, GeneratorState};
use std::pin::Pin;
enum YieldOrReturn<Y, R> {
Yield(Y),
Retur... | }
#[rustc_polymorphize_error]
pub fn used_type_in_return<R: Default>() -> impl Generator<(), Yield = u32, Return = R> + Unpin {
|| {
yield 3;
R::default()
}
}
#[rustc_polymorphize_error]
pub fn unused_const<const T: u32>() -> impl Generator<(), Yield = u32, Return = u32> + Unpin {
//~^ ERR... | random_line_split | |
env.rs | use std::process::Command;
use std::str;
static PROGNAME: &'static str = "./env";
#[test]
fn test_single_name_value_pair() {
let po = Command::new(PROGNAME)
.arg("FOO=bar")
.output()
.unwrap_or_else(|err| panic!("{}", err));
let out = str::from_utf8(&po.stdout[..]).unwrap();
assert!(... |
#[test]
fn test_unset_variable() {
// This test depends on the HOME variable being pre-defined by the
// default shell
let po = Command::new(PROGNAME)
.arg("-u")
.arg("HOME")
.output()
.unwrap_or_else(|err| panic!("{}", err));
let out = str::from_utf8(&po.stdout[..]).unwra... | {
let po = Command::new(PROGNAME)
.arg("-i")
.arg("--null")
.arg("FOO=bar")
.arg("ABC=xyz")
.output()
.unwrap_or_else(|err| panic!("{}", err));
let out = str::from_utf8(&po.stdout[..]).unwrap();
assert_eq!(out, "FOO=bar\0ABC=xyz\0");
} | identifier_body |
env.rs | use std::process::Command;
use std::str;
static PROGNAME: &'static str = "./env";
#[test]
fn test_single_name_value_pair() {
let po = Command::new(PROGNAME)
.arg("FOO=bar")
.output()
.unwrap_or_else(|err| panic!("{}", err));
let out = str::from_utf8(&po.stdout[..]).unwrap();
assert!(... | () {
// This test depends on the HOME variable being pre-defined by the
// default shell
let po = Command::new(PROGNAME)
.arg("-u")
.arg("HOME")
.output()
.unwrap_or_else(|err| panic!("{}", err));
let out = str::from_utf8(&po.stdout[..]).unwrap();
assert_eq!(out.lines_an... | test_unset_variable | identifier_name |
env.rs | use std::str;
static PROGNAME: &'static str = "./env";
#[test]
fn test_single_name_value_pair() {
let po = Command::new(PROGNAME)
.arg("FOO=bar")
.output()
.unwrap_or_else(|err| panic!("{}", err));
let out = str::from_utf8(&po.stdout[..]).unwrap();
assert!(out.lines_any().any(|line| ... | use std::process::Command; | random_line_split | |
name.rs | /*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* 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 ap... | {
#![allow(clippy::dbg_macro, clippy::print_stdout)]
let rdata = Name::from_ascii("WWW.example.com.").unwrap();
let mut bytes = Vec::new();
let mut encoder: BinEncoder = BinEncoder::new(&mut bytes);
assert!(emit(&mut encoder, &rdata).is_ok());
let bytes = encoder.into_bytes();
println!("b... | identifier_body | |
name.rs | /*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* 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 ap... | /// by the corresponding lowercase US-ASCII letters;
/// ```
pub fn emit(encoder: &mut BinEncoder, name_data: &Name) -> ProtoResult<()> {
let is_canonical_names = encoder.is_canonical_names();
name_data.emit_with_lowercase(encoder, is_canonical_names)?;
Ok(())
}
#[test]
pub fn test() {
#![allow(... | random_line_split | |
name.rs | /*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* 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 ap... | () {
#![allow(clippy::dbg_macro, clippy::print_stdout)]
let rdata = Name::from_ascii("WWW.example.com.").unwrap();
let mut bytes = Vec::new();
let mut encoder: BinEncoder = BinEncoder::new(&mut bytes);
assert!(emit(&mut encoder, &rdata).is_ok());
let bytes = encoder.into_bytes();
println!... | test | identifier_name |
transaction.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | (json_data: &[u8]) -> Vec<String> {
let tests = ethjson::transaction::Test::load(json_data).unwrap();
let mut failed = Vec::new();
let old_schedule = evm::Schedule::new_frontier();
let new_schedule = evm::Schedule::new_homestead();
for (name, test) in tests.into_iter() {
let mut fail_unless = |cond: bool, title:... | do_json_test | identifier_name |
transaction.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | let rlp: Vec<u8> = test.rlp.into();
let res = UntrustedRlp::new(&rlp)
.as_val()
.map_err(From::from)
.and_then(|t: UnverifiedTransaction| t.validate(schedule, schedule.have_delegate_call, allow_network_id_of_one));
fail_unless(test.transaction.is_none() == res.is_err(), "Validity different");
if let (... | random_line_split | |
transaction.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | .and_then(|t: UnverifiedTransaction| t.validate(schedule, schedule.have_delegate_call, allow_network_id_of_one));
fail_unless(test.transaction.is_none() == res.is_err(), "Validity different");
if let (Some(tx), Some(sender)) = (test.transaction, test.sender) {
let t = res.unwrap();
fail_unless(public_to_a... | {
let tests = ethjson::transaction::Test::load(json_data).unwrap();
let mut failed = Vec::new();
let old_schedule = evm::Schedule::new_frontier();
let new_schedule = evm::Schedule::new_homestead();
for (name, test) in tests.into_iter() {
let mut fail_unless = |cond: bool, title: &str| if !cond { failed.push(name... | identifier_body |
lib.rs | //! This crate implements a standard linear Kalman filter and smoothing for
//! vectors of arbitrary dimension. Implementation method relies on `rulinalg`
//! library for linear algebra computations. Most inputs and outputs rely
//! therefore on (derived) constructs from
//! [rulinalg](https://athemathmo.github.io/ruli... | (kalman_filter: &KalmanFilter,
init: &KalmanState,
measure: &Vector<f64>)
-> (KalmanState, KalmanState) {
let pred = predict_step(kalman_filter, init);
let upd = update_step(kalman_filter, &pred, measure);
(KalmanState { x: upd.x, p: upd.p }, Kalman... | filter_step | identifier_name |
lib.rs | //! This crate implements a standard linear Kalman filter and smoothing for
//! vectors of arbitrary dimension. Implementation method relies on `rulinalg`
//! library for linear algebra computations. Most inputs and outputs rely
//! therefore on (derived) constructs from
//! [rulinalg](https://athemathmo.github.io/ruli... | {
let j: Matrix<f64> = &filtered.p * &kalman_filter.f.transpose() *
&predicted.p.clone().inverse()
.expect("Predicted state covariance matrix could not be inverted.");
let x: Vector<f64> = &filtered.x + &j * (&init.x - &predicted.x);
let p: Matrix<f64> = &filtered.p + &j * (&init.p - &predi... | identifier_body | |
lib.rs | //! This crate implements a standard linear Kalman filter and smoothing for
//! vectors of arbitrary dimension. Implementation method relies on `rulinalg`
//! library for linear algebra computations. Most inputs and outputs rely
//! therefore on (derived) constructs from
//! [rulinalg](https://athemathmo.github.io/ruli... | ///
/// fn main() {
///
/// let kalman_filter = KalmanFilter {
/// // All matrices are identity matrices
/// q: Matrix::from_diag(&vec![1.0, 1.0]),
/// r: Matrix::from_diag(&vec![1.0, 1.0]),
/// h: Matrix::from_diag(&vec![1.0, 1.0]),
/// f: Matrix::from_diag(&ve... | /// use linearkalman::KalmanFilter; | random_line_split |
explicit_null.rs | use juniper::{
graphql_object, graphql_value, graphql_vars, EmptyMutation, EmptySubscription,
GraphQLInputObject, Nullable, Variables,
};
pub struct Context;
impl juniper::Context for Context {}
pub struct Query;
#[derive(GraphQLInputObject)]
struct ObjectInput {
field: Nullable<i32>,
}
#[graphql_objec... | "noArgIsExplicitNull": false,
"literalOneFieldIsExplicitNull": false,
"literalNullFieldIsExplicitNull": true,
"noFieldIsExplicitNull": false,
"emptyVariableObjectFieldIsExplicitNull": false,
"literalNullVariableObjectFieldIs... | "literalOneIsExplicitNull": false,
"literalNullIsExplicitNull": true, | random_line_split |
explicit_null.rs | use juniper::{
graphql_object, graphql_value, graphql_vars, EmptyMutation, EmptySubscription,
GraphQLInputObject, Nullable, Variables,
};
pub struct Context;
impl juniper::Context for Context {}
pub struct Query;
#[derive(GraphQLInputObject)]
struct ObjectInput {
field: Nullable<i32>,
}
#[graphql_objec... | () {
let query = r#"
query Foo($emptyObj: ObjectInput!, $literalNullObj: ObjectInput!) {
literalOneIsExplicitNull: isExplicitNull(arg: 1)
literalNullIsExplicitNull: isExplicitNull(arg: null)
noArgIsExplicitNull: isExplicitNull
literalOneFieldIsExplicitNull: ob... | explicit_null | identifier_name |
resource-destruct.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 my_total = &Cell::new(10);
{ let pt = shrinky_pointer(my_total); assert!((pt.look_at() == 10)); }
println!("my_total = {}", my_total.get());
assert_eq!(my_total.get(), 9);
}
| main | identifier_name |
resource-destruct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn shrinky_pointer(i: &Cell<isize>) -> shrinky_pointer {
shrinky_pointer {
i: i
}
}
pub fn main() {
let my_total = &Cell::new(10);
{ let pt = shrinky_pointer(my_total); assert!((pt.look_at() == 10)); }
println!("my_total = {}", my_total.get());
assert_eq!(my_total.get(), 9);
}
| { return self.i.get(); } | identifier_body |
resource-destruct.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... | random_line_split | |
main.rs | extern crate graphics;
extern crate freetype as ft;
extern crate sdl2_window;
extern crate opengl_graphics;
extern crate piston;
extern crate find_folder;
use sdl2_window::Sdl2Window;
use opengl_graphics::{ GlGraphics, Texture, OpenGL };
use graphics::math::Matrix2d;
use piston::window::WindowSettings;
use piston::eve... |
}
}
| {
use graphics::*;
gl.draw(args.viewport(), |c, gl| {
let transform = c.transform.trans(0.0, 100.0);
clear(color::WHITE, gl);
render_text(&mut face, gl, transform, "Hello Piston!");
});
} | conditional_block |
main.rs | extern crate graphics;
extern crate freetype as ft;
extern crate sdl2_window;
extern crate opengl_graphics;
extern crate piston;
extern crate find_folder;
use sdl2_window::Sdl2Window;
use opengl_graphics::{ GlGraphics, Texture, OpenGL };
use graphics::math::Matrix2d;
use piston::window::WindowSettings;
use piston::eve... |
gl.draw(args.viewport(), |c, gl| {
let transform = c.transform.trans(0.0, 100.0);
clear(color::WHITE, gl);
render_text(&mut face, gl, transform, "Hello Piston!");
});
}
}
}
| {
let opengl = OpenGL::V3_2;
let window: Sdl2Window =
WindowSettings::new("piston-example-freetype", [300, 300])
.exit_on_esc(true)
.opengl(opengl)
.into();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let freetype = ft... | identifier_body |
main.rs | extern crate graphics;
extern crate freetype as ft;
extern crate sdl2_window;
extern crate opengl_graphics;
extern crate piston;
extern crate find_folder;
use sdl2_window::Sdl2Window;
use opengl_graphics::{ GlGraphics, Texture, OpenGL };
use graphics::math::Matrix2d;
use piston::window::WindowSettings;
use piston::eve... | (face: &mut ft::Face, gl: &mut GlGraphics, t: Matrix2d, text: &str) {
use graphics::*;
let mut x = 10;
let mut y = 0;
for ch in text.chars() {
face.load_char(ch as usize, ft::face::RENDER).unwrap();
let g = face.glyph();
let bitmap = g.bitmap();
let texture = Texture::f... | render_text | identifier_name |
main.rs | extern crate graphics;
extern crate freetype as ft;
extern crate sdl2_window;
extern crate opengl_graphics;
extern crate piston;
extern crate find_folder;
use sdl2_window::Sdl2Window;
use opengl_graphics::{ GlGraphics, Texture, OpenGL };
use graphics::math::Matrix2d;
use piston::window::WindowSettings;
use piston::eve... | }
}
} | random_line_split | |
navigatorinfo.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::str::DOMString;
use util::opts;
pub fn Product() -> DOMString {
DOMString::from("Gecko")
}... | () -> bool {
false
}
pub fn AppName() -> DOMString {
DOMString::from("Netscape") // Like Gecko/Webkit
}
pub fn AppCodeName() -> DOMString {
DOMString::from("Mozilla")
}
#[cfg(target_os = "windows")]
pub fn Platform() -> DOMString {
DOMString::from("Win32")
}
#[cfg(any(target_os = "android", target_o... | TaintEnabled | identifier_name |
navigatorinfo.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::str::DOMString;
use util::opts;
pub fn Product() -> DOMString {
DOMString::from("Gecko")
}... |
pub fn UserAgent() -> DOMString {
DOMString::from(&*opts::get().user_agent)
}
pub fn AppVersion() -> DOMString {
DOMString::from("4.0")
}
pub fn Language() -> DOMString {
DOMString::from("en-US")
}
| {
DOMString::from("Mac")
} | identifier_body |
navigatorinfo.rs | use util::opts;
pub fn Product() -> DOMString {
DOMString::from("Gecko")
}
pub fn TaintEnabled() -> bool {
false
}
pub fn AppName() -> DOMString {
DOMString::from("Netscape") // Like Gecko/Webkit
}
pub fn AppCodeName() -> DOMString {
DOMString::from("Mozilla")
}
#[cfg(target_os = "windows")]
pub fn... | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::str::DOMString; | random_line_split | |
format.rs | use super::{
Attributes, Data, Event, EventFormatDeserializerV03, EventFormatDeserializerV10,
EventFormatSerializerV03, EventFormatSerializerV10,
};
use crate::event::{AttributesReader, ExtensionValue};
use serde::de::{Error, IntoDeserializer};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use ... |
pub fn parse_data_string<E: serde::de::Error>(v: Value) -> Result<String, E> {
parse_field!(v, String, E)
}
pub fn parse_data_base64<E: serde::de::Error>(v: Value) -> Result<Vec<u8>, E> {
parse_field!(v, String, E).and_then(|s| {
base64::decode(&s).map_err(|e| E::custom(format_args!("decode error `{}... | {
Value::deserialize(v.into_deserializer()).map_err(E::custom)
} | identifier_body |
format.rs | use super::{
Attributes, Data, Event, EventFormatDeserializerV03, EventFormatDeserializerV10,
EventFormatSerializerV03, EventFormatSerializerV10,
};
use crate::event::{AttributesReader, ExtensionValue};
use serde::de::{Error, IntoDeserializer};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use ... | <E: serde::de::Error>(v: Value) -> Result<Value, E> {
let data = parse_data_base64(v)?;
serde_json::from_slice(&data).map_err(E::custom)
}
pub(crate) trait EventFormatDeserializer {
fn deserialize_attributes<E: serde::de::Error>(
map: &mut Map<String, Value>,
) -> Result<Attributes, E>;
fn... | parse_data_base64_json | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.