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 |
|---|---|---|---|---|
ascii.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! 7-bit ASCII encoding.
use libtww::std::mem;
use libtww::std::convert::Into;
use types::*;
/**
* ASCII, also known as ISO/IEC 646:US.
*
* It is both a basis and a lowest common denomina... |
fn raw_encoder(&self) -> Box<RawEncoder> {
ASCIIEncoder::new()
}
fn raw_decoder(&self) -> Box<RawDecoder> {
ASCIIDecoder::new()
}
}
/// An encoder for ASCII.
#[derive(Clone, Copy)]
pub struct ASCIIEncoder;
impl ASCIIEncoder {
pub fn new() -> Box<RawEncoder> {
Box::new(ASCI... | {
"ascii"
} | identifier_body |
ascii.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! 7-bit ASCII encoding.
use libtww::std::mem;
use libtww::std::convert::Into;
use types::*;
/**
* ASCII, also known as ISO/IEC 646:US.
*
* It is both a basis and a lowest common denomina... | (&self) -> Box<RawEncoder> {
ASCIIEncoder::new()
}
fn raw_decoder(&self) -> Box<RawDecoder> {
ASCIIDecoder::new()
}
}
/// An encoder for ASCII.
#[derive(Clone, Copy)]
pub struct ASCIIEncoder;
impl ASCIIEncoder {
pub fn new() -> Box<RawEncoder> {
Box::new(ASCIIEncoder)
}
}
... | raw_encoder | identifier_name |
mod.rs | //! Trait Resolution. See the [rustc-dev-guide] for more information on how this works.
//!
//! [rustc-dev-guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
mod engine;
pub mod error_reporting;
mod project;
mod structural_impls;
pub mod util;
use rustc_hir as hir;
use rustc_middle::ty::error::{Expe... | (
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
predicate: O,
) -> Obligation<'tcx, O> {
Obligation { cause, param_env, recursion_depth: 0, predicate }
}
pub fn with_depth(
cause: ObligationCause<'tcx>,
recursion_depth: usize,
param_env... | new | identifier_name |
mod.rs | //! Trait Resolution. See the [rustc-dev-guide] for more information on how this works.
//!
//! [rustc-dev-guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
mod engine;
pub mod error_reporting;
mod project;
mod structural_impls;
pub mod util;
use rustc_hir as hir;
use rustc_middle::ty::error::{Expe... | /// something else, track the total depth to ensure termination.
/// If this goes over a certain threshold, we abort compilation --
/// in such cases, we can not say whether or not the predicate
/// holds for certain. Stupid halting problem; such a drag.
pub recursion_depth: usize,
}
pub type Predi... | /// If we started proving this as a result of trying to prove | random_line_split |
mod.rs | //! Trait Resolution. See the [rustc-dev-guide] for more information on how this works.
//!
//! [rustc-dev-guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
mod engine;
pub mod error_reporting;
mod project;
mod structural_impls;
pub mod util;
use rustc_hir as hir;
use rustc_middle::ty::error::{Expe... |
pub fn with<P>(&self, value: P) -> Obligation<'tcx, P> {
Obligation {
cause: self.cause.clone(),
param_env: self.param_env,
recursion_depth: self.recursion_depth,
predicate: value,
}
}
}
impl<'tcx> FulfillmentError<'tcx> {
pub fn new(
... | {
Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
} | identifier_body |
errors.rs | use primitives::*;
error_chain!{
errors {
/// Error when trying trying to call `Expr::get()`, but the index is invalid.
InvalidExprAccess(index: usize) {
description("Trying to access an invalid expression index.")
display("Trying to access the invalid ex... | display("Invalid arguments: {:?}. '{}' message: {}", args, op, msg)
}
Downcast(from: FundamentalType, to: FundamentalType) {
description("Down casting tensor.")
display("Down casting tensor from {} to {}.", from, to)
}
}
// ... | description("Invalid arguments.") | random_line_split |
super_simplex.rs | //! An example of using Super Simplex noise
extern crate noise;
use noise::{utils::*, Seedable, SuperSimplex};
fn main() {
let mut lookup_2d: [([i8; 2], [f64; 2]); 8 * 4] = [([0; 2], [0.0; 2]); 8 * 4];
let mut lookup_3d: [[i8; 3]; 16 * 4] = [[0; 3]; 16 * 4];
let skew_constant = -0.211324865405187;
f... |
if i & 4 == 0 {
i2 = 0;
j2 = -1;
} else {
i2 = 0;
j2 = 1;
}
} else {
if i & 2!= 0 {
i1 = 2;
j1 = 1;
} else {
i1 = 0;
j1 = 1... | {
i1 = 1;
j1 = 0;
} | conditional_block |
super_simplex.rs | //! An example of using Super Simplex noise
extern crate noise;
use noise::{utils::*, Seedable, SuperSimplex};
fn main() | j2 = 1;
}
} else {
if i & 2!= 0 {
i1 = 2;
j1 = 1;
} else {
i1 = 0;
j1 = 1;
}
if i & 4!= 0 {
i2 = 1;
j2 = 2;
} else {
... | {
let mut lookup_2d: [([i8; 2], [f64; 2]); 8 * 4] = [([0; 2], [0.0; 2]); 8 * 4];
let mut lookup_3d: [[i8; 3]; 16 * 4] = [[0; 3]; 16 * 4];
let skew_constant = -0.211324865405187;
for i in 0..8 {
let (i1, j1, i2, j2);
if i & 1 == 0 {
if i & 2 == 0 {
i1 = -1;
... | identifier_body |
super_simplex.rs | //! An example of using Super Simplex noise
extern crate noise;
use noise::{utils::*, Seedable, SuperSimplex};
fn | () {
let mut lookup_2d: [([i8; 2], [f64; 2]); 8 * 4] = [([0; 2], [0.0; 2]); 8 * 4];
let mut lookup_3d: [[i8; 3]; 16 * 4] = [[0; 3]; 16 * 4];
let skew_constant = -0.211324865405187;
for i in 0..8 {
let (i1, j1, i2, j2);
if i & 1 == 0 {
if i & 2 == 0 {
i1 = -1;... | main | identifier_name |
super_simplex.rs | //! An example of using Super Simplex noise
extern crate noise;
use noise::{utils::*, Seedable, SuperSimplex};
fn main() {
let mut lookup_2d: [([i8; 2], [f64; 2]); 8 * 4] = [([0; 2], [0.0; 2]); 8 * 4];
let mut lookup_3d: [[i8; 3]; 16 * 4] = [[0; 3]; 16 * 4];
let skew_constant = -0.211324865405187;
f... | if i & 4!= 0 {
i2 = 1;
j2 = 2;
} else {
i2 = 1;
j2 = 0;
}
}
lookup_2d[i * 4] = ([0, 0], [0.0, 0.0]);
let skew_factor = -1.0 - 2.0 * skew_constant;
lookup_2d[i * 4 + 1] = ([1, 1], [skew_fac... | } else {
i1 = 0;
j1 = 1;
} | random_line_split |
lib.rs | #![cfg_attr(test, feature(plugin))]
#![warn(
clippy::empty_enum,
clippy::filter_map,
clippy::if_not_else,
clippy::invalid_upcast_comparisons,
clippy::items_after_statements,
clippy::mut_mut,
clippy::nonminimal_bool,
clippy::option_map_unwrap_or,
clippy::option_map_unwrap_or_else,
... | let finished_levels: usize = stats.iter().map(|x| x.solved_levels).sum();
let collections_started = stats.iter().filter(|x| x.started() &&!x.solved()).count();
println!(
"{}",
Yellow.bold().paint(" Collections Levels")
);
println!("------------------------------------"... | let finished_collections = stats.iter().filter(|x| x.solved()).count(); | random_line_split |
lib.rs | #![cfg_attr(test, feature(plugin))]
#![warn(
clippy::empty_enum,
clippy::filter_map,
clippy::if_not_else,
clippy::invalid_upcast_comparisons,
clippy::items_after_statements,
clippy::mut_mut,
clippy::nonminimal_bool,
clippy::option_map_unwrap_or,
clippy::option_map_unwrap_or_else,
... | );
} else {
let solved = if collection.started() {
Blue.paint("solved")
} else {
White.paint("solved")
};
println!(
" {}{}{:>10} {}",
padded_short_name,
White.bold().paint(... | {
let stats = gather_stats();
println!(
" {} {}",
Yellow.bold().paint("File name"),
Yellow.bold().paint("Collection name")
);
println!("--------------------------------------------------------------------------------");
for collection in stats {
let pa... | identifier_body |
lib.rs | #![cfg_attr(test, feature(plugin))]
#![warn(
clippy::empty_enum,
clippy::filter_map,
clippy::if_not_else,
clippy::invalid_upcast_comparisons,
clippy::items_after_statements,
clippy::mut_mut,
clippy::nonminimal_bool,
clippy::option_map_unwrap_or,
clippy::option_map_unwrap_or_else,
... | else {
White.paint("solved")
};
println!(
" {}{}{:>10} {}",
padded_short_name,
White.bold().paint(padded_full_name),
format!("{}/{}", collection.solved_levels, collection.total_levels),
solved
... | {
Blue.paint("solved")
} | conditional_block |
lib.rs | #![cfg_attr(test, feature(plugin))]
#![warn(
clippy::empty_enum,
clippy::filter_map,
clippy::if_not_else,
clippy::invalid_upcast_comparisons,
clippy::items_after_statements,
clippy::mut_mut,
clippy::nonminimal_bool,
clippy::option_map_unwrap_or,
clippy::option_map_unwrap_or_else,
... | () {
let stats = gather_stats();
let num_collections = stats.len();
let num_levels: usize = stats.iter().map(|x| x.total_levels).sum();
let finished_collections = stats.iter().filter(|x| x.solved()).count();
let finished_levels: usize = stats.iter().map(|x| x.solved_levels).sum();
let collect... | print_stats | identifier_name |
HowMuch.rs | fn how_much(mut m: i32, mut n: i32) -> Vec<(String, String, String)> {
if m > n {
std::mem::swap(&mut m, &mut n);
}
let mut result: Vec<(String, String, String)> = Vec::new();
let mut c: f32;
let mut b: f32;
for i in m..n+1 {
c = (i as f32-1f32)/9f32;
b = (i as f32-2f32... |
if c.fract() == 0f32 && b.fract() == 0f32 {
let r_tuple = (format!("M: {}", i),
format!("B: {}", b as i32),
format!("C: {}", c as i32));
result.push(r_tuple);
}
}
return result;
}
fn testing(m: i32, n: i32, exp: Ve... | {
continue;
} | conditional_block |
HowMuch.rs | fn how_much(mut m: i32, mut n: i32) -> Vec<(String, String, String)> {
if m > n {
std::mem::swap(&mut m, &mut n);
}
let mut result: Vec<(String, String, String)> = Vec::new();
let mut c: f32;
let mut b: f32;
for i in m..n+1 {
c = (i as f32-1f32)/9f32;
b = (i as f32-2f32... |
fn tests() {
testing(1, 100, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11")]);
testing(1000, 1100, vec![("M: 1045", "B: 149", "C: 116")]);
testing(10000, 9950, vec![("M: 9991", "B: 1427", "C: 1110")]);
testing(0, 200, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11"), ("M: 163"... | {
let ans: String = format!("{:?}", how_much(m, n));
let sol: String = format!("{:?}", exp);
assert_eq!(ans, sol)
} | identifier_body |
HowMuch.rs | fn | (mut m: i32, mut n: i32) -> Vec<(String, String, String)> {
if m > n {
std::mem::swap(&mut m, &mut n);
}
let mut result: Vec<(String, String, String)> = Vec::new();
let mut c: f32;
let mut b: f32;
for i in m..n+1 {
c = (i as f32-1f32)/9f32;
b = (i as f32-2f32)/7f32;
... | how_much | identifier_name |
HowMuch.rs | fn how_much(mut m: i32, mut n: i32) -> Vec<(String, String, String)> {
if m > n {
std::mem::swap(&mut m, &mut n);
}
let mut result: Vec<(String, String, String)> = Vec::new();
let mut c: f32;
let mut b: f32;
for i in m..n+1 {
c = (i as f32-1f32)/9f32; | if c.fract() == 0f32 && b.fract() == 0f32 {
let r_tuple = (format!("M: {}", i),
format!("B: {}", b as i32),
format!("C: {}", c as i32));
result.push(r_tuple);
}
}
return result;
}
fn testing(m: i32, n: i32, exp: Vec... | b = (i as f32-2f32)/7f32;
if c < 0f32 || b < 0f32 {
continue;
} | random_line_split |
trivial-bounds-lint.rs | #![feature(trivial_bounds)]
#![allow(unused)]
#![deny(trivial_bounds)]
struct A where i32: Copy; //~ ERROR
trait X<T: Copy> {}
trait Y<T>: Copy {}
trait Z {
type S: Copy;
}
// Check only the bound the user writes trigger the lint
fn trivial_elaboration<T>() where T: X<i32> + Z<S = i32>, i32: Y<T> {} // OK
fn ... | // OK
fn global_outlives() where'static:'static {} //~ ERROR
// Check that each bound is checked individually
fn mixed_bounds<T: Copy>() where i32: X<T> + Copy {} //~ ERROR
fn main() {}
| {} | identifier_body |
trivial-bounds-lint.rs | #![feature(trivial_bounds)]
#![allow(unused)]
#![deny(trivial_bounds)]
struct A where i32: Copy; //~ ERROR
trait X<T: Copy> {}
trait Y<T>: Copy {}
trait Z {
type S: Copy; |
fn global_param() where i32: X<()> {} //~ ERROR
// Should only error on the trait bound, not the implicit
// projection bound <i32 as Z>::S == i32.
fn global_projection() where i32: Z<S = i32> {} //~ ERROR
impl A {
fn new() -> A { A }
}
// Lifetime bounds should be linted as well
fn global_lifetimes() where i32... | }
// Check only the bound the user writes trigger the lint
fn trivial_elaboration<T>() where T: X<i32> + Z<S = i32>, i32: Y<T> {} // OK | random_line_split |
trivial-bounds-lint.rs | #![feature(trivial_bounds)]
#![allow(unused)]
#![deny(trivial_bounds)]
struct | where i32: Copy; //~ ERROR
trait X<T: Copy> {}
trait Y<T>: Copy {}
trait Z {
type S: Copy;
}
// Check only the bound the user writes trigger the lint
fn trivial_elaboration<T>() where T: X<i32> + Z<S = i32>, i32: Y<T> {} // OK
fn global_param() where i32: X<()> {} //~ ERROR
// Should only error on the trait ... | A | identifier_name |
debug.rs | /* This Source Code Form is subject to the terms of the Mozilla Public | use std::cast::transmute;
use std::mem::size_of;
fn hexdump_slice(buf: &[u8]) {
let stderr = io::stderr();
stderr.write_str(" ");
for (i, &v) in buf.iter().enumerate() {
stderr.write_str(fmt!("%02X ", v as uint));
match i % 16 {
15 => stderr.write_str("\n "),
... | * 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 std::io;
use std::vec::raw::buf_as_slice; | random_line_split |
debug.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 std::io;
use std::vec::raw::buf_as_slice;
use std::cast::transmute;
use std::mem::size_of;
fn hexdump_slice(b... |
pub fn hexdump<T>(obj: &T) {
unsafe {
let buf: *u8 = transmute(obj);
debug!("dumping at %p", buf);
buf_as_slice(buf, size_of::<T>(), hexdump_slice);
}
}
| {
let stderr = io::stderr();
stderr.write_str(" ");
for (i, &v) in buf.iter().enumerate() {
stderr.write_str(fmt!("%02X ", v as uint));
match i % 16 {
15 => stderr.write_str("\n "),
7 => stderr.write_str(" "),
_ => ()
}
stderr.flu... | identifier_body |
debug.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 std::io;
use std::vec::raw::buf_as_slice;
use std::cast::transmute;
use std::mem::size_of;
fn | (buf: &[u8]) {
let stderr = io::stderr();
stderr.write_str(" ");
for (i, &v) in buf.iter().enumerate() {
stderr.write_str(fmt!("%02X ", v as uint));
match i % 16 {
15 => stderr.write_str("\n "),
7 => stderr.write_str(" "),
_ => ()
}
... | hexdump_slice | identifier_name |
numbers.rs | //! Functions operating on numbers.
use rand::{Rng, SeedableRng, StdRng};
use std::sync::Mutex;
use remacs_macros::lisp_fn;
use remacs_sys::{EmacsInt, INTMASK};
use lisp::LispObject;
use lisp::defsubr;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT i... | pub fn integer_or_marker_p(object: LispObject) -> bool {
object.is_marker() || object.is_integer()
}
/// Return t if OBJECT is a non-negative integer.
#[lisp_fn]
pub fn natnump(object: LispObject) -> bool {
object.is_natnum()
}
/// Return t if OBJECT is a number (floating point or integer).
#[lisp_fn]
pub fn ... |
/// Return t if OBJECT is an integer or a marker (editor pointer).
#[lisp_fn] | random_line_split |
numbers.rs | //! Functions operating on numbers.
use rand::{Rng, SeedableRng, StdRng};
use std::sync::Mutex;
use remacs_macros::lisp_fn;
use remacs_sys::{EmacsInt, INTMASK};
use lisp::LispObject;
use lisp::defsubr;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT i... |
/// Return t if OBJECT is a non-negative integer.
#[lisp_fn]
pub fn natnump(object: LispObject) -> bool {
object.is_natnum()
}
/// Return t if OBJECT is a number (floating point or integer).
#[lisp_fn]
pub fn numberp(object: LispObject) -> bool {
object.is_number()
}
/// Return t if OBJECT is a number or a ... | {
object.is_marker() || object.is_integer()
} | identifier_body |
numbers.rs | //! Functions operating on numbers.
use rand::{Rng, SeedableRng, StdRng};
use std::sync::Mutex;
use remacs_macros::lisp_fn;
use remacs_sys::{EmacsInt, INTMASK};
use lisp::LispObject;
use lisp::defsubr;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT i... |
if let Some(limit) = limit.as_fixnum() {
// Return the remainder, except reject the rare case where
// get_random returns a number so close to INTMASK that the
// remainder isn't random.
loop {
let val: EmacsInt = rng.gen();
let remainder = val.abs() % limit... | {
let values: Vec<usize> = s.as_slice().iter().map(|&x| x as usize).collect();
rng.reseed(&values);
} | conditional_block |
numbers.rs | //! Functions operating on numbers.
use rand::{Rng, SeedableRng, StdRng};
use std::sync::Mutex;
use remacs_macros::lisp_fn;
use remacs_sys::{EmacsInt, INTMASK};
use lisp::LispObject;
use lisp::defsubr;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT i... | (object: LispObject) -> bool {
object.is_number() || object.is_marker()
}
/// Return a pseudo-random number.
/// All integers representable in Lisp, i.e. between `most-negative-fixnum'
/// and `most-positive-fixnum', inclusive, are equally likely.
///
/// With positive integer LIMIT, return random number in interv... | number_or_marker_p | identifier_name |
inherited_table.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedTable", inherited=True,... |
}
}
match (first, second) {
(None, None) => Err(()),
(Some(length), None) => {
Ok(SpecifiedValue {
horizontal: length.clone(),
vertical: length,
})
}
(Some(horizontal), So... | {
second = Some(len);
} | conditional_block |
inherited_table.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedTable", inherited=True,... | fn from_computed_value(computed: &computed_value::T) -> Self {
SpecifiedValue {
horizontal: ToComputedValue::from_computed_value(&computed.horizontal),
vertical: ToComputedValue::from_computed_value(&computed.vertical),
}
}
}
pub fn parse(... | #[inline] | random_line_split |
inherited_table.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedTable", inherited=True,... | <W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.horizontal.to_css(dest));
try!(dest.write_str(" "));
self.vertical.to_css(dest)
}
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write... | to_css | identifier_name |
os.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 ... |
}
}
impl Rng for OSRng {
fn next_u32(&mut self) -> u32 {
let mut v = [0u8,.. 4];
self.fill_bytes(v);
unsafe { cast::transmute(v) }
}
fn next_u64(&mut self) -> u64 {
let mut v = [0u8,.. 8];
self.fill_bytes(v);
... | {
Ok(OSRng { hcryptprov: hcp })
} | conditional_block |
os.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 ... |
}
}
#[cfg(test)]
mod test {
use super::OSRng;
use Rng;
use std::task;
#[test]
fn test_os_rng() {
let mut r = OSRng::new().unwrap();
r.next_u32();
r.next_u64();
let mut v = [0u8,.. 1000];
r.fill_bytes(v);
}
#[test]
fn test_os_rng_tasks() {... | {
let ret = unsafe {
CryptReleaseContext(self.hcryptprov, 0)
};
if ret == 0 {
fail!("couldn't release context: {}", os::last_os_error());
}
} | identifier_body |
os.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 ... | txs.push(tx);
task::spawn(proc() {
// wait until all the tasks are ready to go.
rx.recv();
// deschedule to attempt to interleave things as much
// as possible (XXX: is this a good test?)
let mut r = OSRng::new().un... | let mut txs = vec!();
for _ in range(0, 20) {
let (tx, rx) = channel(); | random_line_split |
os.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 ... | (&mut self) -> u64 {
let mut v = [0u8,.. 8];
self.fill_bytes(v);
unsafe { cast::transmute(v) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
let ret = unsafe {
CryptGenRandom(self.hcryptprov, v.len() as DWORD,
v.... | next_u64 | identifier_name |
websocket.rs | use std::ptr;
use std::thread;
use websocket::client::request::Url;
use websocket::header::{Headers, WebSocketProtocol};
use websocket::ws::util::url::parse_url;
#[derive(JSTraceable, PartialEq, Copy, Clone, Debug, HeapSizeOf)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed ... | name | identifier_name | |
websocket.rs | traits::unwrap_websocket_protocol;
use script_runtime::{CommonScriptMsg, ScriptChan};
use script_runtime::ScriptThreadEventCategory::WebSocketEvent;
use script_thread::Runnable;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ptr;
use std::thread;
use websocket::client::request::Url;
u... |
// Perform _the WebSocket connection is closed_ steps.
// https://html.spec.whatwg.org/multipage/#closeWebSocket
// Step 1.
ws.ready_state.set(WebSocketRequestState::Closed);
// Step 2.
if self.failed {
ws.upcast().fire_simple_event("error");
}
... | {
// Do nothing if already closed.
return;
} | conditional_block |
websocket.rs | _traits::unwrap_websocket_protocol;
use script_runtime::{CommonScriptMsg, ScriptChan};
use script_runtime::ScriptThreadEventCategory::WebSocketEvent;
use script_thread::Runnable;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ptr;
use std::thread;
use websocket::client::request::Url;
... | // Perform _the WebSocket connection is closed_ steps.
// https://html.spec.whatwg.org/multipage/#closeWebSocket
// Step 1.
ws.ready_state.set(WebSocketRequestState::Closed);
// Step 2.
if self.failed {
ws.upcast().fire_simple_event("error");
}
... | random_line_split | |
std-panic-locations.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// revisions: default mir-opt
//[mir-opt] compile-flags: -Zmir-opt-level=4
#![allow(unconditional_panic)]
//! Test that panic locations for `#[track_caller]` functions in std have the correct
//! location reported.
use std::cell::RefCell;
use std... |
}));
fn assert_panicked(f: impl FnOnce() + UnwindSafe) {
std::panic::catch_unwind(f).unwrap_err();
}
let nope: Option<()> = None;
assert_panicked(|| nope.unwrap());
assert_panicked(|| nope.expect(""));
let oops: Result<(), ()> = Err(());
assert_panicked(|| oops.unwrap());
... | {
eprintln!("expected a location in the test file, found {:?}", actual);
panic!();
} | conditional_block |
std-panic-locations.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// revisions: default mir-opt
//[mir-opt] compile-flags: -Zmir-opt-level=4
#![allow(unconditional_panic)]
//! Test that panic locations for `#[track_caller]` functions in std have the correct
//! location reported.
use std::cell::RefCell;
use std... |
let nope: Option<()> = None;
assert_panicked(|| nope.unwrap());
assert_panicked(|| nope.expect(""));
let oops: Result<(), ()> = Err(());
assert_panicked(|| oops.unwrap());
assert_panicked(|| oops.expect(""));
let fine: Result<(), ()> = Ok(());
assert_panicked(|| fine.unwrap_err());
... | {
std::panic::catch_unwind(f).unwrap_err();
} | identifier_body |
std-panic-locations.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// revisions: default mir-opt
//[mir-opt] compile-flags: -Zmir-opt-level=4
#![allow(unconditional_panic)]
//! Test that panic locations for `#[track_caller]` functions in std have the correct
//! location reported.
use std::cell::RefCell;
use std... | (f: impl FnOnce() + UnwindSafe) {
std::panic::catch_unwind(f).unwrap_err();
}
let nope: Option<()> = None;
assert_panicked(|| nope.unwrap());
assert_panicked(|| nope.expect(""));
let oops: Result<(), ()> = Err(());
assert_panicked(|| oops.unwrap());
assert_panicked(|| oops.expect("... | assert_panicked | identifier_name |
std-panic-locations.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// revisions: default mir-opt
//[mir-opt] compile-flags: -Zmir-opt-level=4
#![allow(unconditional_panic)]
//! Test that panic locations for `#[track_caller]` functions in std have the correct
//! location reported.
use std::cell::RefCell;
use std... | std::panic::catch_unwind(f).unwrap_err();
}
let nope: Option<()> = None;
assert_panicked(|| nope.unwrap());
assert_panicked(|| nope.expect(""));
let oops: Result<(), ()> = Err(());
assert_panicked(|| oops.unwrap());
assert_panicked(|| oops.expect(""));
let fine: Result<(), ()>... | fn assert_panicked(f: impl FnOnce() + UnwindSafe) { | random_line_split |
providers.rs | // Copyright 2020 The Kythe Authors. All rights reserved.
//
// 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 appli... |
}
impl FileProvider for ProxyFileProvider {
/// Given a file path and digest, returns whether the proxy can find the
/// file.
fn exists(&mut self, path: &str, digest: &str) -> Result<bool, KytheError> {
// Submit the file request to the proxy
let request = proxyrequests::file(path.to_stri... | {
Self::new()
} | identifier_body |
providers.rs | // Copyright 2020 The Kythe Authors. All rights reserved.
//
// 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 appli... | (&mut self, path: &str, digest: &str) -> Result<bool, KytheError> {
// Submit the file request to the proxy
let request = proxyrequests::file(path.to_string(), digest.to_string())?;
println!("{}", request);
io::stdout().flush().map_err(|err| {
KytheError::IndexerError(format!... | exists | identifier_name |
providers.rs | // Copyright 2020 The Kythe Authors. All rights reserved.
//
// 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 appli... | // Retrieve base64 content and convert to a Vec<u8>
let content_option = args["content"].as_str();
if content_option.is_none() {
return Ok(vec![]);
}
let content_base64: &str = content_option.unwrap();
let content: Vec<u8> = base64:... | } else {
let args: Value = response["args"].clone(); | random_line_split |
providers.rs | // Copyright 2020 The Kythe Authors. All rights reserved.
//
// 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 appli... |
}
}
| {
let args: Value = response["args"].clone();
// Retrieve base64 content and convert to a Vec<u8>
let content_option = args["content"].as_str();
if content_option.is_none() {
return Ok(vec![]);
}
let content_base64: &str = content_o... | conditional_block |
binary.rs | use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::io::{Read, Seek, SeekFrom};
use std::mem;
use std::str;
use std::time::{Duration, UNIX_EPOCH};
use fnv::FnvHasher;
use plist::Plist;
use result::{Result, Error};
#[inline]
fn be_u16(buf: &[u8]) -> u16 {
((buf[0] as u16) << 8 | (buf[1] as u... | <R: Read>(input: &mut R, size: u8, count: usize) -> Result<Vec<u64>> {
let len = size as usize * count;
let mut buf = Vec::with_capacity(len);
try!(input.take(len as u64).read_to_end(&mut buf));
Ok(buf.chunks(size as usize)
.map(|x| sized_int(x, size))
.collect())
}
#[inline]
fn read_size... | sized_ints | identifier_name |
binary.rs | use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::io::{Read, Seek, SeekFrom};
use std::mem;
use std::str;
use std::time::{Duration, UNIX_EPOCH};
use fnv::FnvHasher;
use plist::Plist;
use result::{Result, Error};
#[inline]
fn be_u16(buf: &[u8]) -> u16 {
((buf[0] as u16) << 8 | (buf[1] as u... | try!(input.read_exact(&mut len));
let size = try!(validate_size(1u8 << (len[0] & 0xF)));
try!(input.read_exact(&mut buf[0..size as usize]));
Ok((buf, size))
}
#[inline]
fn read_int<R: Read>(input: &mut R) -> Result<u64> {
let mut buf = [0; 1];
try!(input.read_exact(&mut buf));
if (buf[0] &... | let mut len = [0; 1];
let mut buf = [0; 8]; | random_line_split |
binary.rs | use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::io::{Read, Seek, SeekFrom};
use std::mem;
use std::str;
use std::time::{Duration, UNIX_EPOCH};
use fnv::FnvHasher;
use plist::Plist;
use result::{Result, Error};
#[inline]
fn be_u16(buf: &[u8]) -> u16 {
((buf[0] as u16) << 8 | (buf[1] as u... |
#[inline]
fn be_u64(buf: &[u8]) -> u64 {
((buf[0] as u64) << 56 | (buf[1] as u64) << 48 | (buf[2] as u64) << 40 |
(buf[3] as u64) << 32 | (buf[4] as u64) << 24 | (buf[5] as u64) << 16 |
(buf[6] as u64) << 8 | (buf[7] as u64))
}
#[allow(unsafe_code)]
#[inline]
fn be_f32(buf: &[u8]) -> f32 {
unsafe {... | {
((buf[0] as u32) << 24 | (buf[1] as u32) << 16 | (buf[2] as u32) << 8 | (buf[3] as u32))
} | identifier_body |
pubsub-async-io.rs | use async_lapin::*;
use lapin::{
message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable,
BasicProperties, Connection, ConnectionProperties, Result,
};
use tracing::info;
fn main() -> Result<()> | "hello",
QueueDeclareOptions::default(),
FieldTable::default(),
)
.await?;
info!(?queue, "Declared queue");
let consumer = channel_b
.basic_consume(
"hello",
"my_consumer",
... | {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
tracing_subscriber::fmt::init();
let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into());
async_io::block_on(async {
let conn =
Connection::connect(&... | identifier_body |
pubsub-async-io.rs | use async_lapin::*;
use lapin::{
message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable,
BasicProperties, Connection, ConnectionProperties, Result,
};
use tracing::info;
fn main() -> Result<()> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", ... |
});
let payload = b"Hello world!";
loop {
let confirm = channel_a
.basic_publish(
"",
"hello",
BasicPublishOptions::default(),
payload.to_vec(),
BasicProperties::defa... | {
delivery
.ack(BasicAckOptions::default())
.await
.expect("failed to ack");
} | conditional_block |
pubsub-async-io.rs | use async_lapin::*;
use lapin::{
message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable,
BasicProperties, Connection, ConnectionProperties, Result,
};
use tracing::info;
fn main() -> Result<()> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", ... |
let payload = b"Hello world!";
loop {
let confirm = channel_a
.basic_publish(
"",
"hello",
BasicPublishOptions::default(),
payload.to_vec(),
BasicProperties::default(),
... | }); | random_line_split |
pubsub-async-io.rs | use async_lapin::*;
use lapin::{
message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable,
BasicProperties, Connection, ConnectionProperties, Result,
};
use tracing::info;
fn | () -> Result<()> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
tracing_subscriber::fmt::init();
let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into());
async_io::block_on(async {
let conn =
Conn... | main | identifier_name |
closure.rs | . The allocation strategy for this
// closure depends on the closure type. For a sendfn, the closure
// (and the referenced type descriptors) will be allocated in the
// exchange heap. For a fn, the closure is allocated in the task heap
// and is reference counted. For a block, the closure is allocated on
// the st... | (&self, ccx: &CrateContext) -> String {
format!("{}({})", self.action, self.datum.to_string(ccx))
}
}
// Given a closure ty, emits a corresponding tuple ty
pub fn mk_closure_tys(tcx: &ty::ctxt,
bound_values: &[EnvValue])
-> ty::t {
// determine the types of the ... | to_string | identifier_name |
closure.rs | value>
}
impl EnvValue {
pub fn to_string(&self, ccx: &CrateContext) -> String {
format!("{}({})", self.action, self.datum.to_string(ccx))
}
}
// Given a closure ty, emits a corresponding tuple ty
pub fn mk_closure_tys(tcx: &ty::ctxt,
bound_values: &[EnvValue])
... | {
// Don't regenerate the wrapper, just reuse the original one.
return llfn;
} | conditional_block | |
closure.rs | . The allocation strategy for this
// closure depends on the closure type. For a sendfn, the closure
// (and the referenced type descriptors) will be allocated in the
// exchange heap. For a fn, the closure is allocated in the task heap
// and is reference counted. For a block, the closure is allocated on
// the st... |
fn fill_fn_pair(bcx: &Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) {
Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code]));
let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx()));
Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box]));
}
pub fn trans_expr_fn<'a>(
... | {
let _icx = push_ctxt("closure::load_environment");
if freevars.len() == 0 {
return bcx
}
let llenv = bcx.fcx.llenv.unwrap();
for (i, freevar) in freevars.iter().enumerate() {
let upvar_ptr = GEPi(bcx, llenv, [0, i]);
let def_id = freevar.def.def_id();
bcx.fcx.llup... | identifier_body |
closure.rs | use middle::trans::machine::llsize_of;
use middle::trans::type_of::*;
use middle::trans::type_::Type;
use middle::ty;
use util::ppaux::Repr;
use util::ppaux::ty_to_string;
use arena::TypedArena;
use syntax::ast;
use syntax::ast_util;
// ___Good to know (tm)__________________________________________________
//
// The ... | random_line_split | ||
writer.rs | use std::io::{Write, Result};
use std::path::Path;
use std::fs::File;
use std::iter;
use std::collections::HashMap;
use inflections::Inflect;
use types::{Section, Documentation, Type};
macro_rules! w {
($w:ident) => { writeln!($w) };
($w:ident, $indent:expr, $s:expr) => { writeln!($w, "{}{}", indent($indent)... | New(String, Type),
}
fn write_complex_type<W: Write>(w: &mut W, type_name: String, typ: Type, indent: usize) -> Result<Vec<Todo>> {
let mut todos = Vec::new();
match typ {
Type::Enum(variants) => {
w!(w, indent, "#[derive(Deserialize, Debug, PartialEq, Clone)]")?;
w!(w, inde... | enum Todo {
Existing(String), | random_line_split |
writer.rs | use std::io::{Write, Result};
use std::path::Path;
use std::fs::File;
use std::iter;
use std::collections::HashMap;
use inflections::Inflect;
use types::{Section, Documentation, Type};
macro_rules! w {
($w:ident) => { writeln!($w) };
($w:ident, $indent:expr, $s:expr) => { writeln!($w, "{}{}", indent($indent)... | <P: AsRef<Path>>(path: P, sections: Vec<Section>, mut types: HashMap<String, Type>) -> Result<()> {
let mut file = File::create(path).expect("Unknown path");
write_internal(&mut file, sections, &mut types, 0)
}
fn write_internal<W: Write>(w: &mut W, sections: Vec<Section>, types: &mut HashMap<String, Type>, i:... | write | identifier_name |
writer.rs | use std::io::{Write, Result};
use std::path::Path;
use std::fs::File;
use std::iter;
use std::collections::HashMap;
use inflections::Inflect;
use types::{Section, Documentation, Type};
macro_rules! w {
($w:ident) => { writeln!($w) };
($w:ident, $indent:expr, $s:expr) => { writeln!($w, "{}{}", indent($indent)... | }
}
fn indent(indent: usize) -> String {
iter::repeat(" ").take(indent).collect()
}
| {
match typ {
Type::Bool => Some("bool".to_string()),
Type::F64 => Some("f64".to_string()),
Type::I8 => Some("i8".to_string()),
Type::I16 => Some("i16".to_string()),
Type::I32 => Some("i32".to_string()),
Type::I64 => Some("i64".to_string()),
Type::U8 => Some("... | identifier_body |
encoding_support.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/. */
//! Parsing stylesheets from bytes (not `&str`).
extern crate encoding;
use context::QuirksMode;
use cssparser::... | let (string, _) = decode_stylesheet_bytes(
bytes, protocol_encoding_label, environment_encoding);
Self::update_from_str(existing,
&string,
url_data,
stylesheet_loader,
erro... | url_data: UrlExtraData,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: &ParseErrorReporter) { | random_line_split |
encoding_support.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/. */
//! Parsing stylesheets from bytes (not `&str`).
extern crate encoding;
use context::QuirksMode;
use cssparser::... | (encoding: &Self::Encoding) -> bool {
matches!(encoding.name(), "utf-16be" | "utf-16le")
}
fn from_label(ascii_label: &[u8]) -> Option<Self::Encoding> {
str::from_utf8(ascii_label).ok().and_then(encoding::label::encoding_from_whatwg_label)
}
}
fn decode_stylesheet_bytes(css: &[u8], protoco... | is_utf16_be_or_le | identifier_name |
noise_traits.rs | //! Noise sampling.
use crate::{P2, P3};
use noise::NoiseFn;
/// A trait for types which are sources of noise, samplable by type `P`.
pub trait NoiseSrc<P> {
/// Samples noise.
fn noise(&self, p: P) -> f32;
}
impl<N> NoiseSrc<P2> for N
where
N: NoiseFn<[f64; 2]>,
{
fn noise(&self, p: P2) -> f32 {
... | (&self, p: P3) -> f32 {
self.get([p.x as f64, p.y as f64, p.z as f64]) as f32
}
}
| noise | identifier_name |
noise_traits.rs | //! Noise sampling.
use crate::{P2, P3};
use noise::NoiseFn;
/// A trait for types which are sources of noise, samplable by type `P`. | fn noise(&self, p: P) -> f32;
}
impl<N> NoiseSrc<P2> for N
where
N: NoiseFn<[f64; 2]>,
{
fn noise(&self, p: P2) -> f32 {
self.get([p.x as f64, p.y as f64]) as f32
}
}
impl<N> NoiseSrc<P3> for N
where
N: NoiseFn<[f64; 3]>,
{
fn noise(&self, p: P3) -> f32 {
self.get([p.x as f64, ... | pub trait NoiseSrc<P> {
/// Samples noise. | random_line_split |
noise_traits.rs | //! Noise sampling.
use crate::{P2, P3};
use noise::NoiseFn;
/// A trait for types which are sources of noise, samplable by type `P`.
pub trait NoiseSrc<P> {
/// Samples noise.
fn noise(&self, p: P) -> f32;
}
impl<N> NoiseSrc<P2> for N
where
N: NoiseFn<[f64; 2]>,
{
fn noise(&self, p: P2) -> f32 |
}
impl<N> NoiseSrc<P3> for N
where
N: NoiseFn<[f64; 3]>,
{
fn noise(&self, p: P3) -> f32 {
self.get([p.x as f64, p.y as f64, p.z as f64]) as f32
}
}
| {
self.get([p.x as f64, p.y as f64]) as f32
} | identifier_body |
domrect.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMRectBinding;
use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRec... | left: Au, right: Au) -> DOMRect {
DOMRect {
top: top.to_nearest_px() as f32,
bottom: bottom.to_nearest_px() as f32,
left: left.to_nearest_px() as f32,
right: right.to_nearest_px() as f32,
reflector_: Reflector::new(),
}... | right: f32,
}
impl DOMRect {
fn new_inherited(top: Au, bottom: Au, | random_line_split |
domrect.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMRectBinding;
use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRec... | (self) -> Finite<f32> {
let result = (self.right - self.left).abs();
Finite::wrap(result)
}
fn Height(self) -> Finite<f32> {
let result = (self.bottom - self.top).abs();
Finite::wrap(result)
}
}
| Width | identifier_name |
domrect.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMRectBinding;
use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRec... |
fn Left(self) -> Finite<f32> {
Finite::wrap(self.left)
}
fn Right(self) -> Finite<f32> {
Finite::wrap(self.right)
}
fn Width(self) -> Finite<f32> {
let result = (self.right - self.left).abs();
Finite::wrap(result)
}
fn Height(self) -> Finite<f32> {
... | {
Finite::wrap(self.bottom)
} | identifier_body |
euler.rs | // Copyright 2016 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// 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 ... | A::Epsilon {
A::default_epsilon()
}
#[inline]
fn abs_diff_eq(&self, other: &Self, epsilon: A::Epsilon) -> bool {
A::abs_diff_eq(&self.x, &other.x, epsilon)
&& A::abs_diff_eq(&self.y, &other.y, epsilon)
&& A::abs_diff_eq(&self.z, &other.z, epsilon)
}
}
impl<A: A... | lt_epsilon() -> | identifier_name |
euler.rs | // Copyright 2016 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// 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 ... | }
#[cfg(feature = "rand")]
impl<A> Distribution<Euler<A>> for Standard
where
Standard: Distribution<A>,
A: Angle,
{
fn sample<R: Rng +?Sized>(&self, rng: &mut R) -> Euler<A> {
Euler {
x: rng.gen(),
y: rng.gen(),
z: rng.gen(),
}
}
}
#[cfg(feature = "m... | && A::ulps_eq(&self.y, &other.y, epsilon, max_ulps)
&& A::ulps_eq(&self.z, &other.z, epsilon, max_ulps)
} | random_line_split |
authority.rs | // Copyright 2015-2019 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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... | Ok(ForwardAuthority {
origin: Name::root().into(),
resolver,
})
}
/// Read the Authority for the origin from the specified configuration
pub async fn try_from_config(
origin: Name,
_zone_type: ZoneType,
config: &ForwardConfig,
runtime:... | pub async fn new(runtime: Handle) -> Result<Self, String> {
let resolver = TokioAsyncResolver::from_system_conf(runtime)
.map_err(|e| format!("error constructing new Resolver: {}", e))?;
| random_line_split |
authority.rs | // Copyright 2015-2019 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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... | {
origin: LowerName,
resolver: TokioAsyncResolver,
}
impl ForwardAuthority {
/// TODO: change this name to create or something
#[allow(clippy::new_without_default)]
#[doc(hidden)]
pub async fn new(runtime: Handle) -> Result<Self, String> {
let resolver = TokioAsyncResolver::from_system... | ForwardAuthority | identifier_name |
lib.rs | #![feature(quote, plugin_registrar, rustc_private)]
#![feature(tempdir, path, io, fs, process)]
extern crate syntax;
extern crate rustc;
use std::path::{PathBuf, Path};
use std::fs::{self, TempDir, File};
use std::io;
use std::io::prelude::*;
use std::process::Command;
use syntax::ast;
use syntax::codemap;
use synta... | let mut version = set_once::SetOnce::new();
let mut p = cx.new_parser_from_tts(tts);
while p.token!= token::Eof {
// <name> = "..."
let ident = p.parse_ident();
let ident_span = p.last_span;
match ident.as_str() {
"version" => {
... |
impl Options {
fn parse(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> Options { | random_line_split |
lib.rs | #![feature(quote, plugin_registrar, rustc_private)]
#![feature(tempdir, path, io, fs, process)]
extern crate syntax;
extern crate rustc;
use std::path::{PathBuf, Path};
use std::fs::{self, TempDir, File};
use std::io;
use std::io::prelude::*;
use std::process::Command;
use syntax::ast;
use syntax::codemap;
use synta... |
struct Expander {
dir: TempDir
}
impl base::TTMacroExpander for Expander {
fn expand<'cx>(&self,
cx: &'cx mut ExtCtxt,
sp: codemap::Span,
raw_tts: &[ast::TokenTree])
-> Box<MacResult+'cx>
{
macro_rules! mac_try {
... | {
let dir = match TempDir::new("rustc_python_mixin") {
Ok(d) => d,
Err(e) => {
registrar.sess.span_err(registrar.krate_span,
&format!("could not create temporary directory: {}", e));
return;
}
};
registrar.register_syntax_e... | identifier_body |
lib.rs | #![feature(quote, plugin_registrar, rustc_private)]
#![feature(tempdir, path, io, fs, process)]
extern crate syntax;
extern crate rustc;
use std::path::{PathBuf, Path};
use std::fs::{self, TempDir, File};
use std::io;
use std::io::prelude::*;
use std::process::Command;
use syntax::ast;
use syntax::codemap;
use synta... | {
version: String,
}
impl Options {
fn parse(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> Options {
let mut version = set_once::SetOnce::new();
let mut p = cx.new_parser_from_tts(tts);
while p.token!= token::Eof {
// <name> = "..."
let ident = p.parse_ident();
... | Options | identifier_name |
const-bound.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 ... | {
/*foo(1);
foo("hi".to_string());
foo(~[1, 2, 3]);
foo(F{field: 42});
foo((1, 2_usize));
foo(@1);*/
foo(box 1);
} | identifier_body | |
const-bound.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: Sync>(x: T) -> T { x }
struct F { field: int }
pub fn main() {
/*foo(1);
foo("hi".to_string());
foo(~[1, 2, 3]);
foo(F{field: 42});
foo((1, 2_usize));
foo(@1);*/
foo(box 1);
}
| foo | identifier_name |
const-bound.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 ... | foo(box 1);
} | foo(@1);*/ | random_line_split |
step6_file.rs | #![feature(exit_status)]
extern crate mal;
use std::collections::HashMap;
use std::env as stdenv;
use mal::types::{MalVal, MalRet, MalError, err_str};
use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc};
use mal::types::MalError::{ErrString, ErrMalVal};
use mal::types::MalType::{Nil, False, Sym, ... | ,
_ => { // function call
let el = try!(eval_ast(tmp.clone(), env.clone()));
let args = match *el {
List(ref args,_) => args,
_ => return err_str("Invalid apply"),
};
return match *args.clone()[0] {
Func(f,_) => f(ar... | {
let a1 = (*args)[1].clone();
ast = try!(eval(a1, env.clone()));
env = env_root(&env);
continue 'tco;
} | conditional_block |
step6_file.rs | #![feature(exit_status)]
extern crate mal;
use std::collections::HashMap;
use std::env as stdenv;
use mal::types::{MalVal, MalRet, MalError, err_str};
use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc};
use mal::types::MalError::{ErrString, ErrMalVal};
use mal::types::MalType::{Nil, False, Sym, ... | _ => Ok(ast.clone()),
}
}
fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
'tco: loop {
//println!("eval: {}, {}", ast, env.borrow());
//println!("eval: {}", ast);
match *ast {
List(_,_) => (), // continue
_ => return eval_ast(ast, env),
}
// apply list
mat... | {
match *ast {
Sym(_) => env_get(&env, &ast),
List(ref a,_) | Vector(ref a,_) => {
let mut ast_vec : Vec<MalVal> = vec![];
for mv in a.iter() {
let mv2 = mv.clone();
ast_vec.push(try!(eval(mv2, env.clone())));
}
Ok(match... | identifier_body |
step6_file.rs | #![feature(exit_status)]
extern crate mal;
use std::collections::HashMap;
use std::env as stdenv;
use mal::types::{MalVal, MalRet, MalError, err_str};
use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc};
use mal::types::MalError::{ErrString, ErrMalVal};
use mal::types::MalType::{Nil, False, Sym, ... | let c = try!(eval(a1, env.clone()));
match *c {
False | Nil => {
if args.len() >= 4 {
ast = args[3].clone();
continue 'tco;
} else {
return Ok(_nil());
... | let a1 = (*args)[1].clone(); | random_line_split |
step6_file.rs | #![feature(exit_status)]
extern crate mal;
use std::collections::HashMap;
use std::env as stdenv;
use mal::types::{MalVal, MalRet, MalError, err_str};
use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc};
use mal::types::MalError::{ErrString, ErrMalVal};
use mal::types::MalType::{Nil, False, Sym, ... | (str: String) -> MalRet {
reader::read_str(str)
}
// eval
fn eval_ast(ast: MalVal, env: Env) -> MalRet {
match *ast {
Sym(_) => env_get(&env, &ast),
List(ref a,_) | Vector(ref a,_) => {
let mut ast_vec : Vec<MalVal> = vec![];
for mv in a.iter() {
let mv2 ... | read | identifier_name |
list_blobs_00.rs | use futures::stream::StreamExt;
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// First we retrieve the account name and master key from environment variables.
let account =
std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!");
le... | use azure_sdk_core::prelude::*;
use azure_sdk_storage_blob::prelude::*;
use azure_sdk_storage_core::prelude::*; | random_line_split | |
list_blobs_00.rs | use azure_sdk_core::prelude::*;
use azure_sdk_storage_blob::prelude::*;
use azure_sdk_storage_core::prelude::*;
use futures::stream::StreamExt;
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> | {
panic!("The specified container must not exists!");
}
// create the container
client
.create_container()
.with_container_name(&container_name)
.with_public_access(PublicAccess::None)
.with_timeout(100)
.finalize()
.await?;
println!("Container {} c... | {
// First we retrieve the account name and master key from environment variables.
let account =
std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!");
let master_key =
std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!");
... | identifier_body |
list_blobs_00.rs | use azure_sdk_core::prelude::*;
use azure_sdk_storage_blob::prelude::*;
use azure_sdk_storage_core::prelude::*;
use futures::stream::StreamExt;
use std::error::Error;
#[tokio::main]
async fn | () -> Result<(), Box<dyn Error>> {
// First we retrieve the account name and master key from environment variables.
let account =
std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!");
let master_key =
std::env::var("STORAGE_MASTER_KEY").expect("Set env variable ... | main | identifier_name |
build.rs | /*
Copyright ⓒ 2017 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | /*
Before 1.13, there was no `?` operator. One of the tests needs this information.
*/
if version_matches(">=1.13.0") {
println!("cargo:rustc-cfg=has_qmark");
}
}
| println!("cargo:rustc-cfg=old_rustc_windows_linking_behaviour");
}
| conditional_block |
build.rs | /*
Copyright ⓒ 2017 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | {
println!("cargo:rerun-if-changed=build.rs");
/*
Environment might suffer from <https://github.com/DanielKeep/cargo-script/issues/50>.
*/
if cfg!(windows) {
println!("cargo:rustc-cfg=issue_50");
}
/*
With 1.15, linking on Windows was changed in regards to when it emits `dllim... | in() | identifier_name |
build.rs | /*
Copyright ⓒ 2017 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | */
if version_matches(">=1.13.0") {
println!("cargo:rustc-cfg=has_qmark");
}
}
| println!("cargo:rerun-if-changed=build.rs");
/*
Environment might suffer from <https://github.com/DanielKeep/cargo-script/issues/50>.
*/
if cfg!(windows) {
println!("cargo:rustc-cfg=issue_50");
}
/*
With 1.15, linking on Windows was changed in regards to when it emits `dllimpor... | identifier_body |
build.rs | /*
Copyright ⓒ 2017 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | extern crate rustc_version;
use rustc_version::{version_matches};
fn main() {
println!("cargo:rerun-if-changed=build.rs");
/*
Environment might suffer from <https://github.com/DanielKeep/cargo-script/issues/50>.
*/
if cfg!(windows) {
println!("cargo:rustc-cfg=issue_50");
}
/*
... | or distributed except according to those terms.
*/ | random_line_split |
monitor.rs | use winapi;
use std::collections::RingBuf;
/// Win32 implementation of the main `MonitorID` object.
pub struct MonitorID {
/// The system name of the monitor.
name: [winapi::WCHAR; 32],
/// Name to give to the user.
readable_name: String,
/// See the `StateFlags` element here:
/// http://msd... |
/// See the docs if the crate root file.
pub fn get_dimensions(&self) -> (uint, uint) {
// TODO: retreive the dimensions every time this is called
self.dimensions
}
/// This is a Win32-only function for `MonitorID` that returns the system name of the device.
pub fn get_system_name... | {
Some(self.readable_name.clone())
} | identifier_body |
monitor.rs | use winapi;
use std::collections::RingBuf;
/// Win32 implementation of the main `MonitorID` object.
pub struct MonitorID {
/// The system name of the monitor.
name: [winapi::WCHAR; 32],
/// Name to give to the user.
readable_name: String,
/// See the `StateFlags` element here:
/// http://msd... |
if (output.StateFlags & winapi::DISPLAY_DEVICE_ACTIVE) == 0 ||
(output.StateFlags & winapi::DISPLAY_DEVICE_MIRRORING_DRIVER)!= 0
{
// the device is not active
// the Win32 api usually returns a lot of inactive devices
continue;
... | {
// the device doesn't exist, which means we have finished enumerating
break;
} | conditional_block |
monitor.rs | use winapi;
use std::collections::RingBuf;
/// Win32 implementation of the main `MonitorID` object.
pub struct MonitorID {
/// The system name of the monitor.
name: [winapi::WCHAR; 32],
/// Name to give to the user.
readable_name: String,
/// See the `StateFlags` element here:
/// http://msd... | () -> MonitorID {
// we simply get all available monitors and return the one with the `PRIMARY_DEVICE` flag
// TODO: it is possible to query the win32 API for the primary monitor, this should be done
// instead
for monitor in get_available_monitors().into_iter() {
if (monitor.flags & winapi::DI... | get_primary_monitor | identifier_name |
monitor.rs | use winapi;
use std::collections::RingBuf;
/// Win32 implementation of the main `MonitorID` object.
pub struct MonitorID {
/// The system name of the monitor.
name: [winapi::WCHAR; 32],
/// Name to give to the user.
readable_name: String,
/// See the `StateFlags` element here:
/// http://msd... | // TODO: it is possible to query the win32 API for the primary monitor, this should be done
// instead
for monitor in get_available_monitors().into_iter() {
if (monitor.flags & winapi::DISPLAY_DEVICE_PRIMARY_DEVICE)!= 0 {
return monitor
}
}
panic!("Failed to find the pr... | // we simply get all available monitors and return the one with the `PRIMARY_DEVICE` flag | random_line_split |
mod.rs | /// Terminal functionality built upon core VGA driver
pub mod terminal;
pub const VIDEO_WIDTH: usize = 80;
pub const VIDEO_HEIGHT: usize = 25;
#[allow(dead_code)]
#[repr(u8)]
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
... | Yellow = 14,
White = 15,
}
pub const WHITE: u8 = Color::new(Color::White, Color::Black);
pub const GREEN: u8 = Color::new(Color::Green, Color::Black);
pub const RED: u8 = Color::new(Color::Red, Color::Black);
pub const LCYAN: u8 = Color::new(Color::LightCyan, Color::Black);
impl Color {
pub const fn new(f... | Pink = 13, | random_line_split |
mod.rs | /// Terminal functionality built upon core VGA driver
pub mod terminal;
pub const VIDEO_WIDTH: usize = 80;
pub const VIDEO_HEIGHT: usize = 25;
#[allow(dead_code)]
#[repr(u8)]
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
... | (u16);
impl Entry {
pub fn new(c: u8, color: u8) -> Entry {
Entry((color as u16) << 8 | (c as u16))
}
pub fn from_u16(data: u16) -> Entry {
Entry(data)
}
}
pub struct Writer {
ptr: usize,
}
impl Writer {
pub fn new(ptr: usize) -> Writer {
Writer { ptr: ptr }
}
... | Entry | identifier_name |
util.rs | #[cfg(test)]
use std::process::Command;
#[cfg(test)]
use rand::{self, Rng};
#[cfg(test)]
use std::env::temp_dir;
#[cfg(test)]
use std::ffi::{OsString};
#[cfg(test)]
use std::fs::File;
#[cfg(test)]
use std::io::prelude::*;
#[cfg(test)]
use std::str;
macro_rules! try_opt(
($e:expr) => (match $e { Some(e) => e, None ... |
#[inline(always)]
pub fn bit16(b: u16, pos: usize) -> u8 {
((b >> pos) & 1) as u8
}
#[inline(always)]
pub fn bitneg(b: u8, pos: usize) -> u8 {
!bit(b, pos) & 1
}
#[inline(always)]
pub fn bitneg16(b: u16, pos: usize) -> u8 {
!bit16(b, pos) & 1
}
#[cfg(test)]
pub fn assemble_to_file(code: &str) -> OsStrin... | {
(b >> pos) & 1
} | identifier_body |
util.rs | #[cfg(test)]
use std::process::Command;
#[cfg(test)]
use rand::{self, Rng};
#[cfg(test)]
use std::env::temp_dir;
#[cfg(test)]
use std::ffi::{OsString};
#[cfg(test)]
use std::fs::File;
#[cfg(test)]
use std::io::prelude::*;
#[cfg(test)]
use std::str;
macro_rules! try_opt(
($e:expr) => (match $e { Some(e) => e, None ... |
let o = Command::new("avr-objcopy")
.arg("-O").arg("binary")
.arg(middle_name)
.arg(output_name.clone())
.output()
.expect("avr-objcopy failed");
if!o.status.success() {
println!("avr-objcopy: {:?}, {:?}",
str::from_utf8(&o.stdout).unwrap(),
... | {
println!("avr-gcc: {:?}, {:?}",
str::from_utf8(&o.stdout).unwrap(),
str::from_utf8(&o.stderr).unwrap());
} | conditional_block |
util.rs | #[cfg(test)]
use std::process::Command;
#[cfg(test)]
use rand::{self, Rng};
#[cfg(test)]
use std::env::temp_dir;
#[cfg(test)]
use std::ffi::{OsString};
#[cfg(test)]
use std::fs::File;
#[cfg(test)]
use std::io::prelude::*;
#[cfg(test)]
use std::str;
macro_rules! try_opt(
($e:expr) => (match $e { Some(e) => e, None ... | (b: u8, pos: usize) -> u8 {
!bit(b, pos) & 1
}
#[inline(always)]
pub fn bitneg16(b: u16, pos: usize) -> u8 {
!bit16(b, pos) & 1
}
#[cfg(test)]
pub fn assemble_to_file(code: &str) -> OsString {
let input_name = tmpfile();
let middle_name = tmpfile();
let output_name = tmpfile();
let mut input_f... | bitneg | identifier_name |
util.rs | #[cfg(test)]
use std::process::Command;
#[cfg(test)]
use rand::{self, Rng};
#[cfg(test)]
use std::env::temp_dir;
#[cfg(test)]
use std::ffi::{OsString};
#[cfg(test)]
use std::fs::File;
#[cfg(test)]
use std::io::prelude::*;
#[cfg(test)]
use std::str;
macro_rules! try_opt(
($e:expr) => (match $e { Some(e) => e, None ... | ((b >> pos) & 1) as u8
}
#[inline(always)]
pub fn bitneg(b: u8, pos: usize) -> u8 {
!bit(b, pos) & 1
}
#[inline(always)]
pub fn bitneg16(b: u16, pos: usize) -> u8 {
!bit16(b, pos) & 1
}
#[cfg(test)]
pub fn assemble_to_file(code: &str) -> OsString {
let input_name = tmpfile();
let middle_name = tmp... | pub fn bit16(b: u16, pos: usize) -> u8 { | random_line_split |
content.rs | #![stable]
use libc;
use std;
/// Opaque struct which holds a reference to the underlying Clutter object.
#[repr(C)]
pub struct ContentRef {
opaque: *mut libc::c_void
}
/// Delegate for painting the content of an actor
///
/// Content is an interface to implement types responsible for painting the
/// content of a... | }
}
}
impl Content for ContentRef {
fn as_content(&self) -> *mut libc::c_void {
return self.opaque;
}
}
extern {
fn clutter_content_get_preferred_size(self_value: *mut libc::c_void, width: *mut f32, height: *mut f32) -> i32;
fn clutter_content_invalidate(self_value: *mut libc::c_void);
} | clutter_content_invalidate(self.as_content()); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.