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 |
|---|---|---|---|---|
lib.rs | //! The purpose of this library is to provide an OpenGL context on as many
//! platforms as possible.
//!
//! # Building a window
//!
//! There are two ways to create a window:
//!
//! - Calling `Window::new()`.
//! - Calling `let builder = WindowBuilder::new()` then `builder.build()`.
//!
//! The first way is the s... | /// Whether to use vsync. If vsync is enabled, calling `swap_buffers` will block until the
/// screen refreshes. This is typically used to prevent screen tearing.
///
/// The default is `false`.
pub vsync: bool,
}
impl<S> GlAttributes<S> {
/// Turns the `sharing` parameter into another type by ... | random_line_split | |
generic-tuple-style-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // gdb-command:print case2
// gdb-check:$2 = {{Case2, 0, 4369, 4369, 4369, 4369}, {Case2, 0, 286331153, 286331153}, {Case2, 0, 1229782938247303441}}
// gdb-command:print case3
// gdb-check:$3 = {{Case3, 0, 22873, 22873, 22873, 22873}, {Case3, 0, 1499027801, 1499027801}, {Case3, 0, 6438275382588823897}}
// gdb-command... | random_line_split | |
generic-tuple-style-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
// In order to avoid endianess trouble all of the following test values consist of a single
// repeated byte. This way each interpretation of the union should look the same, no matter if
// this is a big or little endian machine.
// 0b01111100011111000111110001111100011111000111110001111100011111... | main | identifier_name |
lib.rs | //! Simple counting bloom filters.
#![license = "MIT"]
#![deny(missing_doc)]
extern crate rand;
use rand::Rng;
use std::hash::{hash,Hash};
use std::iter;
use std::num;
use std::uint;
/// A counting bloom filter.
///
/// A bloom filter is a probabilistic data structure which allows you to add and
/// remove elements ... | for i in range(0u, 100) {
bf.remove(&i);
}
assert_eq!(bf.number_of_insertions(), 900);
for i in range(100u, 1000) {
assert!(bf.may_include(&i));
}
let false_positives = range(0u, 100).filter(|i| bf.may_include(&i)).count();
assert!(false_positives < 2); // 2%.
bf.cle... | {
use std::iter::range;
let mut bf = BloomFilter::new(1000);
for i in range(0u, 1000) {
bf.insert(&i);
}
assert_eq!(bf.number_of_insertions(), 1000);
for i in range(0u, 1000) {
assert!(bf.may_include(&i));
}
let false_positives =
range(1001u, 2000).filter(|i|... | identifier_body |
lib.rs | //! Simple counting bloom filters.
#![license = "MIT"]
#![deny(missing_doc)]
extern crate rand;
use rand::Rng;
use std::hash::{hash,Hash};
use std::iter;
use std::num;
use std::uint;
/// A counting bloom filter.
///
/// A bloom filter is a probabilistic data structure which allows you to add and
/// remove elements ... | (&self, shash: uint) -> bool {
let (a_idx, shift_amount) = self.shash_to_array_index(shash);
self.bucket_get(a_idx, shift_amount) == 0
}
/// A hash is definitely excluded iff none of the stretched hashes are in
/// the bloom filter.
fn definitely_excludes_hashed(&self, hash: u64) -> boo... | definitely_excludes_shash | identifier_name |
lib.rs | //! Simple counting bloom filters.
#![license = "MIT"]
#![deny(missing_doc)]
extern crate rand;
use rand::Rng;
use std::hash::{hash,Hash};
use std::iter;
use std::num;
use std::uint;
/// A counting bloom filter.
///
/// A bloom filter is a probabilistic data structure which allows you to add and
/// remove elements ... | self.insert_hashed(hash(h))
}
/// Removes a stretched hash from the bloom filter, taking care not to
/// decrememnt saturated counters.
///
/// It is an error to remove never-inserted elements.
fn remove_shash(&mut self, shash: uint) {
let (a_idx, shift_amount) = self.shash_to_a... | /// Inserts a value into the bloom filter. Note that the bloom filter isn't
/// parameterized over the values it holds. That's because it can hold
/// values of different types, as long as it can get a hash out of them.
pub fn insert<H: Hash>(&mut self, h: &H) { | random_line_split |
lib.rs | //! Simple counting bloom filters.
#![license = "MIT"]
#![deny(missing_doc)]
extern crate rand;
use rand::Rng;
use std::hash::{hash,Hash};
use std::iter;
use std::num;
use std::uint;
/// A counting bloom filter.
///
/// A bloom filter is a probabilistic data structure which allows you to add and
/// remove elements ... |
let new_val = b_val + 1;
self.bucket_set(a_idx, shift_amount, new_val);
}
/// Insert a hashed value into the bloom filter.
fn insert_hashed(&mut self, hash: u64) {
self.number_of_insertions += 1;
for h in stretch(&mut to_rng(hash)) {
self.insert_shash(h);
... | {
return;
} | conditional_block |
hypercalls.rs |
#[derive(Debug)]
#[repr(usize)]
#[allow(non_camel_case_types)]
pub enum Command {
set_trap_table = 0,
mmu_update = 1,
set_gdt = 2,
stack_switch = 3,
set_callbacks = 4,
fpu_taskswitch = 5,
sched_op_compat = 6,
platform_op = 7,
s... | (port: &mut Port) -> NegErrnoval {
unsafe {
use core::mem;
use core::ptr;
let mut args: SendArgs = mem::uninitialized();
args.port = ptr::read(port);
hypercall(
Command::event_channel_op,
SubCommand::send as usize,
... | send | identifier_name |
hypercalls.rs | #[derive(Debug)]
#[repr(usize)]
#[allow(non_camel_case_types)]
pub enum Command {
set_trap_table = 0,
mmu_update = 1,
set_gdt = 2,
stack_switch = 3,
set_callbacks = 4,
fpu_taskswitch = 5,
sched_op_compat = 6,
platform_op = 7,
se... | domctl = 36,
kexec_op = 37,
tmem_op = 38,
xc_reserved_op = 39,
xen_pmu_op = 40,
arch_0 = 48,
arch_1 = 49,
arch_2 = 50,
arch_3 = 51,
arch_4 = 52,
arch_5 ... | event_channel_op = 32,
physdev_op = 33,
hvm_op = 34,
sysctl = 35, | random_line_split |
rlp.rs | // The purpose of RLP is to {en|de}code arbitrarily nested arrays of binary data
// specs: https://github.com/ethereum/wiki/wiki/RLP
use std::num::Int;
use std::io::BufReader;
use std::io::extensions::u64_to_be_bytes;
use self::RlpEncodable::{Binary, List};
#[deriving(PartialEq, Eq, Show)]
pub enum RlpEncodable {
B... |
#[test]
fn rlp_encodage() {
for (a, b) in generate_pairs() {
assert!(a.encode() == b);
}
}
#[test]
fn rlp_decodage() {
for (b, a) in generate_pairs() {
assert!(a.decode() == b);
}
}
}
| {
let lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit";
(vec![
(s!(""), RlpDecodable(vec![0x80])),
(s!("\x0f"), RlpDecodable(vec![0x0f])),
(s!("\x04\x00"), RlpDecodable(vec![0x82, 0x04, 0x00])),
(s!("dog"), RlpDec... | identifier_body |
rlp.rs | // The purpose of RLP is to {en|de}code arbitrarily nested arrays of binary data
// specs: https://github.com/ethereum/wiki/wiki/RLP
use std::num::Int;
use std::io::BufReader;
use std::io::extensions::u64_to_be_bytes;
use self::RlpEncodable::{Binary, List};
#[deriving(PartialEq, Eq, Show)]
pub enum RlpEncodable {
B... | u64_to_be_bytes(length as u64, length_of_length, |v| data.push_all(v));
return data;
}
}
panic!()
}
}
impl RlpDecodable {
pub fn new(vec: Vec<u8>) -> RlpDecodable {
RlpDecodable(vec)
}
pub fn to_vec(self) -> Vec<u8> {
let RlpDecodable(vec) = self;
vec
}
pub fn ... | if length < 32u.pow(length_of_length + 1) {
let mut data = vec![length_of_length as u8 + offset + LENGTH_RANGE]; | random_line_split |
rlp.rs | // The purpose of RLP is to {en|de}code arbitrarily nested arrays of binary data
// specs: https://github.com/ethereum/wiki/wiki/RLP
use std::num::Int;
use std::io::BufReader;
use std::io::extensions::u64_to_be_bytes;
use self::RlpEncodable::{Binary, List};
#[deriving(PartialEq, Eq, Show)]
pub enum RlpEncodable {
B... | (reader: &mut BufReader, byte:u8, offset: u8) -> uint {
if byte <= (offset + LENGTH_RANGE) {
(byte - offset) as uint
} else {
let length_of_length = (byte - offset - LENGTH_RANGE) as uint;
reader.read_be_uint_n(length_of_length).unwrap() as uint
}
}
}
#[cfg(test)]
mod tests {
use std:... | decode_next_length | identifier_name |
rlp.rs | // The purpose of RLP is to {en|de}code arbitrarily nested arrays of binary data
// specs: https://github.com/ethereum/wiki/wiki/RLP
use std::num::Int;
use std::io::BufReader;
use std::io::extensions::u64_to_be_bytes;
use self::RlpEncodable::{Binary, List};
#[deriving(PartialEq, Eq, Show)]
pub enum RlpEncodable {
B... |
},
List(v) => {
let mut data:Vec<u8> = Vec::new();
for item in v.into_iter() {
data.push_all(item.encode().to_vec().as_slice());
}
RlpEncodable::encode_next_length(data.len(), LIST_OFFSET) + data
}
}
)
}
fn encode_next_length(l... | { RlpEncodable::encode_next_length(v.len(), BINARY_OFFSET) + v } | conditional_block |
tests.rs | use super::make_command_line;
use super::Arg;
use crate::env;
use crate::ffi::{OsStr, OsString};
use crate::process::Command;
#[test]
fn test_raw_args() {
let command_line = &make_command_line(
OsStr::new("quoted exe"),
&[
Arg::Regular(OsString::from("quote me")),
Arg::Raw(O... | // Invalid file names should return InvalidInput.
assert_eq!(resolve_exe(OsStr::new(""), None).unwrap_err().kind(), io::ErrorKind::InvalidInput);
assert_eq!(
resolve_exe(OsStr::new("\0"), None).unwrap_err().kind(),
io::ErrorKind::InvalidInput
);
// Trailing slash, therefore there's n... | random_line_split | |
tests.rs | use super::make_command_line;
use super::Arg;
use crate::env;
use crate::ffi::{OsStr, OsString};
use crate::process::Command;
#[test]
fn test_raw_args() {
let command_line = &make_command_line(
OsStr::new("quoted exe"),
&[
Arg::Regular(OsString::from("quote me")),
Arg::Raw(O... | // Trailing slash, therefore there's no file name component.
assert_eq!(
resolve_exe(OsStr::new(r"C:\Path\to\"), None).unwrap_err().kind(),
io::ErrorKind::InvalidInput
);
/*
Some of the following tests may need to be changed if you are deliberately
changing the behaviour of `res... | crate::io;
// Test a full path, with and without the `exe` extension.
let mut current_exe = env::current_exe().unwrap();
assert!(resolve_exe(current_exe.as_ref(), None).is_ok());
current_exe.set_extension("");
assert!(resolve_exe(current_exe.as_ref(), None).is_ok());
// Test lone file names.
... | identifier_body |
tests.rs | use super::make_command_line;
use super::Arg;
use crate::env;
use crate::ffi::{OsStr, OsString};
use crate::process::Command;
#[test]
fn test_raw_args() {
let command_line = &make_command_line(
OsStr::new("quoted exe"),
&[
Arg::Regular(OsString::from("quote me")),
Arg::Raw(O... | () {
let test_cases = [
("ä", "Ä"),
("ß", "SS"),
("Ä", "Ö"),
("Ä", "Ö"),
("I", "İ"),
("I", "i"),
("I", "ı"),
("i", "I"),
("i", "İ"),
("i", "ı"),
("İ", "I"),
("İ", "i"),
("İ", "ı"),
("ı", "I"),
("ı... | windows_env_unicode_case | identifier_name |
include_socket_addr.rs | // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
}
| {
let socket_addr = context.ok().map(|x| x.remote_socket_addr());
self.inner.handler(context).map(|x| match (x, socket_addr) {
(ResponseStatus::Done(x), Some(socket_addr)) => ResponseStatus::Done((x, socket_addr)),
(ResponseStatus::Done(_), None) => unreachable!(),
(... | identifier_body |
include_socket_addr.rs | // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (
&mut self,
context: Result<&IC, Error>,
) -> Result<ResponseStatus<(R, IC::SocketAddr)>, Error> {
let socket_addr = context.ok().map(|x| x.remote_socket_addr());
self.inner.handler(context).map(|x| match (x, socket_addr) {
(ResponseStatus::Done(x), Some(socket_addr)) =... | handler | identifier_name |
include_socket_addr.rs | // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0 | // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.... | // | random_line_split |
input.rs | //! This is the implementation of the qlc GUI.
//! There are several distinct
use std::mem;
use glutin::{ElementState, MouseButton};
type Identifier = String;
#[derive(Debug, Serialize, Deserialize)]
pub struct ScreenSlice {
pub x_min: f32,
pub x_max: f32,
pub y_min: f32,
pub y_max: f32
}
impl ScreenSlice {
f... | Move,
Enter
}
pub struct Screen {
interact: Vec<Area>,
latest_position: Option<(f32, f32)>,
latest_interact: Option<Identifier>,
}
impl Screen {
pub fn new() -> Self {
Screen {
interact: Vec::new(),
latest_position: None,
latest_interact: None,
}
}
fn send(&self, id: &str, msg: Message) {
pri... | KeyboardInput
}
enum Action {
LeaveEnter { left: String }, | random_line_split |
input.rs | //! This is the implementation of the qlc GUI.
//! There are several distinct
use std::mem;
use glutin::{ElementState, MouseButton};
type Identifier = String;
#[derive(Debug, Serialize, Deserialize)]
pub struct ScreenSlice {
pub x_min: f32,
pub x_max: f32,
pub y_min: f32,
pub y_max: f32
}
impl ScreenSlice {
f... | }
} else {
self.latest_interact = Some(area.id.clone());
Action::Enter
};
match action {
Action::LeaveEnter {left} => {
self.send(&left, Message::MouseLeave);
self.send(&area.id, Message::MouseEnter { x: x, y: y })
},
Action::Move => self.send(&area.id, Messag... | {
self.latest_position = Some((x, y));
// Traverse the list from the tail, so that the most recent added elements at the top of the screen take precedence.
let mut range = 0..self.interact.len();
while let Some(index) = range.next_back() {
let area = &self.interact[index];
if area.slice.intersect(x... | identifier_body |
input.rs | //! This is the implementation of the qlc GUI.
//! There are several distinct
use std::mem;
use glutin::{ElementState, MouseButton};
type Identifier = String;
#[derive(Debug, Serialize, Deserialize)]
pub struct ScreenSlice {
pub x_min: f32,
pub x_max: f32,
pub y_min: f32,
pub y_max: f32
}
impl ScreenSlice {
f... | {
MouseEnter { x: f32, y: f32 },
MouseLeave,
MouseMove { x: f32, y: f32 },
MouseInput { state: ElementState, button: MouseButton },
MouseWheel,
KeyboardInput
}
enum Action {
LeaveEnter { left: String },
Move,
Enter
}
pub struct Screen {
interact: Vec<Area>,
latest_position: Option<(f32, f32)>,
latest_int... | Message | identifier_name |
mod.rs | pub type c_char = i8;
pub type wchar_t = i32;
pub type off_t = i64;
pub type useconds_t = u32;
pub type blkcnt_t = i64;
pub type socklen_t = u32;
pub type sa_family_t = u8;
pub type pthread_t = ::uintptr_t;
s! {
pub struct sockaddr {
pub sa_len: u8,
pub sa_family: sa_family_t,
pub sa_data: ... | pub struct passwd {
pub pw_name: *mut ::c_char,
pub pw_passwd: *mut ::c_char,
pub pw_uid: ::uid_t,
pub pw_gid: ::gid_t,
pub pw_change: ::time_t,
pub pw_class: *mut ::c_char,
pub pw_gecos: *mut ::c_char,
pub pw_dir: *mut ::c_char,
pub pw_shell: ... | random_line_split | |
borrowck-lend-flow.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 |
// Note: the borrowck analysis is currently flow-insensitive.
// Therefore, some of these errors are marked as spurious and could be
// corrected by a simple change to the analysis. The others are
// either genuine or would require more advanced changes. The latter
// cases are noted.
fn borrow(_v: &int) {}
fn bor... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
borrowck-lend-flow.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 main() {}
| {
// In this instance, the const alias starts after the borrow.
let mut v = box 3;
borrow_mut(v);
let _w = &v;
} | identifier_body |
borrowck-lend-flow.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 ... | (_v: &mut int) {}
fn cond() -> bool { fail!() }
fn for_func(_f: || -> bool) { fail!() }
fn produce<T>() -> T { fail!(); }
fn inc(v: &mut Box<int>) {
*v = box() (**v + 1);
}
fn pre_freeze() {
// In this instance, the freeze starts before the mut borrow.
let mut v = box 3;
let _w = &v;
borrow_mut(v... | borrow_mut | identifier_name |
state_db.rs | // Copyright 2015, 2016 Ethcore (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 later version.... | }
/// Check if pruning is enabled on the database.
pub fn is_pruned(&self) -> bool {
self.db.is_pruned()
}
/// Heap size used.
pub fn mem_used(&self) -> usize {
// TODO: account for LRU-cache overhead; this is a close approximation.
self.db.mem_used() + self.account_cache.lock().accounts.len() * ::std::me... | cache_size: self.cache_size,
parent_hash: Some(parent.clone()),
commit_hash: None,
commit_number: None,
} | random_line_split |
state_db.rs | // Copyright 2015, 2016 Ethcore (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 later version.... | return true;
}
parent = &m.parent;
}
if m.accounts.contains(addr) {
trace!("Cache lookup skipped for {:?}: modified in a later block", addr);
return false;
}
}
trace!("Cache lookup skipped for {:?}: parent hash is unknown", addr);
return false;
}
}
#[cfg(test)]
mod tests {
use u... | {
let mut parent = match *parent_hash {
None => {
trace!("Cache lookup skipped for {:?}: no parent hash", addr);
return false;
}
Some(ref parent) => parent,
};
if modifications.is_empty() {
return true;
}
// Ignore all accounts modified in later blocks
// Modifications contains block ord... | identifier_body |
state_db.rs | // Copyright 2015, 2016 Ethcore (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 later version.... |
// Ignore all accounts modified in later blocks
// Modifications contains block ordered by the number
// We search for our parent in that list first and then for
// all its parent until we hit the canonical block,
// checking against all the intermediate modifications.
let mut iter = modifications.iter();
... | {
return true;
} | conditional_block |
state_db.rs | // Copyright 2015, 2016 Ethcore (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 later version.... | (db: &Database) -> Bloom {
let hash_count_entry = db.get(COL_ACCOUNT_BLOOM, ACCOUNT_BLOOM_HASHCOUNT_KEY)
.expect("Low-level database error");
let hash_count_bytes = match hash_count_entry {
Some(bytes) => bytes,
None => return Bloom::new(ACCOUNT_BLOOM_SPACE, DEFAULT_ACCOUNT_PRESET),
};
assert_eq!(has... | load_bloom | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `webrender_api` crate contains an assortment types and functions used
//! by WebRender consumers as well a... | (self) -> Arc<dyn ApiHitTester> {
self.rx.recv().unwrap()
}
}
/// Describe an item that matched a hit-test query.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct HitTestItem {
/// The pipeline that the display item that was hit belongs to.
pub pipeline: PipelineId,
/// Th... | resolve | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `webrender_api` crate contains an assortment types and functions used
//! by WebRender consumers as well a... |
}
}
}
impl From<PropertyBinding<ColorU>> for PropertyBinding<ColorF> {
fn from(value: PropertyBinding<ColorU>) -> PropertyBinding<ColorF> {
match value {
PropertyBinding::Value(value) => PropertyBinding::Value(value.into()),
PropertyBinding::Binding(k, v) => {
... | {
PropertyBinding::Binding(k.into(), v.into())
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `webrender_api` crate contains an assortment types and functions used
//! by WebRender consumers as well a... | mod display_item;
mod display_item_cache;
mod display_list;
mod font;
mod gradient_builder;
mod image;
pub mod units;
pub use crate::color::*;
pub use crate::display_item::*;
pub use crate::display_item_cache::DisplayItemCache;
pub use crate::display_list::*;
pub use crate::font::*;
pub use crate::gradient_builder::*;... | extern crate malloc_size_of;
extern crate peek_poke;
pub mod channel;
mod color; | random_line_split |
mod.rs | /*
(c) 2014 by Jeffrey Quesnelle
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in th... | pub a: u8,
pub x: u8,
pub y: u8,
pub p: u8
} | pub pc: u16,
pub sp: u8, | random_line_split |
mod.rs | /*
(c) 2014 by Jeffrey Quesnelle
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in th... | {
pub pc: u16,
pub sp: u8,
pub a: u8,
pub x: u8,
pub y: u8,
pub p: u8
}
| Cpu | identifier_name |
errors1.rs | // errors1.rs
// This function refuses to generate text to be printed on a nametag if
// you pass it an empty string. It'd be nicer if it explained what the problem
// was, instead of just sometimes returning `None`. The 2nd test currently
// does not compile or pass, but it illustrates the behavior we would like
// th... |
}
#[cfg(test)]
mod tests {
use super::*;
// This test passes initially if you comment out the 2nd test.
// You'll need to update what this test expects when you change
// the function under test!
#[test]
fn generates_nametag_text_for_a_nonempty_name() {
assert_eq!(
generat... | {
// Empty names aren't allowed.
None
} | conditional_block |
errors1.rs | // errors1.rs
// This function refuses to generate text to be printed on a nametag if
// you pass it an empty string. It'd be nicer if it explained what the problem
// was, instead of just sometimes returning `None`. The 2nd test currently
// does not compile or pass, but it illustrates the behavior we would like
// th... |
#[cfg(test)]
mod tests {
use super::*;
// This test passes initially if you comment out the 2nd test.
// You'll need to update what this test expects when you change
// the function under test!
#[test]
fn generates_nametag_text_for_a_nonempty_name() {
assert_eq!(
generate_... | {
if name.len() > 0 {
Some(format!("Hi! My name is {}", name))
} else {
// Empty names aren't allowed.
None
}
} | identifier_body |
errors1.rs | // errors1.rs
// This function refuses to generate text to be printed on a nametag if
// you pass it an empty string. It'd be nicer if it explained what the problem
// was, instead of just sometimes returning `None`. The 2nd test currently
// does not compile or pass, but it illustrates the behavior we would like
// th... | );
}
} | fn explains_why_generating_nametag_text_fails() {
assert_eq!(
generate_nametag_text("".into()),
Err("`name` was empty; it must be nonempty.".into()) | random_line_split |
errors1.rs | // errors1.rs
// This function refuses to generate text to be printed on a nametag if
// you pass it an empty string. It'd be nicer if it explained what the problem
// was, instead of just sometimes returning `None`. The 2nd test currently
// does not compile or pass, but it illustrates the behavior we would like
// th... | (name: String) -> Option<String> {
if name.len() > 0 {
Some(format!("Hi! My name is {}", name))
} else {
// Empty names aren't allowed.
None
}
}
#[cfg(test)]
mod tests {
use super::*;
// This test passes initially if you comment out the 2nd test.
// You'll need to updat... | generate_nametag_text | identifier_name |
xrview.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRViewBinding;
use crate::dom::bindings::codegen::Bindings::XRViewBi... | /// https://immersive-web.github.io/webxr/#dom-xrview-eye
fn Eye(&self) -> XREye {
self.eye
}
#[allow(unsafe_code)]
/// https://immersive-web.github.io/webxr/#dom-xrview-projectionmatrix
unsafe fn ProjectionMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> {
NonNull::new(s... | }
impl XRViewMethods for XRView { | random_line_split |
xrview.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRViewBinding;
use crate::dom::bindings::codegen::Bindings::XRViewBi... | else {
(&data.right_projection_matrix, &data.right_view_matrix)
};
let cx = global.get_cx();
unsafe {
create_typed_array(cx, proj, &ret.proj);
create_typed_array(cx, view, &ret.view);
}
ret
}
pub fn session(&self) -> &XRSession {
... | {
(&data.left_projection_matrix, &data.left_view_matrix)
} | conditional_block |
xrview.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRViewBinding;
use crate::dom::bindings::codegen::Bindings::XRViewBi... | (session: &XRSession, eye: XREye) -> XRView {
XRView {
reflector_: Reflector::new(),
session: Dom::from_ref(session),
eye,
proj: Heap::default(),
view: Heap::default(),
}
}
#[allow(unsafe_code)]
pub fn new(
global: &GlobalS... | new_inherited | identifier_name |
xrview.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRViewBinding;
use crate::dom::bindings::codegen::Bindings::XRViewBi... |
#[allow(unsafe_code)]
/// https://immersive-web.github.io/webxr/#dom-xrview-projectionmatrix
unsafe fn ViewMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> {
NonNull::new(self.view.get()).unwrap()
}
}
| {
NonNull::new(self.proj.get()).unwrap()
} | identifier_body |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use diem_logger::debug;
use std::{cmp::min, future::Future, pin::Pin, thread, time::Duration};
/// Given an operation retries it successfully sleeping everytime it fails
/// If the operation succeeds before the... | (&mut self) -> Option<Duration> {
Some(self.duration)
}
}
impl Iterator for ExponentWithLimitDelay {
type Item = Duration;
fn next(&mut self) -> Option<Duration> {
let duration = self.current;
self.current = min(
Duration::from_millis((self.current.as_millis() as f64 * ... | next | identifier_name |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use diem_logger::debug;
use std::{cmp::min, future::Future, pin::Pin, thread, time::Duration};
/// Given an operation retries it successfully sleeping everytime it fails
/// If the operation succeeds before the... |
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fixed_retry_strategy_success() {
let mut collection = vec![1, 2, 3, 4, 5].into_iter();
let result = retry(fixed_retry_strategy(0, 10), || match collection.next() {
Some(n) if n == 5 => Ok(n),
Some(_) => Err("... | {
let duration = self.current;
self.current = min(
Duration::from_millis((self.current.as_millis() as f64 * self.exp) as u64),
self.limit,
);
Some(duration)
} | identifier_body |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use diem_logger::debug;
use std::{cmp::min, future::Future, pin::Pin, thread, time::Duration};
/// Given an operation retries it successfully sleeping everytime it fails
/// If the operation succeeds before the... | } else {
return Err(err);
}
}
}
}
}
pub fn fixed_retry_strategy(delay_ms: u64, tries: usize) -> impl Iterator<Item = Duration> {
FixedDelay::new(delay_ms).take(tries)
}
pub fn exp_retry_strategy(
start_ms: u64,
limit_ms: u64,
... | if let Some(delay) = iterator.next() {
debug!("{}. Retrying in {} seconds..", err, delay.as_secs());
tokio::time::sleep(delay).await; | random_line_split |
rustiny-rulecomp.rs | //! TODO: Docs
#![feature(plugin)]
extern crate clap;
extern crate env_logger;
extern crate rustiny;
use clap::{Arg, App};
use rustiny::util::{read_file, write_file};
#[cfg(not(test))]
fn | () {
env_logger::init().unwrap();
// Parse arguments
let app = App::new("rustiny-rulecomp")
.version(env!("CARGO_PKG_VERSION"))
.author("Markus SIemens <markus@m-siemens.de>")
.arg(Arg::with_name("output")
.short("o")
.value_name("OUTPUT")
.help("Sets ... | main | identifier_name |
rustiny-rulecomp.rs | //! TODO: Docs
#![feature(plugin)]
extern crate clap;
extern crate env_logger;
extern crate rustiny;
use clap::{Arg, App};
use rustiny::util::{read_file, write_file};
#[cfg(not(test))]
fn main() {
env_logger::init().unwrap();
// Parse arguments
let app = App::new("rustiny-rulecomp")
.version(en... |
// Read source file
let input_file = args.value_of("INPUT").unwrap();
let source = read_file(input_file);
// Compile rules
let rules = rustiny::back::compile_rules(&source, input_file);
if let Some(output_file) = args.value_of("output") {
write_file(output_file, &rules);
} else {
... | .required(true)
.index(1));
let args = app.get_matches(); | random_line_split |
rustiny-rulecomp.rs | //! TODO: Docs
#![feature(plugin)]
extern crate clap;
extern crate env_logger;
extern crate rustiny;
use clap::{Arg, App};
use rustiny::util::{read_file, write_file};
#[cfg(not(test))]
fn main() | let input_file = args.value_of("INPUT").unwrap();
let source = read_file(input_file);
// Compile rules
let rules = rustiny::back::compile_rules(&source, input_file);
if let Some(output_file) = args.value_of("output") {
write_file(output_file, &rules);
} else {
println!("{}", &r... | {
env_logger::init().unwrap();
// Parse arguments
let app = App::new("rustiny-rulecomp")
.version(env!("CARGO_PKG_VERSION"))
.author("Markus SIemens <markus@m-siemens.de>")
.arg(Arg::with_name("output")
.short("o")
.value_name("OUTPUT")
.help("Se... | identifier_body |
rustiny-rulecomp.rs | //! TODO: Docs
#![feature(plugin)]
extern crate clap;
extern crate env_logger;
extern crate rustiny;
use clap::{Arg, App};
use rustiny::util::{read_file, write_file};
#[cfg(not(test))]
fn main() {
env_logger::init().unwrap();
// Parse arguments
let app = App::new("rustiny-rulecomp")
.version(en... | else {
println!("{}", &rules)
}
} | {
write_file(output_file, &rules);
} | conditional_block |
floatf.rs | //! formatter for %f %F common-notation floating-point subs
use super::super::format_field::FormatField;
use super::super::formatter::{FormatPrimitive, Formatter, InPrefix};
use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis};
pub struct | {
as_num: f64,
}
impl Floatf {
pub fn new() -> Floatf {
Floatf { as_num: 0.0 }
}
}
impl Formatter for Floatf {
fn get_primitive(
&self,
field: &FormatField,
inprefix: &InPrefix,
str_in: &str,
) -> Option<FormatPrimitive> {
let second_field = field.sec... | Floatf | identifier_name |
floatf.rs | //! formatter for %f %F common-notation floating-point subs
use super::super::format_field::FormatField;
use super::super::formatter::{FormatPrimitive, Formatter, InPrefix};
use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis};
pub struct Floatf {
as_num: f64,
}
impl Floatf {
pu... | } | Some(f)
}
fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String {
primitive_to_str_common(prim, &field)
} | random_line_split |
path.rs | use crate::factory::IFactory;
use crate::geometry::IGeometry;
use crate::resource::IResource;
use com_wrapper::ComWrapper;
use dcommon::Error;
use winapi::shared::winerror::SUCCEEDED;
use winapi::um::d2d1::{ID2D1Geometry, ID2D1PathGeometry, ID2D1Resource};
use wio::com::ComPtr;
pub use self::builder::*;
pub mod buil... | (&self) -> &ID2D1Geometry {
&self.ptr
}
}
unsafe impl super::GeometryType for PathGeometry {}
| raw_geom | identifier_name |
path.rs | use crate::factory::IFactory;
use crate::geometry::IGeometry;
use crate::resource::IResource;
use com_wrapper::ComWrapper;
use dcommon::Error;
use winapi::shared::winerror::SUCCEEDED;
use winapi::um::d2d1::{ID2D1Geometry, ID2D1PathGeometry, ID2D1Resource};
use wio::com::ComPtr;
pub use self::builder::*;
pub mod buil... | }
unsafe impl IResource for PathGeometry {
unsafe fn raw_resource(&self) -> &ID2D1Resource {
&self.ptr
}
}
unsafe impl IGeometry for PathGeometry {
unsafe fn raw_geom(&self) -> &ID2D1Geometry {
&self.ptr
}
}
unsafe impl super::GeometryType for PathGeometry {} | Err(From::from(result))
}
}
} | random_line_split |
path.rs | use crate::factory::IFactory;
use crate::geometry::IGeometry;
use crate::resource::IResource;
use com_wrapper::ComWrapper;
use dcommon::Error;
use winapi::shared::winerror::SUCCEEDED;
use winapi::um::d2d1::{ID2D1Geometry, ID2D1PathGeometry, ID2D1Resource};
use wio::com::ComPtr;
pub use self::builder::*;
pub mod buil... | else {
Err(hr.into())
}
} else {
Err(hr.into())
}
}
}
pub fn segment_count(&self) -> Result<u32, Error> {
unsafe {
let mut count = 0;
let result = self.ptr.GetSegmentCount(&mut count);
... | {
Ok(PathBuilder {
path: path,
sink: ComPtr::from_raw(ptr),
})
} | conditional_block |
main.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
//! Standalone server for socket_bench
//! ========================================
//!
//! You can run `socket_bench` across a real network by running this bench
//! server remotely. For example,
//!
//! `RUSTF... |
std::thread::park();
}
| {
let addr = start_stream_server(&executor, build_tcp_noise_transport(), addr);
info!("bench: tcp+noise: listening on: {}", addr);
} | conditional_block |
main.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
//! Standalone server for socket_bench
//! ========================================
//!
//! You can run `socket_bench` across a real network by running this bench
//! server remotely. For example,
//!
//! `RUSTF... | }
std::thread::park();
}
| {
::diem_logger::Logger::new().init();
let args = Args::from_env();
let rt = Builder::new_multi_thread()
.worker_threads(32)
.enable_all()
.build()
.unwrap();
let executor = rt.handle();
if let Some(addr) = args.tcp_addr {
let addr = start_stream_server(&ex... | identifier_body |
main.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
//! Standalone server for socket_bench
//! ========================================
//!
//! You can run `socket_bench` across a real network by running this bench
//! server remotely. For example,
//!
//! `RUSTF... | } | random_line_split | |
main.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
//! Standalone server for socket_bench
//! ========================================
//!
//! You can run `socket_bench` across a real network by running this bench
//! server remotely. For example,
//!
//! `RUSTF... | () {
::diem_logger::Logger::new().init();
let args = Args::from_env();
let rt = Builder::new_multi_thread()
.worker_threads(32)
.enable_all()
.build()
.unwrap();
let executor = rt.handle();
if let Some(addr) = args.tcp_addr {
let addr = start_stream_server(&exe... | main | identifier_name |
force_generator.rs | #![allow(missing_docs)] // for downcast.
use downcast_rs::Downcast;
use generational_arena::Arena;
use na::RealField;
use crate::object::{BodyHandle, BodySet, DefaultBodyHandle};
use crate::solver::IntegrationParameters;
/// Default force generator set based on an arena with generational indices.
pub type DefaultFor... |
fn get_mut(&mut self, handle: Self::Handle) -> Option<&mut Self::ForceGenerator> {
self.get_mut(handle).map(|c| &mut **c)
}
fn contains(&self, handle: Self::Handle) -> bool {
self.contains(handle)
}
fn foreach(&self, mut f: impl FnMut(Self::Handle, &Self::ForceGenerator)) {
... |
fn get(&self, handle: Self::Handle) -> Option<&Self::ForceGenerator> {
self.get(handle).map(|c| &**c)
} | random_line_split |
force_generator.rs | #![allow(missing_docs)] // for downcast.
use downcast_rs::Downcast;
use generational_arena::Arena;
use na::RealField;
use crate::object::{BodyHandle, BodySet, DefaultBodyHandle};
use crate::solver::IntegrationParameters;
/// Default force generator set based on an arena with generational indices.
pub type DefaultFor... |
fn get_mut(&mut self, handle: Self::Handle) -> Option<&mut Self::ForceGenerator> {
self.get_mut(handle).map(|c| &mut **c)
}
fn contains(&self, handle: Self::Handle) -> bool {
self.contains(handle)
}
fn foreach(&self, mut f: impl FnMut(Self::Handle, &Self::ForceGenerator)) {
... | {
self.get(handle).map(|c| &**c)
} | identifier_body |
force_generator.rs | #![allow(missing_docs)] // for downcast.
use downcast_rs::Downcast;
use generational_arena::Arena;
use na::RealField;
use crate::object::{BodyHandle, BodySet, DefaultBodyHandle};
use crate::solver::IntegrationParameters;
/// Default force generator set based on an arena with generational indices.
pub type DefaultFor... | (&mut self, handle: Self::Handle) -> Option<&mut Self::ForceGenerator> {
self.get_mut(handle).map(|c| &mut **c)
}
fn contains(&self, handle: Self::Handle) -> bool {
self.contains(handle)
}
fn foreach(&self, mut f: impl FnMut(Self::Handle, &Self::ForceGenerator)) {
for (h, b) in... | get_mut | identifier_name |
ray_bounding_sphere.rs | use crate::bounding_volume::BoundingSphere;
use crate::math::Isometry;
use crate::query::{Ray, RayCast, RayIntersection};
use crate::shape::Ball;
use na::RealField;
impl<N: RealField> RayCast<N> for BoundingSphere<N> {
#[inline]
fn toi_with_ray(&self, m: &Isometry<N>, ray: &Ray<N>, max_toi: N, solid: bool) -> ... | (
&self,
m: &Isometry<N>,
ray: &Ray<N>,
max_toi: N,
solid: bool,
) -> Option<RayIntersection<N>> {
let centered_ray = ray.translate_by(-(m * self.center()).coords);
Ball::new(self.radius()).toi_and_normal_and_uv_with_ray(
&Isometry::identity(),
... | toi_and_normal_and_uv_with_ray | identifier_name |
ray_bounding_sphere.rs | use crate::bounding_volume::BoundingSphere;
use crate::math::Isometry;
use crate::query::{Ray, RayCast, RayIntersection};
use crate::shape::Ball;
use na::RealField;
impl<N: RealField> RayCast<N> for BoundingSphere<N> {
#[inline]
fn toi_with_ray(&self, m: &Isometry<N>, ray: &Ray<N>, max_toi: N, solid: bool) -> ... |
#[cfg(feature = "dim3")]
#[inline]
fn toi_and_normal_and_uv_with_ray(
&self,
m: &Isometry<N>,
ray: &Ray<N>,
max_toi: N,
solid: bool,
) -> Option<RayIntersection<N>> {
let centered_ray = ray.translate_by(-(m * self.center()).coords);
Ball::new(se... | {
let centered_ray = ray.translate_by(-(m * self.center()).coords);
Ball::new(self.radius()).toi_and_normal_with_ray(
&Isometry::identity(),
¢ered_ray,
max_toi,
solid,
)
} | identifier_body |
ray_bounding_sphere.rs | use crate::bounding_volume::BoundingSphere;
use crate::math::Isometry;
use crate::query::{Ray, RayCast, RayIntersection};
use crate::shape::Ball;
use na::RealField;
impl<N: RealField> RayCast<N> for BoundingSphere<N> {
#[inline]
fn toi_with_ray(&self, m: &Isometry<N>, ray: &Ray<N>, max_toi: N, solid: bool) -> ... |
Ball::new(self.radius()).intersects_ray(&Isometry::identity(), ¢ered_ray, max_toi)
}
} | fn intersects_ray(&self, m: &Isometry<N>, ray: &Ray<N>, max_toi: N) -> bool {
let centered_ray = ray.translate_by(-(m * self.center()).coords); | random_line_split |
regions-creating-enums5.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a> {
num(usize),
add(&'a ast<'a>, &'a ast<'a>)
}
fn mk_add_ok<'a>(x: &'a ast<'a>, y: &'a ast<'a>, _z: &ast) -> ast<'a> {
ast::add(x, y)
}
pub fn main() {
}
| ast | identifier_name |
regions-creating-enums5.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 ... | {
} | identifier_body | |
regions-creating-enums5.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 | #![allow(dead_code)]
#![allow(non_camel_case_types)]
// pretty-expanded FIXME #23616
enum ast<'a> {
num(usize),
add(&'a ast<'a>, &'a ast<'a>)
}
fn mk_add_ok<'a>(x: &'a ast<'a>, y: &'a ast<'a>, _z: &ast) -> ast<'a> {
ast::add(x, y)
}
pub fn main() {
} | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass | random_line_split |
archive.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <'a>(&'a self, file: &str) -> Option<&'a [u8]> {
unsafe {
let mut size = 0 as libc::size_t;
let ptr = file.with_c_str(|file| {
llvm::LLVMRustArchiveReadSection(self.ptr, file, &mut size)
});
if ptr.is_null() {
None
} els... | read | identifier_name |
archive.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
/// Reads a file in the archive
pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> {
unsafe {
let mut size = 0 as libc::size_t;
let ptr = file.with_c_str(|file| {
llvm::LLVMRustArchiveReadSection(self.ptr, file, &mut size)
});
if p... | {
unsafe {
let ar = dst.with_c_str(|dst| {
llvm::LLVMRustOpenArchive(dst)
});
if ar.is_null() {
None
} else {
Some(ArchiveRO { ptr: ar })
}
}
} | identifier_body |
archive.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | match cmd.spawn() {
Ok(prog) => {
let o = prog.wait_with_output().unwrap();
if!o.status.success() {
sess.err(format!("{} failed with: {}", cmd, o.status));
sess.note(format!("stdout ---\n{}",
str::from_utf8(o.output.as... | random_line_split | |
archive.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | ;
run_ar(self.sess, cmd, None, [&self.dst, file]);
}
/// Removes a file from this archive
pub fn remove_file(&mut self, file: &str) {
run_ar(self.sess, "d", None, [&self.dst, &Path::new(file)]);
}
/// Updates all symbols in the archive (runs 'ar s' over it)
pub fn update_symbol... | {"rS"} | conditional_block |
cci_nested_lib.rs | #![feature(box_syntax)]
use std::cell::RefCell;
pub struct Entry<A,B> {
key: A,
value: B
}
pub struct alist<A,B> {
eq_fn: extern "Rust" fn(A,A) -> bool,
data: Box<RefCell<Vec<Entry<A,B>>>>,
}
pub fn alist_add<A:'static,B:'static>(lst: &alist<A,B>, k: A, v: B) {
let mut data = lst.data.borrow_mut... | <A:Clone +'static,
B:Clone +'static>(
lst: &alist<A,B>,
k: A)
-> B {
let eq_fn = lst.eq_fn;
let data = lst.data.borrow();
for entry in &(*data) {
if eq_fn(entry.key.clone(), k.clone()) {
return entry.value.clone();
... | alist_get | identifier_name |
cci_nested_lib.rs | #![feature(box_syntax)]
use std::cell::RefCell;
pub struct Entry<A,B> {
key: A,
value: B
}
pub struct alist<A,B> {
eq_fn: extern "Rust" fn(A,A) -> bool,
data: Box<RefCell<Vec<Entry<A,B>>>>,
}
pub fn alist_add<A:'static,B:'static>(lst: &alist<A,B>, k: A, v: B) {
let mut data = lst.data.borrow_mut... |
}
panic!();
}
#[inline]
pub fn new_int_alist<B:'static>() -> alist<isize, B> {
fn eq_int(a: isize, b: isize) -> bool { a == b }
return alist {
eq_fn: eq_int,
data: box RefCell::new(Vec::new()),
};
}
#[inline]
pub fn new_int_alist_2<B:'static>() -> alist<isize, B> {
#[inline]
... | {
return entry.value.clone();
} | conditional_block |
cci_nested_lib.rs | #![feature(box_syntax)]
use std::cell::RefCell;
pub struct Entry<A,B> {
key: A,
value: B
}
pub struct alist<A,B> {
eq_fn: extern "Rust" fn(A,A) -> bool,
data: Box<RefCell<Vec<Entry<A,B>>>>,
}
pub fn alist_add<A:'static,B:'static>(lst: &alist<A,B>, k: A, v: B) {
let mut data = lst.data.borrow_mut... |
#[inline]
pub fn new_int_alist_2<B:'static>() -> alist<isize, B> {
#[inline]
fn eq_int(a: isize, b: isize) -> bool { a == b }
return alist {
eq_fn: eq_int,
data: box RefCell::new(Vec::new()),
};
} | } | random_line_split |
audio-whitenoise.rs | extern crate sdl2;
extern crate rand;
use sdl2::audio::{AudioCallback, AudioSpecDesired};
use std::time::Duration;
struct MyCallback {
volume: f32
}
impl AudioCallback for MyCallback {
type Channel = f32;
fn callback(&mut self, out: &mut [f32]) |
}
fn main() -> Result<(), String> {
let sdl_context = sdl2::init()?;
let audio_subsystem = sdl_context.audio()?;
let desired_spec = AudioSpecDesired {
freq: Some(44_100),
channels: Some(1), // mono
samples: None, // default sample size
};
// None: use default device... | {
use self::rand::{Rng, thread_rng};
let mut rng = thread_rng();
// Generate white noise
for x in out.iter_mut() {
*x = (rng.gen_range(0.0, 2.0) - 1.0) * self.volume;
}
} | identifier_body |
audio-whitenoise.rs | extern crate sdl2;
extern crate rand;
use sdl2::audio::{AudioCallback, AudioSpecDesired};
use std::time::Duration;
struct | {
volume: f32
}
impl AudioCallback for MyCallback {
type Channel = f32;
fn callback(&mut self, out: &mut [f32]) {
use self::rand::{Rng, thread_rng};
let mut rng = thread_rng();
// Generate white noise
for x in out.iter_mut() {
*x = (rng.gen_range(0.0, 2.0) - 1.... | MyCallback | identifier_name |
audio-whitenoise.rs | extern crate sdl2; | use std::time::Duration;
struct MyCallback {
volume: f32
}
impl AudioCallback for MyCallback {
type Channel = f32;
fn callback(&mut self, out: &mut [f32]) {
use self::rand::{Rng, thread_rng};
let mut rng = thread_rng();
// Generate white noise
for x in out.iter_mut() {
... | extern crate rand;
use sdl2::audio::{AudioCallback, AudioSpecDesired}; | random_line_split |
look.rs | // Copyright 2015-2016 Joe Neeman.
//
// 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... |
quickcheck(prop as fn(_, _) -> _);
}
}
| {
a.intersection(&b).as_set() == &a.as_set().intersection(b.as_set())
} | identifier_body |
look.rs | // Copyright 2015-2016 Joe Neeman.
//
// 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... | (a: Look, b: Look) -> bool {
a.intersection(&b) <= a
}
quickcheck(prop as fn(_, _) -> _);
}
#[test]
fn intersection_eoi() {
fn prop(a: Look, b: Look) -> bool {
a.intersection(&b).allows_eoi() == (a.allows_eoi() && b.allows_eoi())
}
quickcheck(... | prop | identifier_name |
look.rs | // Copyright 2015-2016 Joe Neeman.
//
// 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... | None
}
}
}
impl Look {
pub fn intersection(&self, other: &Look) -> Look {
use self::Look::*;
match *self {
Full => *other,
WordChar => match *other {
Full => WordChar,
WordChar => WordChar,
_ => Empty,
... | } else if self.intersection(other) == *self {
Some(Ordering::Less)
} else if self.intersection(other) == *other {
Some(Ordering::Greater)
} else { | random_line_split |
net.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/. */
#[crate_id = "github.com/mozilla/servo#net:0.1"];
#[crate_type = "lib"];
#[feature(globs, managed_boxes)];
| extern crate http;
extern crate servo_util = "util";
extern crate stb_image;
extern crate extra;
extern crate png;
extern crate serialize;
extern crate sync;
/// Image handling.
///
/// It may be surprising that this goes in the network crate as opposed to the graphics crate.
/// However, image handling is generally v... | extern crate collections;
extern crate geom; | random_line_split |
borrowck-closures-two-mut.rs | // Tests that two closures cannot simultaneously have mutable
// access to the variable, whether that mutable access be used
// for direct assignment or for taking mutable ref. Issue #6801.
fn to_fn_mut<F: FnMut()>(f: F) -> F { f }
fn a() {
let mut x = 3;
let c1 = to_fn_mut(|| x = 4);
let c2 = to_fn_mut... | drop((c1, c2));
}
fn d() {
let mut x = 3;
let c1 = to_fn_mut(|| x = 5);
let c2 = to_fn_mut(|| { let _y = to_fn_mut(|| set(&mut x)); }); // (nested closure)
//~^ ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn g() {
struct Foo {
f: Box<isize>
}
let mu... | let c1 = to_fn_mut(|| x = 5);
let c2 = to_fn_mut(|| set(&mut x)); //~ ERROR cannot borrow `x` as mutable more than once | random_line_split |
borrowck-closures-two-mut.rs | // Tests that two closures cannot simultaneously have mutable
// access to the variable, whether that mutable access be used
// for direct assignment or for taking mutable ref. Issue #6801.
fn to_fn_mut<F: FnMut()>(f: F) -> F { f }
fn a() {
let mut x = 3;
let c1 = to_fn_mut(|| x = 4);
let c2 = to_fn_mut... | () {
let mut x = 3;
let c1 = to_fn_mut(|| x = 5);
let c2 = to_fn_mut(|| { let _y = to_fn_mut(|| set(&mut x)); }); // (nested closure)
//~^ ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn g() {
struct Foo {
f: Box<isize>
}
let mut x: Box<_> = Box::new(Foo ... | d | identifier_name |
borrowck-closures-two-mut.rs | // Tests that two closures cannot simultaneously have mutable
// access to the variable, whether that mutable access be used
// for direct assignment or for taking mutable ref. Issue #6801.
fn to_fn_mut<F: FnMut()>(f: F) -> F |
fn a() {
let mut x = 3;
let c1 = to_fn_mut(|| x = 4);
let c2 = to_fn_mut(|| x = 5); //~ ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn set(x: &mut isize) {
*x = 4;
}
fn b() {
let mut x = 3;
let c1 = to_fn_mut(|| set(&mut x));
let c2 = to_fn_mut(|| set(&mut x))... | { f } | identifier_body |
pipe.rs | use alloc::arc::{Arc, Weak};
use collections::{BTreeMap, VecDeque};
use core::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use spin::{Mutex, Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
use sync::WaitCondition;
use syscall::error::{Error, Result, EBADF, EPIPE};
use syscall::flag::O_NONBLOCK;
use sysc... | (&self, id: usize, buf: &[u8]) -> Result<usize> {
let pipe_option = {
let pipes = pipes();
pipes.1.get(&id).map(|pipe| pipe.clone())
};
if let Some(pipe) = pipe_option {
pipe.write(buf)
} else {
Err(Error::new(EBADF))
}
}
... | write | identifier_name |
pipe.rs | use alloc::arc::{Arc, Weak};
use collections::{BTreeMap, VecDeque};
use core::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use spin::{Mutex, Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
use sync::WaitCondition;
use syscall::error::{Error, Result, EBADF, EPIPE};
use syscall::flag::O_NONBLOCK;
use sysc... | vec: Arc::new(Mutex::new(VecDeque::new())),
}
}
fn read(&self, buf: &mut [u8]) -> Result<usize> {
loop {
{
let mut vec = self.vec.lock();
let mut i = 0;
while i < buf.len() {
if let Some(b) = vec.pop_fr... | random_line_split | |
pipe.rs | use alloc::arc::{Arc, Weak};
use collections::{BTreeMap, VecDeque};
use core::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use spin::{Mutex, Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
use sync::WaitCondition;
use syscall::error::{Error, Result, EBADF, EPIPE};
use syscall::flag::O_NONBLOCK;
use sysc... | if self.flags & O_NONBLOCK == O_NONBLOCK || Arc::weak_count(&self.vec) == 0 {
return Ok(0);
} else {
self.condition.wait();
}
}
}
}
/// Read side of a pipe
#[derive(Clone)]
pub struct PipeWrite {
condition: Arc<WaitCondition>,
vec... | {
loop {
{
let mut vec = self.vec.lock();
let mut i = 0;
while i < buf.len() {
if let Some(b) = vec.pop_front() {
buf[i] = b;
i += 1;
} else {
... | identifier_body |
pipe.rs | use alloc::arc::{Arc, Weak};
use collections::{BTreeMap, VecDeque};
use core::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use spin::{Mutex, Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
use sync::WaitCondition;
use syscall::error::{Error, Result, EBADF, EPIPE};
use syscall::flag::O_NONBLOCK;
use sysc... | else {
Err(Error::new(EPIPE))
}
}
}
impl Drop for PipeWrite {
fn drop(&mut self) {
self.condition.notify();
}
}
| {
let mut vec = vec_lock.lock();
for &b in buf.iter() {
vec.push_back(b);
}
self.condition.notify();
Ok(buf.len())
} | conditional_block |
mock_alarm.rs | // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | use kernel::hil::time::Ticks;
self.setpoint.set(Some(reference.wrapping_add(dt)));
}
fn get_alarm(&self) -> Self::Ticks { self.setpoint.get().unwrap_or(0.into()) }
// Ignored -- the test should manually trigger the client.
fn set_alarm_client(&'a self, _client: &'a dyn kernel::hil::tim... | }
impl<'a> kernel::hil::time::Alarm<'a> for MockAlarm {
fn set_alarm(&self, reference: Self::Ticks, dt: Self::Ticks) { | random_line_split |
mock_alarm.rs | // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
fn disarm(&self) -> kernel::ReturnCode {
self.setpoint.set(None);
kernel::ReturnCode::SUCCESS
}
fn minimum_dt(&self) -> Self::Ticks { 1.into() }
}
| { self.setpoint.get().is_some() } | identifier_body |
mock_alarm.rs | // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | {
current_time: core::cell::Cell<kernel::hil::time::Ticks32>,
setpoint: core::cell::Cell<Option<kernel::hil::time::Ticks32>>,
}
impl MockAlarm {
pub fn new() -> MockAlarm {
MockAlarm {
current_time: core::cell::Cell::new(0.into()),
setpoint: core::cell::Cell::new(Some(0.int... | MockAlarm | identifier_name |
color.rs | use na::Vector3;
use std::fmt;
use std::ops::{Mul, Add, Div};
use std::cmp::Ordering;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Color {
pub rgb: Vector3<f64>
}
impl Color {
pub fn new(r:f64, g:f64, b:f64) -> Color {
return Color {
rgb: Vector3::new(r,g,b)
}
}
pub... | else { self.rgb.y },
if self.rgb.z.is_nan() { 0. } else { self.rgb.z },
);
}
}
impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "#{:0>2x}{:0>2x}{:0>2x}", (self.rgb.x * 255f64) as u8, (self.rgb.y * 255f64) as u8, (self.rgb.z * 255f64) a... | { 0. } | conditional_block |
color.rs | use na::Vector3;
use std::fmt;
use std::ops::{Mul, Add, Div};
use std::cmp::Ordering;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Color {
pub rgb: Vector3<f64>
}
impl Color {
pub fn new(r:f64, g:f64, b:f64) -> Color {
return Color {
rgb: Vector3::new(r,g,b)
}
}
pub... | (self, _rhs: f64) -> Color {
Color {rgb: self.rgb * _rhs }
}
}
impl Add<Color> for Color {
type Output = Color;
fn add(self, _rhs: Color) -> Color {
Color {rgb: self.rgb + _rhs.rgb }
}
}
impl Add<Vector3<f64>> for Color {
type Output = Color;
fn add(self, _rhs: Vector3<f64>) ... | mul | identifier_name |
color.rs | use na::Vector3;
use std::fmt;
use std::ops::{Mul, Add, Div};
use std::cmp::Ordering;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Color {
pub rgb: Vector3<f64>
}
impl Color {
pub fn new(r:f64, g:f64, b:f64) -> Color {
return Color {
rgb: Vector3::new(r,g,b)
}
}
pub... | impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "#{:0>2x}{:0>2x}{:0>2x}", (self.rgb.x * 255f64) as u8, (self.rgb.y * 255f64) as u8, (self.rgb.z * 255f64) as u8)
}
}
impl Mul<Vector3<f64>> for Color {
type Output = Color;
fn mul(self, _rhs: Vector3... | );
}
}
| random_line_split |
guard.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 https://mozilla.org/MPL/2.0/. */
//! Machinery to conditionally expose things.
use js::jsapi::JSContext;
use js::rust::HandleObject;
use servo_co... |
}
}
/// A condition to expose things.
pub enum Condition {
/// The condition is satisfied if the function returns true.
Func(unsafe fn(*mut JSContext, HandleObject) -> bool),
/// The condition is satisfied if the preference is set.
Pref(&'static str),
/// The condition is always satisfied.
... | {
None
} | conditional_block |
guard.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 https://mozilla.org/MPL/2.0/. */
//! Machinery to conditionally expose things.
use js::jsapi::JSContext;
use js::rust::HandleObject;
use servo_co... | }
impl<T: Clone + Copy> Guard<T> {
/// Construct a new guarded value.
pub const fn new(condition: Condition, value: T) -> Self {
Guard {
condition: condition,
value: value,
}
}
/// Expose the value if the condition is satisfied.
///
/// The passed handle... | pub struct Guard<T: Clone + Copy> {
condition: Condition,
value: T, | random_line_split |
guard.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 https://mozilla.org/MPL/2.0/. */
//! Machinery to conditionally expose things.
use js::jsapi::JSContext;
use js::rust::HandleObject;
use servo_co... | <T: Clone + Copy> {
condition: Condition,
value: T,
}
impl<T: Clone + Copy> Guard<T> {
/// Construct a new guarded value.
pub const fn new(condition: Condition, value: T) -> Self {
Guard {
condition: condition,
value: value,
}
}
/// Expose the value if t... | Guard | identifier_name |
mod.rs | //! If an extern token is provided, then this pass validates that
//! terminal IDs have conversions. Otherwise, it generates a
//! tokenizer. This can only be done after macro expansion because
//! some macro arguments never make it into an actual production and
//! are only used in `if` conditions; we use string liter... |
}
}
Ok(())
}
fn validate_alternative(&mut self, alternative: &Alternative) -> NormResult<()> {
assert!(alternative.condition.is_none()); // macro expansion should have removed these
try!(self.validate_expr(&alternative.expr));
Ok(())
}
fn validate_e... | {
for alternative in &data.alternatives {
try!(self.validate_alternative(alternative));
}
} | conditional_block |
mod.rs | //! If an extern token is provided, then this pass validates that
//! terminal IDs have conversions. Otherwise, it generates a
//! tokenizer. This can only be done after macro expansion because
//! some macro arguments never make it into an actual production and
//! are only used in `if` conditions; we use string liter... |
fn validate_alternative(&mut self, alternative: &Alternative) -> NormResult<()> {
assert!(alternative.condition.is_none()); // macro expansion should have removed these
try!(self.validate_expr(&alternative.expr));
Ok(())
}
fn validate_expr(&mut self, expr: &ExprSymbol) -> NormResu... | {
for item in &self.grammar.items {
match *item {
GrammarItem::Use(..) => { }
GrammarItem::ExternToken(_) => { }
GrammarItem::InternToken(_) => { }
GrammarItem::Nonterminal(ref data) => {
for alternative in &data.alt... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.