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 |
|---|---|---|---|---|
html.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/. */
#![allow(unrooted_must_root)]
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateEleme... | ;
for handle in children {
(&*handle).serialize(serializer, IncludeNode)?;
}
if traversal_scope == IncludeNode {
serializer.end_elem(name.clone())?;
}
Ok(())
},
(ChildrenOnl... | {
node.children()
} | conditional_block |
html.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/. */
#![allow(unrooted_must_root)]
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateEleme... | tree_builder.trace_handles(&tracer);
tree_builder.sink.trace(trc);
}
}
impl<'a> Serialize for &'a Node {
fn serialize<S: Serializer>(&self, serializer: &mut S,
traversal_scope: TraversalScope) -> io::Result<()> {
let node = *self;
match (traversal... | unsafe { node.trace(self.0); }
}
}
let tree_builder = &self.sink; | random_line_split |
counters.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/. */
//! Generic types for counters-related CSS values.
#[cfg(feature = "servo")]
use crate::computed_values::list_st... | )]
pub enum Content<ImageUrl> {
/// `normal` reserved keyword.
Normal,
/// `none` reserved keyword.
None,
/// `-moz-alt-content`.
#[cfg(feature = "gecko")]
MozAltContent,
/// Content items.
Items(#[css(iterable)] Box<[ContentItem<ImageUrl>]>),
}
impl<ImageUrl> Content<ImageUrl> {
... | ToCss,
ToResolvedValue,
ToShmem, | random_line_split |
counters.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/. */
//! Generic types for counters-related CSS values.
#[cfg(feature = "servo")]
use crate::computed_values::list_st... | (&self) -> &Self::Target {
&(self.0).0
}
}
/// A generic value for the `counter-set` and `counter-reset` properties.
#[derive(
Clone,
Debug,
Default,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
pub struct CounterS... | deref | identifier_name |
derive-clone_1_0.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
/// Since builtin `Clone` impls were introduced in Rust 1.21 this struct
/// should impl `Clone` "manually".
#[repr(C)]
#[derive(Copy)]
pub struct ShouldImplClone {
pub large: [::std::os::raw::c_int; 33usize],
}
#[... |
}
impl Default for ShouldImplClone {
fn default() -> Self {
unsafe {
let mut s: Self = ::std::mem::uninitialized();
::std::ptr::write_bytes(&mut s, 0, 1);
s
}
}
}
| {
*self
} | identifier_body |
derive-clone_1_0.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
/// Since builtin `Clone` impls were introduced in Rust 1.21 this struct
/// should impl `Clone` "manually".
#[repr(C)]
#[derive(Copy)]
pub struct ShouldImplClone {
pub large: [::std::os::raw::c_int; 33usize],
}
#[... | );
assert_eq!(
unsafe {
&(*(::std::ptr::null::<ShouldImplClone>())).large as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(ShouldImplClone),
"::",
stringify!(large)
)
)... | assert_eq!(
::std::mem::align_of::<ShouldImplClone>(),
4usize,
concat!("Alignment of ", stringify!(ShouldImplClone)) | random_line_split |
derive-clone_1_0.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
/// Since builtin `Clone` impls were introduced in Rust 1.21 this struct
/// should impl `Clone` "manually".
#[repr(C)]
#[derive(Copy)]
pub struct ShouldImplClone {
pub large: [::std::os::raw::c_int; 33usize],
}
#[... | () -> Self {
unsafe {
let mut s: Self = ::std::mem::uninitialized();
::std::ptr::write_bytes(&mut s, 0, 1);
s
}
}
}
| default | identifier_name |
regions-fn-subtyping-2.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 wants_same_region(_f: Box<for<'b> FnMut(&'b isize, Box<FnMut(&'b isize)>)>) {
}
pub fn main() {
} | fn has_same_region(f: Box<for<'a> FnMut(&'a isize, Box<FnMut(&'a isize)>)>) {
// `f` should be the type that `wants_same_region` wants, but
// right now the compiler complains that it isn't.
wants_same_region(f);
} | random_line_split |
regions-fn-subtyping-2.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 ... | (f: Box<for<'a> FnMut(&'a isize, Box<FnMut(&'a isize)>)>) {
// `f` should be the type that `wants_same_region` wants, but
// right now the compiler complains that it isn't.
wants_same_region(f);
}
fn wants_same_region(_f: Box<for<'b> FnMut(&'b isize, Box<FnMut(&'b isize)>)>) {
}
pub fn main() {
}
| has_same_region | identifier_name |
regions-fn-subtyping-2.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 wants_same_region(_f: Box<for<'b> FnMut(&'b isize, Box<FnMut(&'b isize)>)>) {
}
pub fn main() {
}
| {
// `f` should be the type that `wants_same_region` wants, but
// right now the compiler complains that it isn't.
wants_same_region(f);
} | identifier_body |
ability.rs | use entity::Entity;
use spatial::Place;
use self::Ability::*;
/// Ability describes some way of affecting the game world. It is generally
/// attached to a mob or an item.
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub enum Ability {
Multi(Vec<Ability>),
/// Damage a target for a given amount.
... | (&self, agent: Option<Entity>, target: Place) {
if let &Multi(ref abls) = self {
for abl in abls.iter() {
abl.apply(agent, target);
}
return;
}
// Target entity.
let te = match target {
Place::In(e, _) => Some(e),
... | apply | identifier_name |
ability.rs | use entity::Entity;
use spatial::Place;
use self::Ability::*;
/// Ability describes some way of affecting the game world. It is generally
/// attached to a mob or an item.
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub enum Ability {
Multi(Vec<Ability>),
/// Damage a target for a given amount.
... | }
} | } | random_line_split |
ability.rs | use entity::Entity;
use spatial::Place;
use self::Ability::*;
/// Ability describes some way of affecting the game world. It is generally
/// attached to a mob or an item.
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub enum Ability {
Multi(Vec<Ability>),
/// Damage a target for a given amount.
... |
}
_ => ()
}
}
}
| {
e.heal(n);
if let Some(a) = agent { a.delete() }
} | conditional_block |
mod.rs | use std::hash::{Hash, Hasher};
use std::hash::sip::SipHasher;
static LOG_MAX_SIZE: uint = 21;
pub static MAX_SIZE: uint = 1 << LOG_MAX_SIZE;
pub fn hash<T: Hash>(s: &T, k1: u64, k2: u64) -> (uint, uint, uint) |
pub fn displace(f1: uint, f2: uint, d1: uint, d2: uint) -> uint {
d2 + f1 * d1 + f2
}
| {
let hash = SipHasher::new_with_keys(k1, k2).hash(s);
let mask = (MAX_SIZE - 1) as u64;
((hash & mask) as uint,
((hash >> LOG_MAX_SIZE) & mask) as uint,
((hash >> (2 * LOG_MAX_SIZE)) & mask) as uint)
} | identifier_body |
mod.rs | use std::hash::{Hash, Hasher};
use std::hash::sip::SipHasher;
static LOG_MAX_SIZE: uint = 21;
pub static MAX_SIZE: uint = 1 << LOG_MAX_SIZE;
pub fn | <T: Hash>(s: &T, k1: u64, k2: u64) -> (uint, uint, uint) {
let hash = SipHasher::new_with_keys(k1, k2).hash(s);
let mask = (MAX_SIZE - 1) as u64;
((hash & mask) as uint,
((hash >> LOG_MAX_SIZE) & mask) as uint,
((hash >> (2 * LOG_MAX_SIZE)) & mask) as uint)
}
pub fn displace(f1: uint, f2: uint, ... | hash | identifier_name |
mod.rs | use std::hash::{Hash, Hasher};
use std::hash::sip::SipHasher;
static LOG_MAX_SIZE: uint = 21;
pub static MAX_SIZE: uint = 1 << LOG_MAX_SIZE; | ((hash & mask) as uint,
((hash >> LOG_MAX_SIZE) & mask) as uint,
((hash >> (2 * LOG_MAX_SIZE)) & mask) as uint)
}
pub fn displace(f1: uint, f2: uint, d1: uint, d2: uint) -> uint {
d2 + f1 * d1 + f2
} |
pub fn hash<T: Hash>(s: &T, k1: u64, k2: u64) -> (uint, uint, uint) {
let hash = SipHasher::new_with_keys(k1, k2).hash(s);
let mask = (MAX_SIZE - 1) as u64;
| random_line_split |
searching.rs | use criterion::Criterion;
use criterion::{criterion_group, criterion_main};
use futures::stream::StreamExt;
use mimir::domain::model::configuration;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs::File;
use mimir::adapters::primary::bragi::api::DEFAULT_LIMIT_RESULT_ES;
use mimir::adapters::... | .await
.unwrap();
download::ntfs("fr-idf").await.unwrap();
// false: don't force regenerate admins for 'ile-de-france'
cosmogony::generate("ile-de-france", false).await.unwrap();
// true: force reindex admins on bench dataset for 'ile-de-france'
cosmogony::i... | {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(6)
.enable_time()
.enable_io()
.build()
.unwrap();
rt.block_on(async {
docker::initialize()
.await
.expect("elasticsearch docker initialization");
let config = ... | identifier_body |
searching.rs | use criterion::Criterion;
use criterion::{criterion_group, criterion_main};
use futures::stream::StreamExt;
use mimir::domain::model::configuration;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs::File;
use mimir::adapters::primary::bragi::api::DEFAULT_LIMIT_RESULT_ES;
use mimir::adapters::... | )
.await
.unwrap();
}
})
.await;
})
});
});
group.finish();
}
#[derive(Debug, Serialize, Deserialize)]
struct Record {
pub query: ... | DEFAULT_LIMIT_RESULT_ES,
None, | random_line_split |
searching.rs | use criterion::Criterion;
use criterion::{criterion_group, criterion_main};
use futures::stream::StreamExt;
use mimir::domain::model::configuration;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs::File;
use mimir::adapters::primary::bragi::api::DEFAULT_LIMIT_RESULT_ES;
use mimir::adapters::... | {
pub query: String,
pub lon: Option<String>,
pub lat: Option<String>,
pub limit: Option<String>,
pub expected_housenumber: Option<String>,
pub expected_street: Option<String>,
pub expected_city: Option<String>,
pub expected_postcode: Option<String>,
}
criterion_group! {
name = ben... | Record | identifier_name |
literals.rs | fn | () {
// 整数相加
println!("1 + 2 = {}", 1u32 + 2);
// 整数相减
println!("1 - 2 = {}", 1i32 - 2);
// 试一试 ^ 尝试将 `1i32` 改为 `1u32`,体会为什么类型声明这么重要
// 短路的布尔类型的逻辑运算
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT true is {}",!true);
... | main | identifier_name |
literals.rs | fn main() { | // 试一试 ^ 尝试将 `1i32` 改为 `1u32`,体会为什么类型声明这么重要
// 短路的布尔类型的逻辑运算
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT true is {}",!true);
// 位运算符
println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101);
println!("0011 OR 0101 is {:04... | // 整数相加
println!("1 + 2 = {}", 1u32 + 2);
// 整数相减
println!("1 - 2 = {}", 1i32 - 2); | random_line_split |
literals.rs | fn main() | // 使用下划线改善数字的可读性!
println!("One million is written as {}", 1_000_000u32);
}
| {
// 整数相加
println!("1 + 2 = {}", 1u32 + 2);
// 整数相减
println!("1 - 2 = {}", 1i32 - 2);
// 试一试 ^ 尝试将 `1i32` 改为 `1u32`,体会为什么类型声明这么重要
// 短路的布尔类型的逻辑运算
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT true is {}", !true);
... | identifier_body |
feature-gate-cfg-target-vendor.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (u64, u64);
#[cfg(not(any(all(target_vendor = "x"))))] //~ ERROR `cfg(target_vendor)` is experimental
fn foo() {}
fn main() {
cfg!(target_vendor = "x");
//~^ ERROR `cfg(target_vendor)` is experimental and subject to change
}
| Foo | identifier_name |
feature-gate-cfg-target-vendor.rs | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file... | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT | random_line_split | |
issue-19135.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <F: for<'a>FnMut(LifetimeStruct<'a>)>(mut f: F) {
f(LifetimeStruct(PhantomData));
}
| takes_hrtb_closure | identifier_name |
issue-19135.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | f(LifetimeStruct(PhantomData));
} | }
fn takes_hrtb_closure<F: for<'a>FnMut(LifetimeStruct<'a>)>(mut f: F) { | random_line_split |
issue-19135.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
f(LifetimeStruct(PhantomData));
} | identifier_body | |
node.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/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency between layout and
//! style.
use le... | use smallvec::VecLike;
use selectors::matching::DeclarationBlock;
pub use selectors::tree::{TNode, TElement};
use string_cache::{Atom, Namespace};
pub trait TElementAttributes {
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, &mut V)
where V: VecLike<DeclarationBlock<Vec<PropertyDeclara... | use properties::PropertyDeclaration; | random_line_split |
unifont.rs | use std::fs::File;
use std::io::{BufRead, BufReader, Read, Write};
fn main() {
let mut input = File::open("unifont.hex").unwrap();
let mut output = File::create("unifont.font").unwrap();
let mut count = 0;
for line_res in BufReader::new(input).lines() {
let line = line_res.unwrap();
let mut ... | count += 1;
}
} |
output.write(&data).unwrap();
| random_line_split |
unifont.rs | use std::fs::File;
use std::io::{BufRead, BufReader, Read, Write};
fn | () {
let mut input = File::open("unifont.hex").unwrap();
let mut output = File::create("unifont.font").unwrap();
let mut count = 0;
for line_res in BufReader::new(input).lines() {
let line = line_res.unwrap();
let mut parts = line.split(":");
let num = u32::from_str_radix(parts.next().... | main | identifier_name |
unifont.rs | use std::fs::File;
use std::io::{BufRead, BufReader, Read, Write};
fn main() | count += 1;
}
}
| {
let mut input = File::open("unifont.hex").unwrap();
let mut output = File::create("unifont.font").unwrap();
let mut count = 0;
for line_res in BufReader::new(input).lines() {
let line = line_res.unwrap();
let mut parts = line.split(":");
let num = u32::from_str_radix(parts.next().unw... | identifier_body |
closest-pair.rs | // Implements http://rosettacode.org/wiki/Closest-pair_problem
// We interpret complex numbers as points in the Cartesian plane, here.
// We also use the sweepline/plane sweep closest pairs algorithm
// (http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html) instead
// of the divide-and-conquer algorithm, sinc... | {
point: Point
}
impl PartialOrd for YSortedPoint {
fn partial_cmp(&self, other: &YSortedPoint) -> Option<Ordering> {
(self.point.im, self.point.re).partial_cmp(&(other.point.im, other.point.re))
}
}
impl Ord for YSortedPoint {
fn cmp(&self, other: &YSortedPoint) -> Ordering {
self.pa... | YSortedPoint | identifier_name |
closest-pair.rs | // Implements http://rosettacode.org/wiki/Closest-pair_problem
// We interpret complex numbers as points in the Cartesian plane, here.
// We also use the sweepline/plane sweep closest pairs algorithm
// (http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html) instead
// of the divide-and-conquer algorithm, sinc... | closest_distance_sqr = dist_sqr;
closest_distance = dist_sqr.sqrt();
}
}
}
// Insert point into strip
strip.insert(YSortedPoint { point: point.clone() });
}
Some(closest_pair)
}
#[cfg(not(test))]
pub fn main() {
l... | closest_pair = (point2, *point); | random_line_split |
box-of-array-of-drop-2.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we ... | random_line_split | |
box-of-array-of-drop-2.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> D { panic!("Oh no"); }
let g = thread::spawn(|| {
let _b1: Box<[D; 4]> = Box::new([D( 1), D( 2), D( 3), D( 4)]);
let _b2: Box<[D; 4]> = Box::new([D( 5), D( 6), D( 7), D( 8)]);
let _b3: Box<[D; 4]> = Box::new([D( 9), D(10), die(), D(12)]);
let _b4: Box<[D; 4]> = Box::new([D(13),... | die | identifier_name |
box-of-array-of-drop-2.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
let g = thread::spawn(|| {
let _b1: Box<[D; 4]> = Box::new([D( 1), D( 2), D( 3), D( 4)]);
let _b2: Box<[D; 4]> = Box::new([D( 5), D( 6), D( 7), D( 8)]);
let _b3: Box<[D; 4]> = Box::new([D( 9), D(10), die(), D(12)]);
let _b4: Box<[D; 4]> = Box::new([D(13), D(14), D(15), D(16)]);
... | { panic!("Oh no"); } | identifier_body |
lib.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... |
/// Construct a TimeSpan that started at `start` and ends at `end`.
pub fn from_start_and_end_systemtime(
start: &std::time::SystemTime,
end: &std::time::SystemTime,
) -> TimeSpan {
let start = Self::since_epoch(start);
let end = Self::since_epoch(end);
let duration = match end.checked_sub(s... | {
let start = Self::since_epoch(start);
let duration = Self::since_epoch(&std::time::SystemTime::now()) - start;
TimeSpan {
start: start.into(),
duration: duration.into(),
}
} | identifier_body |
lib.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | {
/// Duration since the UNIX_EPOCH
pub start: Duration,
/// Duration since `start`
pub duration: Duration,
}
impl TimeSpan {
fn since_epoch(time: &std::time::SystemTime) -> std::time::Duration {
time
.duration_since(std::time::UNIX_EPOCH)
.expect("Surely you're not before the unix epoch?")
... | TimeSpan | identifier_name |
lib.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | }
}
/// A timespan
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
pub struct TimeSpan {
/// Duration since the UNIX_EPOCH
pub start: Duration,
/// Duration since `start`
pub duration: Duration,
}
impl TimeSpan {
fn since_epoch(time: &std::time::SystemTime) -> std::time::Duration {
time
... |
impl From<Duration> for std::time::Duration {
fn from(duration: Duration) -> std::time::Duration {
std::time::Duration::new(duration.secs, duration.nanos) | random_line_split |
eio.rs | // Eio Rust bindings for EFL.
// Copyright (C) 2014 Luis Araujo <araujoc.luisf@gmail.com>
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at... | () -> int {
unsafe { eio_shutdown() as int }
}
/// List contents of a directory without locking your app.
pub fn file_ls<T>(dir: &str, filter_cb: EioFilterCb<T>,
main_cb: EioMainCb<T>, done_cb: EioDoneCb<T>,
error_cb: EioErrorCb<T>, data: &T) -> Box<EioFile> {
dir.with_c_str... | shutdown | identifier_name |
eio.rs | // Eio Rust bindings for EFL.
// Copyright (C) 2014 Luis Araujo <araujoc.luisf@gmail.com>
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at... | type _CEioProgressCb = fn (*c_void, *EioFile, *EioProgress);
#[link(name = "eio")]
extern "C" {
fn eio_init() -> c_int;
fn eio_shutdown() -> c_int;
fn eio_file_ls(dir: *c_char, filter_cb: _CEioFilterCb,
main_cb: _CEioMainCb, done_cb: _CEioDoneCb,
error_cb: _CEioErrorCb... | pub type EioErrorCb<T> = fn (&mut T, &EioFile, int);
type _CEioErrorCb = fn (*c_void, *EioFile, c_int);
pub type EioProgressCb<T> = fn (&mut T, &EioFile, &EioProgress); | random_line_split |
3_10_exercise_oop_wave.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Exercise 3-10: OOP Wave
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
wave0: Wave,
wave1: Wave,
}
struct Wave {
x_spacing: f32, // How far apart should each horizontal positio... | y_values,
}
}
fn calculate(&mut self) {
// Increment theta (try different values for 'angular velocity' here
self.theta += 0.02;
// For every x values, calculate a y value with sine function
let mut x = self.theta;
for i in 0..self.y_values.len() {
... | dx, | random_line_split |
3_10_exercise_oop_wave.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Exercise 3-10: OOP Wave
use nannou::prelude::*;
fn | () {
nannou::app(model).update(update).run();
}
struct Model {
wave0: Wave,
wave1: Wave,
}
struct Wave {
x_spacing: f32, // How far apart should each horizontal position be spaced
_w: f32, // Width of entire wave
origin: Point2, // Where does the wave's first point start
... | main | identifier_name |
subscription.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 crypto::CryptoContext;
use error::{WebPushError, WebPushResult};
use hyper::header::{ContentEncoding, Encoding, A... | {
push_uri: String,
public_key: String,
auth: Option<String>
}
impl Subscription {
pub fn new(push_uri: &str, public_key: &str, auth: &str) -> Self {
Subscription {
push_uri: push_uri.to_owned(),
public_key: public_key.to_owned(),
auth: Some(auth.to_owned())... | Subscription | identifier_name |
subscription.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 crypto::CryptoContext;
use error::{WebPushError, WebPushResult};
use hyper::header::{ContentEncoding, Encoding, A... |
}
pub struct Subscription {
push_uri: String,
public_key: String,
auth: Option<String>
}
impl Subscription {
pub fn new(push_uri: &str, public_key: &str, auth: &str) -> Self {
Subscription {
push_uri: push_uri.to_owned(),
public_key: public_key.to_owned(),
... | {
sub.post(&self.crypto, &self.gcm_api_key, message)
} | identifier_body |
subscription.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 crypto::CryptoContext;
use error::{WebPushError, WebPushResult};
use hyper::header::{ContentEncoding, Encoding, A... | ;
// TODO: Add a retry mechanism if 429 Too Many Requests returned by push service
Ok(try!(req.send()))
}
}
| {
req.header(ContentEncoding(vec![Encoding::EncodingExt(String::from("aesgcm128"))]))
.header(EncryptionKey(format!("keyid=p256dh;dh={}", public_key)))
} | conditional_block |
subscription.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 crypto::CryptoContext;
use error::{WebPushError, WebPushResult};
use hyper::header::{ContentEncoding, Encoding, A... | use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use std::cmp::max;
// Place these headers inside a sub module to prevent them from getting
// exported by the crate, as the macro declares them pub.
mod hidden {
header! { (CryptoKey, "Crypto-Key") => [String] }
header! { (Encryption, "Encr... | use hyper::client::response::Response; | random_line_split |
scrolling.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/. */
//! A timer thread that gives the painting task a little time to catch up when the user scrolls.
use compositor_t... | impl ScrollingTimer {
pub fn run(&mut self) {
while let Ok(ToScrollingTimerMsg::ScrollEventProcessedMsg(timestamp)) = self.receiver.recv() {
let target = timestamp + TIMEOUT;
let delta_ns = target - time::precise_time_ns();
thread::sleep(duration_from_nanoseconds(delta_ns... | pub fn shutdown(&mut self) {
self.sender.send(ToScrollingTimerMsg::ExitMsg).unwrap()
}
}
| random_line_split |
scrolling.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/. */
//! A timer thread that gives the painting task a little time to catch up when the user scrolls.
use compositor_t... | (&mut self, timestamp: u64) {
self.sender.send(ToScrollingTimerMsg::ScrollEventProcessedMsg(timestamp)).unwrap()
}
pub fn shutdown(&mut self) {
self.sender.send(ToScrollingTimerMsg::ExitMsg).unwrap()
}
}
impl ScrollingTimer {
pub fn run(&mut self) {
while let Ok(ToScrollingTime... | scroll_event_processed | identifier_name |
stack_depth_checker.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// 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... |
}?;
}
Ok(())
}
pub struct StackDepthChecker;
impl BuildASTPass for StackDepthChecker {
fn run_pass(contract_ast: &mut ContractAST) -> ParseResult<()> {
check(&contract_ast.pre_expressions, 0)
}
}
| {
// Other symbolic expressions don't have depth
// impacts.
Ok(())
} | conditional_block |
stack_depth_checker.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// 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... | ;
impl BuildASTPass for StackDepthChecker {
fn run_pass(contract_ast: &mut ContractAST) -> ParseResult<()> {
check(&contract_ast.pre_expressions, 0)
}
}
| StackDepthChecker | identifier_name |
stack_depth_checker.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// 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... |
pub struct StackDepthChecker;
impl BuildASTPass for StackDepthChecker {
fn run_pass(contract_ast: &mut ContractAST) -> ParseResult<()> {
check(&contract_ast.pre_expressions, 0)
}
}
| {
if depth >= (AST_CALL_STACK_DEPTH_BUFFER + MAX_CALL_STACK_DEPTH as u64) {
return Err(ParseErrors::ExpressionStackDepthTooDeep.into());
}
for expression in args.iter() {
match expression.pre_expr {
List(ref exprs) => check(exprs, depth + 1),
_ => {
//... | identifier_body |
stack_depth_checker.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify | // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Gene... | // it under the terms of the GNU General Public License as published by | random_line_split |
table_rowgroup.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMargi... |
}
if let Some(collapsed_block_direction_border_width_for_table) =
collapsed_block_direction_border_widths_for_table.peek() {
self.collapsed_block_direction_border_widths_for_table
.push(**collapsed_block_direction_border_width_for_table)
}
}
}
imp... | {
self.collapsed_block_direction_border_widths_for_table
.push(*collapsed_block_direction_border_width_for_table)
} | conditional_block |
table_rowgroup.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMargi... |
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_th... | {
self.block_flow.generated_containing_block_size(flow)
} | identifier_body |
table_rowgroup.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMargi... | (&self, print_tree: &mut PrintTree) {
self.block_flow.print_extra_flow_children(print_tree);
}
}
impl fmt::Debug for TableRowGroupFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableRowGroupFlow: {:?}", self.block_flow)
}
}
| print_extra_flow_children | identifier_name |
table_rowgroup.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMargi... | let inline_size_computer = InternalTable;
inline_size_computer.compute_used_inline_size(&mut self.block_flow,
shared_context,
containing_block_inline_size);
let collapsed_inline_direction... | random_line_split | |
x86_64_unknown_hermit.rs | // Copyright 2016 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 ... | () -> TargetResult {
let mut base = super::hermit_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.linker = Some("x86_64-hermit-gcc".to_string());
base.max_atomic_width = Some(64);
Ok(Target {
llvm_targ... | target | identifier_name |
x86_64_unknown_hermit.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
| {
let mut base = super::hermit_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.linker = Some("x86_64-hermit-gcc".to_string());
base.max_atomic_width = Some(64);
Ok(Target {
llvm_target: "x86_64-unknown... | identifier_body |
x86_64_unknown_hermit.rs | // Copyright 2016 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 ... | target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
} | target_env: String::new(), | random_line_split |
utils.rs | use byteorder::{ByteOrder, WriteBytesExt, LE};
use nom::le_i32;
use nom::IResult;
use std::str;
use super::{BestTimes, ElmaError, Time, TimeEntry};
/// Parse top10 lists and return a vector of `TimeEntry`s
pub fn parse_top10(top10: &[u8]) -> Result<Vec<TimeEntry>, ElmaError> {
let mut list: Vec<TimeEntry> = vec![... |
let mut bytes = name.to_vec();
bytes.resize(pad, 0);
Ok(bytes)
}
#[cfg_attr(rustfmt, rustfmt_skip)]
named!(_boolean<bool>,
map!(le_i32, to_bool)
);
#[cfg_attr(rustfmt, rustfmt_skip)]
named_args!(_null_padded_string(n: usize)<&str>,
do_parse!(
s: map_res!(take_while!(is_nonzero), str::from_utf8) ... | {
return Err(ElmaError::PaddingTooShort(
(pad as isize - name.len() as isize) as isize,
));
} | conditional_block |
utils.rs | use byteorder::{ByteOrder, WriteBytesExt, LE};
use nom::le_i32;
use nom::IResult;
use std::str;
use super::{BestTimes, ElmaError, Time, TimeEntry};
/// Parse top10 lists and return a vector of `TimeEntry`s
pub fn parse_top10(top10: &[u8]) -> Result<Vec<TimeEntry>, ElmaError> {
let mut list: Vec<TimeEntry> = vec![... |
pub(crate) fn is_nonzero(u: u8) -> bool {
to_bool(i32::from(u))
}
#[cfg(test)]
mod tests {
use super::null_padded_string;
use nom::verbose_errors::Context::Code;
use nom::Err::Error;
use nom::Err::Incomplete;
use nom::ErrorKind::CondReduce;
use nom::Needed::Size;
#[test]
fn null_p... | {
i != 0
} | identifier_body |
utils.rs | use byteorder::{ByteOrder, WriteBytesExt, LE};
use nom::le_i32;
use nom::IResult;
use std::str;
use super::{BestTimes, ElmaError, Time, TimeEntry};
/// Parse top10 lists and return a vector of `TimeEntry`s
pub fn parse_top10(top10: &[u8]) -> Result<Vec<TimeEntry>, ElmaError> {
let mut list: Vec<TimeEntry> = vec![... | (u: u8) -> bool {
to_bool(i32::from(u))
}
#[cfg(test)]
mod tests {
use super::null_padded_string;
use nom::verbose_errors::Context::Code;
use nom::Err::Error;
use nom::Err::Incomplete;
use nom::ErrorKind::CondReduce;
use nom::Needed::Size;
#[test]
fn null_pad_string() {
asse... | is_nonzero | identifier_name |
utils.rs | use byteorder::{ByteOrder, WriteBytesExt, LE};
use nom::le_i32;
use nom::IResult;
use std::str;
use super::{BestTimes, ElmaError, Time, TimeEntry};
/// Parse top10 lists and return a vector of `TimeEntry`s
pub fn parse_top10(top10: &[u8]) -> Result<Vec<TimeEntry>, ElmaError> {
let mut list: Vec<TimeEntry> = vec![... | let mut names_1 = vec![];
let mut names_2 = vec![];
for (n, entry) in best_times.single.iter().enumerate() {
if n < 10 {
times[n] = entry.time.into();
names_1.extend_from_slice(&string_null_pad(&entry.names.0, 15)?);
names_2.extend_from_slice(&string_null_pad(&ent... |
// Single-player times.
let single_times = best_times.single.len();
top10_bytes.write_i32::<LE>(if 10 < single_times { 10 } else { single_times } as i32)?;
let mut times = [0_i32; 10]; | random_line_split |
update_repo_file.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
api_utils::{create_command, get_hosts, wait_for_cmds_success, SendCmd, SendJob},
display_utils::{display_cancelled, display_error, wrap_fut},
... |
}
if xs.is_empty() {
display_error("0 hosts can be updated. Exiting");
return Ok(());
}
let cmd = SendCmd {
jobs: xs
.iter()
.map(|x| SendJob {
class_name: "UpdateYumFileJob".into(),
args: HostId { host_id: x.id },
... | {
display_cancelled(format!("Unknown host: {}", x));
} | conditional_block |
update_repo_file.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
api_utils::{create_command, get_hosts, wait_for_cmds_success, SendCmd, SendJob},
display_utils::{display_cancelled, display_error, wrap_fut},
... |
#[derive(serde::Serialize)]
pub struct HostId {
host_id: i32,
}
pub async fn update_repo_file_cli(config: UpdateRepoFileHosts) -> Result<(), ImlManagerCliError> {
let r = parse_hosts(&config.hosts)?;
tracing::debug!("Parsed hosts {:?}", r);
let api_hosts = wrap_fut("Fetching hosts...", get_hosts())... | {
api_hosts
.iter()
.any(|y| y.fqdn == host || y.nodename == host)
} | identifier_body |
update_repo_file.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
api_utils::{create_command, get_hosts, wait_for_cmds_success, SendCmd, SendJob},
display_utils::{display_cancelled, display_error, wrap_fut},
... | <'a, 'b>(
hostlist: &'b BTreeSet<String>,
api_hosts: &'a [Host],
) -> Vec<&'a Host> {
api_hosts
.iter()
.filter(move |x| hostlist.contains(&x.fqdn) || hostlist.contains(&x.nodename))
.collect()
}
fn has_host(api_hosts: &[&Host], host: &str) -> bool {
api_hosts
.iter()
... | filter_known_hosts | identifier_name |
update_repo_file.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
api_utils::{create_command, get_hosts, wait_for_cmds_success, SendCmd, SendJob},
display_utils::{display_cancelled, display_error, wrap_fut},
... |
for x in r.iter() {
if!has_host(&xs, &x) {
display_cancelled(format!("Unknown host: {}", x));
}
}
if xs.is_empty() {
display_error("0 hosts can be updated. Exiting");
return Ok(());
}
let cmd = SendCmd {
jobs: xs
.iter()
.... | let xs = filter_known_hosts(&r, &api_hosts.objects); | random_line_split |
program.rs | //! A `Program` holds multiple `Function`.
use crate::il::*;
use crate::RC;
use std::collections::BTreeMap;
use std::fmt;
/// A representation of a program by `il::Function`
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
pub struct Program {
// Mapping of function indices (not addresses) to `Function`.
... |
}
None
}
/// Get all `Function` for this `Program`.
pub fn functions(&self) -> Vec<&Function> {
let mut v = Vec::new();
for f in &self.functions {
let f: &Function = &f.1;
v.push(f);
}
v
}
/// Get the underlying BTreeMap hold... | {
return Some(function.1);
} | conditional_block |
program.rs | //! A `Program` holds multiple `Function`.
use crate::il::*;
use crate::RC;
use std::collections::BTreeMap;
use std::fmt;
/// A representation of a program by `il::Function`
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
pub struct Program {
// Mapping of function indices (not addresses) to `Function`.
... |
}
impl fmt::Display for Program {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for function in &self.functions {
writeln!(f, "{}@{:08X}", function.1.name(), function.0)?
}
Ok(())
}
}
| {
self.functions
.iter()
.find(|(_, function)| function.name() == name)
.map(|(_, function)| function.as_ref())
} | identifier_body |
program.rs | //! A `Program` holds multiple `Function`.
use crate::il::*;
use crate::RC;
use std::collections::BTreeMap;
use std::fmt;
/// A representation of a program by `il::Function`
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
pub struct Program {
// Mapping of function indices (not addresses) to `Function`.
... | pub fn add_function(&mut self, mut function: Function) {
function.set_index(Some(self.next_index));
self.functions.insert(self.next_index, RC::new(function));
self.next_index += 1;
}
/// Get a `Function` by its name.
pub fn function_by_name(&self, name: &str) -> Option<&Function... | /// Add a `Function` to the `Program`.
///
/// This will also assign an index to the `Function`. | random_line_split |
program.rs | //! A `Program` holds multiple `Function`.
use crate::il::*;
use crate::RC;
use std::collections::BTreeMap;
use std::fmt;
/// A representation of a program by `il::Function`
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
pub struct Program {
// Mapping of function indices (not addresses) to `Function`.
... | (&self) -> BTreeMap<usize, &Function> {
self.functions
.iter()
.map(|(index, function)| (*index, function.as_ref()))
.collect::<BTreeMap<usize, &Function>>()
}
/// Get a `Function` by its index.
///
/// A `Function` index is assigned by `Program` and is not the ... | functions_map | identifier_name |
encryption.rs | mod builder_key;
mod message;
mod origin_key;
mod service_key;
mod user_key;
pub use builder_key::{generate_builder_encryption_key,
BuilderSecretEncryptionKey,
BUILDER_KEY_NAME};
pub use message::{AnonymousBox, | OriginPublicEncryptionKey,
OriginSecretEncryptionKey};
pub use service_key::{generate_service_encryption_key_pair,
ServicePublicEncryptionKey,
ServiceSecretEncryptionKey};
pub use user_key::{generate_user_encryption_key_pair,
... | SignedBox};
pub use origin_key::{generate_origin_encryption_key_pair, | random_line_split |
size_of.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 script::test::size_of;
// Macro so that we can stringify type names
// I'd really prefer the tests themselve... | let new = size_of::$t();
let old = $known_size;
if new < old {
panic!("Your changes have decreased the stack size of commonly used DOM struct {} from {} to {}. \
Good work! Please update the size in tests/unit/script/size_of.rs.",
... | ($testname: ident, $t: ident, $known_size: expr) => (
#[test]
fn $testname() { | random_line_split |
issue-17121.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
pub fn new_from_file(p: Path) -> IoResult<Lexer<File>>
{
Ok(Lexer::new_from_reader(try!(File::open(&p))))
}
pub fn new_from_str<'a>(s: &'a str) -> Lexer<BufReader<'a>>
{
Lexer::new_from_reader(BufReader::new(s.as_bytes()))
}
}
fn main() {} | {
Lexer{reader: BufferedReader::new(r)} | random_line_split |
issue-17121.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn new_from_str<'a>(s: &'a str) -> Lexer<BufReader<'a>>
{
Lexer::new_from_reader(BufReader::new(s.as_bytes()))
}
}
fn main() {}
| {
Ok(Lexer::new_from_reader(try!(File::open(&p))))
} | identifier_body |
issue-17121.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (r: R) -> Lexer<R>
{
Lexer{reader: BufferedReader::new(r)}
}
pub fn new_from_file(p: Path) -> IoResult<Lexer<File>>
{
Ok(Lexer::new_from_reader(try!(File::open(&p))))
}
pub fn new_from_str<'a>(s: &'a str) -> Lexer<BufReader<'a>>
{
Lexer::new_from_reader(BufReader::n... | new_from_reader | identifier_name |
day22.rs | extern crate dotenv;
extern crate lettre;
extern crate uuid;
use std::env;
use lettre::email::{EmailBuilder, SendableEmail};
use lettre::transport::EmailTransport;
use lettre::transport::smtp;
struct | {
contents: String,
recipient: String,
}
impl SendableEmail for Report {
fn from_address(&self) -> String {
"complicated.report.system@gmail.com".to_string()
}
fn to_addresses(&self) -> Vec<String> {
vec![self.recipient.clone()]
}
fn message(&self) -> String {
for... | Report | identifier_name |
day22.rs | extern crate dotenv;
extern crate lettre;
extern crate uuid;
use std::env;
use lettre::email::{EmailBuilder, SendableEmail};
use lettre::transport::EmailTransport;
use lettre::transport::smtp;
| contents: String,
recipient: String,
}
impl SendableEmail for Report {
fn from_address(&self) -> String {
"complicated.report.system@gmail.com".to_string()
}
fn to_addresses(&self) -> Vec<String> {
vec![self.recipient.clone()]
}
fn message(&self) -> String {
format... | struct Report { | random_line_split |
mergesort.rs | // Author : Thomas Minier
// Apply Merge sort on two slices
fn merge(left : &[i32], right : &[i32]) -> Vec<i32> {
let mut res = vec!();
let (mut left_set, mut right_set) = (left, right);
while (!left_set.is_empty()) && (!right_set.is_empty()) {
let (left_head, left_tail) = left_set.split_first().un... | (list : &[i32]) -> Vec<i32> {
if list.len() <= 1 {
return list.to_vec();
}
let (left, right) = list.split_at(list.len() / 2);
return merge(&merge_sort(left), &merge_sort(right));
}
#[test]
fn test_merge_sort() {
let v = vec!(5,1,4,3,2,6);
let w = merge_sort(&v);
assert_eq!(vec!(1,2,... | merge_sort | identifier_name |
mergesort.rs | // Author : Thomas Minier
// Apply Merge sort on two slices
fn merge(left : &[i32], right : &[i32]) -> Vec<i32> {
let mut res = vec!();
let (mut left_set, mut right_set) = (left, right);
while (!left_set.is_empty()) && (!right_set.is_empty()) {
let (left_head, left_tail) = left_set.split_first().un... |
let (left, right) = list.split_at(list.len() / 2);
return merge(&merge_sort(left), &merge_sort(right));
}
#[test]
fn test_merge_sort() {
let v = vec!(5,1,4,3,2,6);
let w = merge_sort(&v);
assert_eq!(vec!(1,2,3,4,5,6), w);
}
| {
return list.to_vec();
} | conditional_block |
mergesort.rs | // Author : Thomas Minier
// Apply Merge sort on two slices
fn merge(left : &[i32], right : &[i32]) -> Vec<i32> {
let mut res = vec!();
let (mut left_set, mut right_set) = (left, right);
while (!left_set.is_empty()) && (!right_set.is_empty()) {
let (left_head, left_tail) = left_set.split_first().un... |
#[test]
fn test_merge_sort() {
let v = vec!(5,1,4,3,2,6);
let w = merge_sort(&v);
assert_eq!(vec!(1,2,3,4,5,6), w);
}
| {
if list.len() <= 1 {
return list.to_vec();
}
let (left, right) = list.split_at(list.len() / 2);
return merge(&merge_sort(left), &merge_sort(right));
} | identifier_body |
mergesort.rs | // Author : Thomas Minier
// Apply Merge sort on two slices
fn merge(left : &[i32], right : &[i32]) -> Vec<i32> {
let mut res = vec!();
let (mut left_set, mut right_set) = (left, right);
while (!left_set.is_empty()) && (!right_set.is_empty()) {
let (left_head, left_tail) = left_set.split_first().un... | // drain collections
for x in left_set {
res.push(*x);
}
for x in right_set {
res.push(*x);
}
res
}
// Sort a slice using the Merge Sort algorithm
pub fn merge_sort(list : &[i32]) -> Vec<i32> {
if list.len() <= 1 {
return list.to_vec();
}
let (left, right) = ... | } else {
res.push(*right_head);
right_set = right_tail;
}
} | random_line_split |
ptr_offset.rs | extern crate crucible;
use std::ptr;
use crucible::*;
use crucible::method_spec::{MethodSpec, MethodSpecBuilder, clobber_globals};
fn f(ptr: *mut u8) {
unsafe { ptr::swap(ptr, ptr.add(1)) };
}
#[crux_test]
fn f_test() {
clobber_globals();
let mut x = <[u8; 2]>::symbolic("x");
crucible_assume!(x[0] > 0... | } | random_line_split | |
ptr_offset.rs | extern crate crucible;
use std::ptr;
use crucible::*;
use crucible::method_spec::{MethodSpec, MethodSpecBuilder, clobber_globals};
fn f(ptr: *mut u8) {
unsafe { ptr::swap(ptr, ptr.add(1)) };
}
#[crux_test]
fn f_test() |
fn f_spec() -> MethodSpec {
let mut x = <[u8; 2]>::symbolic("x");
crucible_assume!(x[0] > 0);
crucible_assume!(x[1] == 0);
let mut msb = MethodSpecBuilder::new(f);
msb.add_arg(& &mut x[0]);
msb.gather_assumes();
// Call happens here
crucible_assert!(x[1] > 0);
msb.set_return(&()... | {
clobber_globals();
let mut x = <[u8; 2]>::symbolic("x");
crucible_assume!(x[0] > 0);
f(&mut x[0]);
crucible_assert!(x[1] > 0);
} | identifier_body |
ptr_offset.rs | extern crate crucible;
use std::ptr;
use crucible::*;
use crucible::method_spec::{MethodSpec, MethodSpecBuilder, clobber_globals};
fn f(ptr: *mut u8) {
unsafe { ptr::swap(ptr, ptr.add(1)) };
}
#[crux_test]
fn f_test() {
clobber_globals();
let mut x = <[u8; 2]>::symbolic("x");
crucible_assume!(x[0] > 0... | () {
f_spec().enable();
let a = u8::symbolic("a");
let b = u8::symbolic("b");
let x = u8::symbolic("x");
let y = u8::symbolic("y");
crucible_assume!(0 < a && a < 10);
crucible_assume!(b == 0);
let mut arr = [x, a, b, y];
f(&mut arr[1]);
let [x2, a2, b2, y2] = arr;
crucible_a... | use_f | identifier_name |
htmllinkelement.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 cssparser::Parser as CssParser;
use document_loader::LoadType;
use dom::attr::{Attr, AttrValue};
use dom::bind... | }
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
fn bind_to_tree(&self, tree_... | } | random_line_split |
htmllinkelement.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 cssparser::Parser as CssParser;
use document_loader::LoadType;
use dom::attr::{Attr, AttrValue};
use dom::bind... | win.css_error_reporter(),
ParserContextExtraData::default());
let media = self.media.take().unwrap();
sheet.set_media(Some(media));
let sheet = Arc::new(sheet);
let elem = elem.r();
let... | {
if status.is_err() {
self.elem.root().upcast::<EventTarget>().fire_simple_event("error");
return;
}
let data = mem::replace(&mut self.data, vec!());
let metadata = match self.metadata.take() {
Some(meta) => meta,
None => return,
}... | identifier_body |
htmllinkelement.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 cssparser::Parser as CssParser;
use document_loader::LoadType;
use dom::attr::{Attr, AttrValue};
use dom::bind... | (&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if!self.upcast::<Node>().is_in_doc() || mutation == Attribut... | super_type | identifier_name |
shadow.rs | // -*- rust -*-
// 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
// ... |
}
_ => { }
}
}
enum t<T> { none, some(T), }
pub fn main() { let x = 10; let x = x + 20; assert!((x == 30)); foo(~[]); }
| {
for c.each |i| {
debug!(a);
let a = 17;
b += ~[a];
} | conditional_block |
shadow.rs | // -*- rust -*-
// 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
// ... | match none::<int> {
some::<int>(_) => {
for c.each |i| {
debug!(a);
let a = 17;
b += ~[a];
}
}
_ => { }
}
}
enum t<T> { none, some(T), }
pub fn main() { let x = 10; let x = x + 20; assert!((x == 30)); foo(~[]); } | let mut b: ~[int] = ~[];
| random_line_split |
shadow.rs | // -*- rust -*-
// 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
// ... |
}
enum t<T> { none, some(T), }
pub fn main() { let x = 10; let x = x + 20; assert!((x == 30)); foo(~[]); }
| {
let a: int = 5;
let mut b: ~[int] = ~[];
match none::<int> {
some::<int>(_) => {
for c.each |i| {
debug!(a);
let a = 17;
b += ~[a];
}
}
_ => { }
} | identifier_body |
shadow.rs | // -*- rust -*-
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// ... | () { let x = 10; let x = x + 20; assert!((x == 30)); foo(~[]); }
| main | identifier_name |
camera.rs | extern crate cgmath;
use {Mat4, Vec3, Vec4};
use cgmath::*;
use geometry;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Camera {
pub at: Vec3,
pub pitch: Rad<f64>,
pub viewport: (u32, u32),
pub pixels_per_unit: f64,
}
impl Camera {
pub fn view(&self) -> Mat4 {
view(self.pitch, self.... | else {
None
}
}
| {
let n_x = (x as f64) / (width as f64) * 2.0 - 1.0;
let n_y = ((y as f64) / (height as f64) * 2.0 - 1.0) * -1.0;
let front = Vec4::new(n_x, n_y, -1.0, 1.0);
let back = Vec4::new(n_x, n_y, 1.0, 1.0);
let front_world = inverse_view_projection * front;
let back_world = in... | conditional_block |
camera.rs | extern crate cgmath;
use {Mat4, Vec3, Vec4};
use cgmath::*;
use geometry;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Camera {
pub at: Vec3,
pub pitch: Rad<f64>,
pub viewport: (u32, u32),
pub pixels_per_unit: f64,
}
impl Camera {
pub fn view(&self) -> Mat4 {
view(self.pitch, self.... |
pub fn view(pitch: Rad<f64>, at: Vec3) -> Mat4 {
Mat4::from_angle_x(pitch) * Mat4::from_translation(at * -1.0)
}
pub fn projection(width:u32, height:u32, pixels_per_unit: f64) -> Mat4 {
let effective_width = (width as f64) / (pixels_per_unit);
let effective_height = (height as f64) / (pixels_per_unit) / (... | random_line_split | |
camera.rs | extern crate cgmath;
use {Mat4, Vec3, Vec4};
use cgmath::*;
use geometry;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Camera {
pub at: Vec3,
pub pitch: Rad<f64>,
pub viewport: (u32, u32),
pub pixels_per_unit: f64,
}
impl Camera {
pub fn view(&self) -> Mat4 {
view(self.pitch, self.... | (&self) -> f64 {
1.0 / self.pixels_per_unit
}
pub fn view_projection(&self) -> Mat4 {
self.projection() * self.view()
}
pub fn inverse_view_projection(&self) -> Option<Mat4> {
use cgmath::SquareMatrix;
let vp = self.view_projection();
vp.invert()
}
pub ... | units_per_pixel | identifier_name |
oneshot.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self, task: BlockedTask) -> SelectionResult<T> {
let n = unsafe { task.cast_to_uint() };
match self.state.compare_and_swap(EMPTY, n, atomic::SeqCst) {
EMPTY => SelSuccess,
DATA => SelCanceled(unsafe { BlockedTask::cast_from_uint(n) }),
DISCONNECTED if self.data.... | start_selection | identifier_name |
oneshot.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // If the other end has hung up, then we have complete ownership
// of the port. First, check if there was data waiting for us. This
// is possible if the other end sent something and then hung up.
//
// We then need to check to see if there was an upgrade req... | {
let state = match self.state.load(atomic::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
s @ DATA |
s @ DISCONNECTED => s,
// If we've got a blocked task, the... | identifier_body |
oneshot.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | /// is created.
///
/// Another possible optimization would be to not use an Arc box because
/// in theory we know when the shared packet can be deallocated (no real need
/// for the atomic reference counting), but I was having trouble how to destroy
/// the data early in a drop of a Port.
///
/// # Implementation
///
... | ///
/// This is the initial flavor of channels/ports used for comm module. This is
/// an optimization for the one-use case of a channel. The major optimization of
/// this type is to have one and exactly one allocation when the chan/port pair | random_line_split |
oneshot.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
// If someone's waiting, we gotta wake them up
n => UpWoke(unsafe { BlockedTask::cast_from_uint(n) })
}
}
pub fn drop_chan(&mut self) {
match self.state.swap(DISCONNECTED, atomic::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's wait... | { self.upgrade = prev; UpDisconnected } | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.