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 |
|---|---|---|---|---|
var-captured-in-nested-closure.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: int,
b: f64,
c: uint
}
fn main() {
let mut variable = 1;
let constant = 2;
let a_struct = Struct {
a: -3,
b: 4.5,
c: 5
};
let struct_ref = &a_struct;
let owned = box 6;
let managed = box(GC) 7;
let closure = || {
let closure_local = 8... | Struct | identifier_name |
config.rs | use toml;
pub struct Config {
value: Option<toml::Value>,
}
impl Config {
pub fn new(str: &str) -> Config {
Config {
value: str.parse::<toml::Value>().ok()
}
}
/// # Get the value of the preference
pub fn get(&self, str: &str) -> Option<&toml::Value> | break;
},
}
}
}
config_value
}
/// # Checks if the value of the preference is boolean true
pub fn is(&self, str: &str) -> Option<bool> {
let value: Option<&toml::Value> = self.get(str);
if value.is_so... | {
let strings: Vec<&str> = str.split(".").collect::<Vec<&str>>();
let mut config_value: Option<&toml::Value> = self.value.as_ref();
for item in &strings {
if config_value.is_some() {
match config_value.unwrap().get(item) {
Some(value) => {
... | identifier_body |
config.rs | use toml;
pub struct Config {
value: Option<toml::Value>,
}
impl Config {
pub fn new(str: &str) -> Config {
Config {
value: str.parse::<toml::Value>().ok()
}
}
/// # Get the value of the preference
pub fn get(&self, str: &str) -> Option<&toml::Value> {
let stri... | ,
None => {
config_value = None;
break;
},
}
}
}
config_value
}
/// # Checks if the value of the preference is boolean true
pub fn is(&self, str: &str) -> Option<bool> {
... | {
config_value = Some(value);
match *value {
toml::Value::Array(_) | toml::Value::Table(_) => {
config_value = Some(value);
},
_ => {
... | conditional_block |
config.rs | use toml;
pub struct Config {
value: Option<toml::Value>,
}
impl Config {
pub fn new(str: &str) -> Config {
Config {
value: str.parse::<toml::Value>().ok()
}
}
/// # Get the value of the preference
pub fn get(&self, str: &str) -> Option<&toml::Value> {
let stri... | (&self, str: &str) -> Option<bool> {
let value: Option<&toml::Value> = self.get(str);
if value.is_some() {
return value.unwrap().as_bool()
} else {
return None
}
}
} | is | identifier_name |
config.rs | use toml;
pub struct Config {
value: Option<toml::Value>,
}
impl Config {
pub fn new(str: &str) -> Config {
Config {
value: str.parse::<toml::Value>().ok()
}
}
/// # Get the value of the preference
pub fn get(&self, str: &str) -> Option<&toml::Value> {
let stri... | _ => {
break;
},
}
},
None => {
config_value = None;
break;
},
}
}
... | match *value {
toml::Value::Array(_) | toml::Value::Table(_) => {
config_value = Some(value);
}, | random_line_split |
issue-62307-match-ref-ref-forbidden-without-eq.rs | // RFC 1445 introduced `#[structural_match]`; this attribute must
// appear on the `struct`/`enum` definition for any `const` used in a
// pattern.
//
// This is our (forever-unstable) way to mark a datatype as having a
// `PartialEq` implementation that is equivalent to recursion over its
// substructure. This avoids ... | (i32);
// Overriding `PartialEq` to use this strange notion of "equality" exposes
// whether `match` is using structural-equality or method-dispatch
// under the hood, which is the antithesis of rust-lang/rfcs#1445
impl PartialEq for B {
fn eq(&self, other: &B) -> bool { std::cmp::min(self.0, other.0) == 0 }
}
fn... | B | identifier_name |
issue-62307-match-ref-ref-forbidden-without-eq.rs | // RFC 1445 introduced `#[structural_match]`; this attribute must
// appear on the `struct`/`enum` definition for any `const` used in a
// pattern.
//
// This is our (forever-unstable) way to mark a datatype as having a
// `PartialEq` implementation that is equivalent to recursion over its
// substructure. This avoids ... | {
const RR_B0: & & B = & & B(0);
const RR_B1: & & B = & & B(1);
match RR_B0 {
RR_B1 => { println!("CLAIM RR0: {:?} matches {:?}", RR_B1, RR_B0); }
//~^ WARN must be annotated with `#[derive(PartialEq, Eq)]`
//~| WARN this was previously accepted
_ => { }
}
match RR_... | identifier_body | |
issue-62307-match-ref-ref-forbidden-without-eq.rs | // RFC 1445 introduced `#[structural_match]`; this attribute must
// appear on the `struct`/`enum` definition for any `const` used in a
// pattern.
//
// This is our (forever-unstable) way to mark a datatype as having a |
// Issue 62307 pointed out a case where the structural-match checking
// was too shallow.
#![warn(indirect_structural_match, nontrivial_structural_match)]
// run-pass
#[derive(Debug)]
struct B(i32);
// Overriding `PartialEq` to use this strange notion of "equality" exposes
// whether `match` is using structural-equa... | // `PartialEq` implementation that is equivalent to recursion over its
// substructure. This avoids (at least in the short term) any need to
// resolve the question of what semantics is used for such matching.
// (See RFC 1445 for more details and discussion.) | random_line_split |
arc-rw-write-mode-shouldnt-escape.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = ~arc::RWARC(1);
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(write_mode);
}
y.get();
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).write |state| { assert!(*state == 1); }
} | identifier_body | |
arc-rw-write-mode-shouldnt-escape.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = ~arc::RWARC(1);
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(write_mode);
}
y.get();
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).write |state| { assert!(*state == 1); }
}
| main | identifier_name |
arc-rw-write-mode-shouldnt-escape.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 ... | // do (&option::unwrap(y)).write |state| { assert!(*state == 1); }
} | random_line_split | |
motion.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/. */
//! Computed types for CSS values that are related to motion path.
use crate::values::computed::Angle;
use crate... | (auto: &bool, angle: &Angle) -> bool {
*auto && angle.is_zero()
}
/// A computed offset-rotate.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
ToAnimatedZero,
ToCss,
ToResolvedValue,
)]
#[repr(C)]
pub struct OffsetRotate {
/// If ... | is_auto_zero_angle | identifier_name |
motion.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/. */
//! Computed types for CSS values that are related to motion path.
use crate::values::computed::Angle;
use crate... | ToResolvedValue,
)]
#[repr(C)]
pub struct OffsetRotate {
/// If auto is false, this is a fixed angle which indicates a
/// constant clockwise rotation transformation applied to it by this
/// specified rotation angle. Otherwise, the angle will be added to
/// the angle of the direction in layout.
... | ToAnimatedZero,
ToCss, | random_line_split |
motion.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/. */
//! Computed types for CSS values that are related to motion path.
use crate::values::computed::Angle;
use crate... |
}
| {
OffsetRotate {
auto: true,
angle: Zero::zero(),
}
} | identifier_body |
lib.rs | //!
//! # Conrod
//!
//! An easy-to-use, immediate-mode, 2D GUI library featuring a range of useful widgets.
//!
#![deny(missing_copy_implementations)]
#![warn(missing_docs)]
#[macro_use] extern crate bitflags;
extern crate clock_ticks;
extern crate elmesque;
extern crate graphics;
extern crate json_io;
extern crate ... | // Handle the final ID.
( $prev_id:expr => ) => ();
///// Handle end cases that don't have a trailing comma. /////
// Handle a single ID without a trailing comma.
( $widget_id:ident ) => (
const $widget_id: $crate::WidgetId = 0;
);
// Handle a single ID with some given step with... | () => ();
| random_line_split |
lib.rs | //!
//! # Conrod
//!
//! An easy-to-use, immediate-mode, 2D GUI library featuring a range of useful widgets.
//!
#![deny(missing_copy_implementations)]
#![warn(missing_docs)]
#[macro_use] extern crate bitflags;
extern crate clock_ticks;
extern crate elmesque;
extern crate graphics;
extern crate json_io;
extern crate ... | () {
widget_ids! {
A,
B with 64,
C with 32,
D,
E with 8,
}
assert_eq!(A, 0);
assert_eq!(B, 1);
assert_eq!(C, 66);
assert_eq!(D, 99);
assert_eq!(E, 100);
}
| test | identifier_name |
lib.rs | //!
//! # Conrod
//!
//! An easy-to-use, immediate-mode, 2D GUI library featuring a range of useful widgets.
//!
#![deny(missing_copy_implementations)]
#![warn(missing_docs)]
#[macro_use] extern crate bitflags;
extern crate clock_ticks;
extern crate elmesque;
extern crate graphics;
extern crate json_io;
extern crate ... | {
widget_ids! {
A,
B with 64,
C with 32,
D,
E with 8,
}
assert_eq!(A, 0);
assert_eq!(B, 1);
assert_eq!(C, 66);
assert_eq!(D, 99);
assert_eq!(E, 100);
} | identifier_body | |
touch.rs | // Copyright 2014 The sdl2-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | pub fn SDL_GetNumTouchFingers(touchID: SDL_TouchID) -> c_int;
pub fn SDL_GetTouchFinger(touchID: SDL_TouchID, index: c_int) -> *SDL_Finger;
} | pub fn SDL_GetTouchDevice(index: c_int) -> SDL_TouchID; | random_line_split |
touch.rs | // Copyright 2014 The sdl2-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | {
pub id: SDL_FingerID,
pub x: c_float,
pub y: c_float,
pub pressure: c_float,
}
pub static SDL_TOUCH_MOUSEID: Uint32 = -1;
extern "C" {
pub fn SDL_GetNumTouchDevices() -> c_int;
pub fn SDL_GetTouchDevice(index: c_int) -> SDL_TouchID;
pub fn SDL_GetNumTouchFingers(touchID: SDL_TouchID) ->... | SDL_Finger | identifier_name |
deriving-meta-multiple.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... | {
bar: uint,
baz: int
}
fn hash<T: Hash>(_t: &T) {}
pub fn main() {
let a = Foo {bar: 4, baz: -3};
a == a; // check for PartialEq impl w/o testing its correctness
a.clone(); // check for Clone impl w/o testing its correctness
hash(&a); // check for Hash impl w/o testing its correctness
}... | Foo | identifier_name |
deriving-meta-multiple.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... |
pub fn main() {
let a = Foo {bar: 4, baz: -3};
a == a; // check for PartialEq impl w/o testing its correctness
a.clone(); // check for Clone impl w/o testing its correctness
hash(&a); // check for Hash impl w/o testing its correctness
}
| {} | identifier_body |
deriving-meta-multiple.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 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::hash::{Hash, SipHasher};
// testing multiple separate deriving attributes
#[derive(PartialEq)]
#[derive(Clone)]
#[derive(Hash)]
struct Foo {
... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
htmlformelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLFormElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::d... | (&self) -> DOMString {
~""
}
pub fn SetTarget(&mut self, _target: DOMString) -> ErrorResult {
Ok(())
}
pub fn Elements(&self) -> @mut HTMLCollection {
let window = self.htmlelement.element.node.owner_doc().document().window;
HTMLCollection::new(window, ~[])
}
p... | Target | identifier_name |
htmlformelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLFormElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::d... | pub fn SetMethod(&mut self, _method: DOMString) -> ErrorResult {
Ok(())
}
pub fn Name(&self) -> DOMString {
~""
}
pub fn SetName(&mut self, _name: DOMString) -> ErrorResult {
Ok(())
}
pub fn NoValidate(&self) -> bool {
false
}
pub fn SetNoValidate(... | }
| random_line_split |
htmlformelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLFormElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::d... |
pub fn SetTarget(&mut self, _target: DOMString) -> ErrorResult {
Ok(())
}
pub fn Elements(&self) -> @mut HTMLCollection {
let window = self.htmlelement.element.node.owner_doc().document().window;
HTMLCollection::new(window, ~[])
}
pub fn Length(&self) -> i32 {
0
... | {
~""
} | identifier_body |
mod.rs | use num::{BigUint, Integer, Zero, One};
use rand::{Rng,Rand};
use std::io;
use std::ops::{Mul, Rem, Shr};
use std::fs;
use std::path::Path;
use time;
mod int128;
mod spotify_id;
mod arcvec;
mod subfile;
mod zerofile;
pub use util::int128::u128;
pub use util::spotify_id::{SpotifyId, FileId};
pub use util::arcvec::ArcV... |
}
pub fn now_ms() -> i64 {
let ts = time::now_utc().to_timespec();
ts.sec * 1000 + ts.nsec as i64 / 1000000
}
pub fn mkdir_existing(path: &Path) -> io::Result<()> {
fs::create_dir(path)
.or_else(|err| if err.kind() == io::ErrorKind::AlreadyExists {
Ok(())
} else {
E... | {
match self {
Ok(_) => (),
Err(_) => (),
}
} | identifier_body |
mod.rs | use num::{BigUint, Integer, Zero, One};
use rand::{Rng,Rand};
use std::io;
use std::ops::{Mul, Rem, Shr};
use std::fs;
use std::path::Path;
use time;
mod int128;
mod spotify_id;
mod arcvec;
mod subfile;
mod zerofile;
pub use util::int128::u128;
pub use util::spotify_id::{SpotifyId, FileId};
pub use util::arcvec::ArcV... | }
pub mod version {
include!(concat!(env!("OUT_DIR"), "/version.rs"));
pub fn version_string() -> String {
format!("librespot-{}", short_sha())
}
}
pub fn hexdump(data: &[u8]) {
for b in data.iter() {
eprint!("{:02X} ", b);
}
eprintln!("");
}
pub trait IgnoreExt {
fn igno... | return vec | random_line_split |
mod.rs | use num::{BigUint, Integer, Zero, One};
use rand::{Rng,Rand};
use std::io;
use std::ops::{Mul, Rem, Shr};
use std::fs;
use std::path::Path;
use time;
mod int128;
mod spotify_id;
mod arcvec;
mod subfile;
mod zerofile;
pub use util::int128::u128;
pub use util::spotify_id::{SpotifyId, FileId};
pub use util::arcvec::ArcV... | <'a>(&'a self, size: usize) -> StrChunks<'a> {
StrChunks(self, size)
}
}
impl <'s> Iterator for StrChunks<'s> {
type Item = &'s str;
fn next(&mut self) -> Option<&'s str> {
let &mut StrChunks(data, size) = self;
if data.is_empty() {
None
} else {
let ... | chunks | identifier_name |
f12-race-condition.rs | /// Figure 8.12 Program with a race condition
///
/// Takeaway: on OSX it needed at least usleep(20) in order
/// to experience the race condition
///
/// $ f12-race-condition | awk 'END{print NR}'
/// 2
extern crate libc;
extern crate apue;
use libc::{c_char, FILE, STDOUT_FILENO, fork, setbuf, fdopen, usleep};
use a... | (out: *mut FILE, s: &str) {
for c in s.chars() {
putc(c as i32, out);
usleep(20);
}
}
fn main() {
unsafe {
// set unbuffered
let stdout = fdopen(STDOUT_FILENO, &('w' as c_char));
setbuf(stdout, std::ptr::null_mut());
let pid = fork().check_not_negative().expe... | charatatime | identifier_name |
f12-race-condition.rs | /// Figure 8.12 Program with a race condition
///
/// Takeaway: on OSX it needed at least usleep(20) in order
/// to experience the race condition
///
/// $ f12-race-condition | awk 'END{print NR}'
/// 2
extern crate libc;
extern crate apue;
use libc::{c_char, FILE, STDOUT_FILENO, fork, setbuf, fdopen, usleep};
use a... | putc(c as i32, out);
usleep(20);
}
}
fn main() {
unsafe {
// set unbuffered
let stdout = fdopen(STDOUT_FILENO, &('w' as c_char));
setbuf(stdout, std::ptr::null_mut());
let pid = fork().check_not_negative().expect("fork error");
match pid {
0 =... | random_line_split | |
f12-race-condition.rs | /// Figure 8.12 Program with a race condition
///
/// Takeaway: on OSX it needed at least usleep(20) in order
/// to experience the race condition
///
/// $ f12-race-condition | awk 'END{print NR}'
/// 2
extern crate libc;
extern crate apue;
use libc::{c_char, FILE, STDOUT_FILENO, fork, setbuf, fdopen, usleep};
use a... |
fn main() {
unsafe {
// set unbuffered
let stdout = fdopen(STDOUT_FILENO, &('w' as c_char));
setbuf(stdout, std::ptr::null_mut());
let pid = fork().check_not_negative().expect("fork error");
match pid {
0 => charatatime(stdout, "output from child \n"),
... | {
for c in s.chars() {
putc(c as i32, out);
usleep(20);
}
} | identifier_body |
arena.rs | use std::ptr;
use crate::gc::Address;
use crate::mem;
use crate::os::page_size;
pub fn reserve(size: usize) -> Address {
debug_assert!(mem::is_page_aligned(size));
let ptr = unsafe {
libc::mmap(
ptr::null_mut(),
size,
libc::PROT_NONE,
libc::MAP_PRIVATE ... |
}
| {
panic!("discarding memory with mprotect() failed");
} | conditional_block |
arena.rs | use std::ptr;
| pub fn reserve(size: usize) -> Address {
debug_assert!(mem::is_page_aligned(size));
let ptr = unsafe {
libc::mmap(
ptr::null_mut(),
size,
libc::PROT_NONE,
libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE,
-1,
0,
) a... | use crate::gc::Address;
use crate::mem;
use crate::os::page_size;
| random_line_split |
arena.rs | use std::ptr;
use crate::gc::Address;
use crate::mem;
use crate::os::page_size;
pub fn reserve(size: usize) -> Address {
debug_assert!(mem::is_page_aligned(size));
let ptr = unsafe {
libc::mmap(
ptr::null_mut(),
size,
libc::PROT_NONE,
libc::MAP_PRIVATE ... | (ptr: Address, size: usize) {
debug_assert!(ptr.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
let res = unsafe { libc::madvise(ptr.to_mut_ptr(), size, libc::MADV_DONTNEED) };
if res!= 0 {
panic!("discarding memory with madvise() failed");
}
let res = unsafe { libc::mp... | discard | identifier_name |
arena.rs | use std::ptr;
use crate::gc::Address;
use crate::mem;
use crate::os::page_size;
pub fn reserve(size: usize) -> Address {
debug_assert!(mem::is_page_aligned(size));
let ptr = unsafe {
libc::mmap(
ptr::null_mut(),
size,
libc::PROT_NONE,
libc::MAP_PRIVATE ... |
pub fn discard(ptr: Address, size: usize) {
debug_assert!(ptr.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
let res = unsafe { libc::madvise(ptr.to_mut_ptr(), size, libc::MADV_DONTNEED) };
if res!= 0 {
panic!("discarding memory with madvise() failed");
}
let res = u... | {
debug_assert!(ptr.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
let val = unsafe {
libc::mmap(
ptr.to_mut_ptr(),
size,
libc::PROT_NONE,
libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE,
-1,
0,
... | identifier_body |
mod.rs | // Copyright 2017 Kai Strempel | //
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distribut... | random_line_split | |
mod.rs | // Copyright 2017 Kai Strempel
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | () {
use Client;
use volumes::VolumesClient;
let client = Client::from_env();
let volumes_client = VolumesClient::new(&client);
let volumes = volumes_client.get();
assert!(volumes.is_ok());
}
}
| it_works | identifier_name |
mod.rs | // Copyright 2017 Kai Strempel
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... |
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
use Client;
use volumes::VolumesClient;
let client = Client::from_env();
let volumes_client = VolumesClient::new(&client);
let volumes = volumes_client.get();
assert!(volumes.is_ok());
}
}
| {
get(self.client, "volumes")
} | identifier_body |
lib.rs | //! Atomic counting semaphore that can help you control access to a common resource
//! by multiple processes in a concurrent system.
//!
//! ## Features
//!
//! - Effectively lock-free* semantics
//! - Provides RAII-style acquire/release API
//! - Implements `Send`, `Sync` and `Clone`
//!
//! _* lock-free when not usi... |
} else {
Err(TryAccessError::Shutdown)
}
}
/// Shut down the semaphore.
///
/// This prevents any further access from being granted to the underlying resource.
/// As soon as the last access is released and the returned handle goes out of scope,
/// the resource wil... | {
Err(TryAccessError::NoCapacity)
} | conditional_block |
lib.rs | //! Atomic counting semaphore that can help you control access to a common resource
//! by multiple processes in a concurrent system.
//!
//! ## Features
//!
//! - Effectively lock-free* semantics
//! - Provides RAII-style acquire/release API
//! - Implements `Send`, `Sync` and `Clone`
//!
//! _* lock-free when not usi... | use parking_lot::RwLock;
mod raw;
use raw::RawSemaphore;
mod guard;
pub use guard::SemaphoreGuard;
mod shutdown;
pub use shutdown::ShutdownHandle;
#[cfg(test)]
mod tests;
/// Result returned from `Semaphore::try_access`.
pub type TryAccessResult<T> = Result<SemaphoreGuard<T>, TryAccessError>;
#[derive(Copy, Clone... | random_line_split | |
lib.rs | //! Atomic counting semaphore that can help you control access to a common resource
//! by multiple processes in a concurrent system.
//!
//! ## Features
//!
//! - Effectively lock-free* semantics
//! - Provides RAII-style acquire/release API
//! - Implements `Send`, `Sync` and `Clone`
//!
//! _* lock-free when not usi... |
#[inline]
/// Attempt to access the underlying resource of this semaphore.
///
/// This function will try to acquire access, and then return an RAII
/// guard structure which will release the access when it falls out of scope.
/// If the semaphore is out of capacity or shut down, a `TryAccessE... | {
Semaphore {
raw: Arc::new(RawSemaphore::new(capacity)),
resource: Arc::new(RwLock::new(Some(Arc::new(resource))))
}
} | identifier_body |
lib.rs | //! Atomic counting semaphore that can help you control access to a common resource
//! by multiple processes in a concurrent system.
//!
//! ## Features
//!
//! - Effectively lock-free* semantics
//! - Provides RAII-style acquire/release API
//! - Implements `Send`, `Sync` and `Clone`
//!
//! _* lock-free when not usi... | (&self) -> ShutdownHandle<T> {
shutdown::new(&self.raw, self.resource.write().take())
}
}
| shutdown | identifier_name |
animation.rs | // Copyright 2018 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | {
Animation,
InputOnly,
}
impl EventLoopMode {
pub fn merge(self, other: EventLoopMode) -> EventLoopMode {
match self {
EventLoopMode::Animation => EventLoopMode::Animation,
_ => other,
}
}
}
#[derive(Clone)]
pub struct TimeLerp {
started_at: Instant,
d... | EventLoopMode | identifier_name |
animation.rs | // Copyright 2018 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | // 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.
use map_model::Pt2D;
use std::time::Instant;
#[derive(PartialEq)]
pub enum EventLoopMode {
Animation,
InputOnly,
}
impl EventLoo... | random_line_split | |
animation.rs | // Copyright 2018 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
}
#[derive(Clone)]
pub struct TimeLerp {
started_at: Instant,
dur_s: f64,
}
impl TimeLerp {
pub fn with_dur_s(dur_s: f64) -> TimeLerp {
TimeLerp {
dur_s,
started_at: Instant::now(),
}
}
fn elapsed(&self) -> f64 {
let dt = self.started_at.elapsed();... | {
match self {
EventLoopMode::Animation => EventLoopMode::Animation,
_ => other,
}
} | identifier_body |
comment.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::CommentBinding;
use crate::dom::bindings::codegen::Bindings::WindowB... | (window: &Window, data: DOMString) -> Fallible<DomRoot<Comment>> {
let document = window.Document();
Ok(Comment::new(data, &document))
}
}
| Constructor | identifier_name |
comment.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::CommentBinding; | use crate::dom::characterdata::CharacterData;
use crate::dom::document::Document;
use crate::dom::node::Node;
use crate::dom::window::Window;
use dom_struct::dom_struct;
/// An HTML comment.
#[dom_struct]
pub struct Comment {
characterdata: CharacterData,
}
impl Comment {
fn new_inherited(text: DOMString, doc... | use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString; | random_line_split |
compress.rs | extern crate byteorder;
extern crate crc;
use std::io;
use std::io::{BufWriter, ErrorKind, Write, Seek, SeekFrom, Result, Error};
use self::byteorder::{ByteOrder, WriteBytesExt, LittleEndian};
use self::crc::{crc32, Hasher32};
use definitions::*;
// We limit how far copy back-references can go, the same as the C++ ... |
x = length;
if x > 1 << 6 {
x = 1 << 6;
}
dst[i] = ((x as u8) - 1) << 2 | TAG_COPY_2;
dst[i + 1] = offset as u8;
dst[i + 2] = (offset >> 8) as u8;
i += 3;
length -= x;
}
// (Future) Return a `Result<usize>` Instead??
i
}
// max_co... | {
dst[i] = ((offset >> 8) as u8) & 0x07 << 5 | (x as u8) << 2 | TAG_COPY_1;
dst[i + 1] = offset as u8;
i += 2;
break;
} | conditional_block |
compress.rs | extern crate byteorder;
extern crate crc;
use std::io;
use std::io::{BufWriter, ErrorKind, Write, Seek, SeekFrom, Result, Error};
use self::byteorder::{ByteOrder, WriteBytesExt, LittleEndian};
use self::crc::{crc32, Hasher32};
use definitions::*;
// We limit how far copy back-references can go, the same as the C++ ... |
while length > 0 {
// TODO: Handle Overflow
let mut x = length - 4;
if 0 <= x && x < 1 << 3 && offset < 1 << 11 {
dst[i] = ((offset >> 8) as u8) & 0x07 << 5 | (x as u8) << 2 | TAG_COPY_1;
dst[i + 1] = offset as u8;
i += 2;
break;
}
... | random_line_split | |
compress.rs | extern crate byteorder;
extern crate crc;
use std::io;
use std::io::{BufWriter, ErrorKind, Write, Seek, SeekFrom, Result, Error};
use self::byteorder::{ByteOrder, WriteBytesExt, LittleEndian};
use self::crc::{crc32, Hasher32};
use definitions::*;
// We limit how far copy back-references can go, the same as the C++ ... | (&mut self, src: &[u8]) -> Result<usize> {
let mut written: usize = 0;
if!self.wrote_header {
// Write Stream Literal
try!(self.inner.write(&MAGIC_CHUNK));
self.wrote_header = true;
}
// Split source into chunks of 65536 bytes each.
for src_... | write | identifier_name |
compress.rs | extern crate byteorder;
extern crate crc;
use std::io;
use std::io::{BufWriter, ErrorKind, Write, Seek, SeekFrom, Result, Error};
use self::byteorder::{ByteOrder, WriteBytesExt, LittleEndian};
use self::crc::{crc32, Hasher32};
use definitions::*;
// We limit how far copy back-references can go, the same as the C++ ... |
}
// Compress writes the encoded form of src into dst and return the length
// written.
// Returns an error if dst was not large enough to hold the entire encoded
// block.
// (Future) Include a Legacy Compress??
pub fn compress(dst: &mut [u8], src: &[u8]) -> io::Result<usize> {
if dst.len() < max_compressed_le... | {
self.inner.seek(pos).and_then(|res: u64| {
self.pos = res;
Ok(res)
})
} | identifier_body |
mod.rs | extern crate fdt;
extern crate byteorder;
use alloc::vec::Vec;
use core::slice;
use crate::memory::MemoryArea;
use self::byteorder::{ByteOrder, BE};
pub static mut MEMORY_MAP: [MemoryArea; 512] = [MemoryArea {
base_addr: 0,
length: 0,
_type: 0,
acpi: 0,
}; 512];
fn root_cell_sz(dt: &fdt::DeviceTree) ... | }
let mut s = 0;
for sz_chunk in size.rchunks(4) {
s += BE::read_u32(sz_chunk);
}
ranges[index] = (b as usize, s as usize);
index += 1;
}
index
}
pub fn diag_uart_range(dtb_base: usize, dtb_size: usize) -> Option<(usize, usize)> {
let data = unsaf... | let mut b = 0;
for base_chunk in base.rchunks(4) {
b += BE::read_u32(base_chunk); | random_line_split |
mod.rs | extern crate fdt;
extern crate byteorder;
use alloc::vec::Vec;
use core::slice;
use crate::memory::MemoryArea;
use self::byteorder::{ByteOrder, BE};
pub static mut MEMORY_MAP: [MemoryArea; 512] = [MemoryArea {
base_addr: 0,
length: 0,
_type: 0,
acpi: 0,
}; 512];
fn root_cell_sz(dt: &fdt::DeviceTree) ... | (dtb_base: usize, dtb_size: usize) -> Option<(usize, usize)> {
let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) };
let dt = fdt::DeviceTree::new(data).unwrap();
let chosen_node = dt.find_node("/chosen").unwrap();
let stdout_path = chosen_node.properties().find(|p| p.name.conta... | diag_uart_range | identifier_name |
mod.rs | extern crate fdt;
extern crate byteorder;
use alloc::vec::Vec;
use core::slice;
use crate::memory::MemoryArea;
use self::byteorder::{ByteOrder, BE};
pub static mut MEMORY_MAP: [MemoryArea; 512] = [MemoryArea {
base_addr: 0,
length: 0,
_type: 0,
acpi: 0,
}; 512];
fn root_cell_sz(dt: &fdt::DeviceTree) ... |
}
pub fn fill_memory_map(dtb_base: usize, dtb_size: usize) {
let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) };
let dt = fdt::DeviceTree::new(data).unwrap();
let (address_cells, size_cells) = root_cell_sz(&dt).unwrap();
let mut ranges: [(usize, usize); 10] = [(0,0); 10];
... | {
0
} | conditional_block |
mod.rs | extern crate fdt;
extern crate byteorder;
use alloc::vec::Vec;
use core::slice;
use crate::memory::MemoryArea;
use self::byteorder::{ByteOrder, BE};
pub static mut MEMORY_MAP: [MemoryArea; 512] = [MemoryArea {
base_addr: 0,
length: 0,
_type: 0,
acpi: 0,
}; 512];
fn root_cell_sz(dt: &fdt::DeviceTree) ... | ranges[index] = (b as usize, s as usize);
index += 1;
}
index
}
pub fn diag_uart_range(dtb_base: usize, dtb_size: usize) -> Option<(usize, usize)> {
let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) };
let dt = fdt::DeviceTree::new(data).unwrap();
let chos... | {
let memory_node = dt.find_node("/memory").unwrap();
let reg = memory_node.properties().find(|p| p.name.contains("reg")).unwrap();
let chunk_sz = (address_cells + size_cells) * 4;
let chunk_count = (reg.data.len() / chunk_sz);
let mut index = 0;
for chunk in reg.data.chunks(chunk_sz as usize) ... | identifier_body |
monomorphized-callees-with-ty-params-3314.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 ... |
}
impl Serializer for int {
}
pub fn main() {
let foo = F { a: 1 };
foo.serialize(1);
let bar = F { a: F {a: 1 } };
bar.serialize(2);
}
| {
self.a.serialize(s);
} | identifier_body |
monomorphized-callees-with-ty-params-3314.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let foo = F { a: 1 };
foo.serialize(1);
let bar = F { a: F {a: 1 } };
bar.serialize(2);
}
| main | identifier_name |
monomorphized-callees-with-ty-params-3314.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 ... |
trait Serializable {
fn serialize<S:Serializer>(&self, s: S);
}
impl Serializable for int {
fn serialize<S:Serializer>(&self, _s: S) { }
}
struct F<A> { a: A }
impl<A:Serializable> Serializable for F<A> {
fn serialize<S:Serializer>(&self, s: S) {
self.a.serialize(s);
}
}
impl Serializer for... |
trait Serializer {
} | random_line_split |
window_builder.rs | use std::{collections::HashMap, sync::mpsc};
use super::{Shell, Window};
use crate::{
render::RenderContext2D, utils::Rectangle, window_adapter::WindowAdapter, WindowRequest,
WindowSettings,
};
/// The `WindowBuilder` is used to construct an os independent window
/// shell that will communicate with the suppo... |
let window = orbclient::Window::new_flags(
self.bounds.x() as i32,
self.bounds.y() as i32,
self.bounds.width() as u32,
self.bounds.height() as u32,
self.title.as_str(),
&flags,
)
.expect("WindowBuilder: Could not create an ... | {
flags.push(orbclient::WindowFlag::Front);
} | conditional_block |
window_builder.rs | use std::{collections::HashMap, sync::mpsc};
use super::{Shell, Window};
use crate::{
render::RenderContext2D, utils::Rectangle, window_adapter::WindowAdapter, WindowRequest,
WindowSettings,
};
/// The `WindowBuilder` is used to construct an os independent window
/// shell that will communicate with the suppo... |
/// Mark window as resizeable.
pub fn resizeable(mut self, resizeable: bool) -> Self {
self.resizeable = resizeable;
self
}
/// Register a window request receiver to communicate with the
/// window shell via interprocess communication.
pub fn request_receiver(mut self, request... | {
WindowBuilder {
adapter,
always_on_top: false,
borderless: false,
bounds: Rectangle::new((0.0, 0.0), (100.0, 75.0)),
fonts: HashMap::new(),
request_receiver: None,
resizeable: false,
shell,
title: Strin... | identifier_body |
window_builder.rs | use std::{collections::HashMap, sync::mpsc};
use super::{Shell, Window};
use crate::{
render::RenderContext2D, utils::Rectangle, window_adapter::WindowAdapter, WindowRequest,
WindowSettings,
};
/// The `WindowBuilder` is used to construct an os independent window
/// shell that will communicate with the suppo... | always_on_top: settings.always_on_top,
borderless: settings.borderless,
bounds: Rectangle::new(settings.position, (settings.size.0, settings.size.1)),
fonts: settings.fonts,
request_receiver: None,
resizeable: settings.resizeable,
shell... | adapter, | random_line_split |
window_builder.rs | use std::{collections::HashMap, sync::mpsc};
use super::{Shell, Window};
use crate::{
render::RenderContext2D, utils::Rectangle, window_adapter::WindowAdapter, WindowRequest,
WindowSettings,
};
/// The `WindowBuilder` is used to construct an os independent window
/// shell that will communicate with the suppo... | (shell: &'a mut Shell<A>, adapter: A) -> Self {
WindowBuilder {
adapter,
always_on_top: false,
borderless: false,
bounds: Rectangle::new((0.0, 0.0), (100.0, 75.0)),
fonts: HashMap::new(),
request_receiver: None,
resizeable: fals... | new | identifier_name |
geometry.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::ToCss;
use euclid::length::Length;
use euclid::num::Zero;
use euclid::point::Point2D;
use euclid::... | <T: PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool {
point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width &&
point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height
}
/// A helper function to convert a rect of `f32` pixels to a rect of app units.
pu... | rect_contains_point | identifier_name |
geometry.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::ToCss;
use euclid::length::Length;
use euclid::num::Zero;
use euclid::point::Point2D;
use euclid::... | y: Au(0),
},
size: Size2D {
width: Au(0),
height: Au(0),
}
};
pub static MAX_RECT: Rect<Au> = Rect {
origin: Point2D {
x: Au(i32::MIN / 2),
y: Au(i32::MIN / 2),
},
size: Size2D {
width: MAX_AU,
height: MAX_AU,
}
};
pub const MIN_AU: A... | origin: Point2D {
x: Au(0), | random_line_split |
geometry.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::ToCss;
use euclid::length::Length;
use euclid::num::Zero;
use euclid::point::Point2D;
use euclid::... | ;
}
#[inline]
pub fn from_f32_px(px: f32) -> Au {
Au((px * (AU_PER_PX as f32)) as i32)
}
#[inline]
pub fn from_pt(pt: f64) -> Au {
Au::from_f64_px(pt_to_px(pt))
}
#[inline]
pub fn from_f64_px(px: f64) -> Au {
Au((px * (AU_PER_PX as f64)) as i32)
}
}
//... | { return Au(self.0 - res) } | conditional_block |
geometry.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::ToCss;
use euclid::length::Length;
use euclid::num::Zero;
use euclid::point::Point2D;
use euclid::... |
/// Rounds this app unit down to the previous (left or top) pixel and returns it.
#[inline]
pub fn to_prev_px(self) -> i32 {
((self.0 as f64) / (AU_PER_PX as f64)).floor() as i32
}
/// Rounds this app unit up to the next (right or bottom) pixel and returns it.
#[inline]
pub fn to_... | {
self.0 / AU_PER_PX
} | identifier_body |
util.rs | /*
* Copyright 2020 Clint Byrum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | } else if input[0] == b'1' {
true
} else {
false
}
}
pub fn new_res(ptype: u32, data: Bytes) -> Packet {
Packet {
magic: PacketMagic::RES,
ptype: ptype,
psize: data.len() as u32,
data: data,
}
}
pub fn new_req(ptype: u32, data: Bytes) -> Packet {
... | pub fn bytes2bool(input: &Bytes) -> bool {
if input.len() != 1 {
false | random_line_split |
util.rs | /*
* Copyright 2020 Clint Byrum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | {
Packet {
magic: PacketMagic::TEXT,
ptype: ADMIN_RESPONSE,
psize: 0,
data: Bytes::new(),
}
} | identifier_body | |
util.rs | /*
* Copyright 2020 Clint Byrum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | (ptype: u32, data: Bytes) -> Packet {
Packet {
magic: PacketMagic::REQ,
ptype: ptype,
psize: data.len() as u32,
data: data,
}
}
pub fn next_field(buf: &mut Bytes) -> Bytes {
match buf[..].iter().position(|b| *b == b'\0') {
Some(null_pos) => {
let value = ... | new_req | identifier_name |
messageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... | }
} | random_line_split | |
messageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... |
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
self.lastEventId.clone()
} | identifier_body |
messageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... | {
event: Event,
data: Heap<JSVal>,
origin: DOMString,
lastEventId: DOMString,
}
impl MessageEvent {
pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<MessageEvent> {
MessageEvent::new_initialized(global,
HandleValue::undefined(),
... | MessageEvent | identifier_name |
window.rs | use std::fmt;
use std::ops::Range;
use std::iter::IntoIterator;
use types::{State, BoardView};
use board::Board;
#[derive(Clone, Copy)]
pub struct Window<'a> {
pub min_x: i32,
pub min_y: i32,
pub max_x: i32,
pub max_y: i32,
board: &'a Board
}
impl<'a> Window<'a> {
pub fn new(board: &'a Board,... |
}
impl<'a> BoardView for Window<'a> {
fn cell_state(&self, x: i32, y: i32) -> State {
self.board.cell_state(x, y)
}
fn as_window<'b>(&'b self) -> Window<'b> {
*self
}
fn iter<'b>(&'b self) -> Iter<'b> {
Iter {
window: *self,
x: self.min_x,
... | {
loop {
if self.x == self.window.max_x + 1 {
return None;
}
match self.ys.next() {
Some(y) => {
let state = self.window.cell_state(self.x, y);
return Some((self.x, y, state))
},
... | identifier_body |
window.rs | use std::fmt;
use std::ops::Range;
use std::iter::IntoIterator;
use types::{State, BoardView};
use board::Board;
#[derive(Clone, Copy)]
pub struct Window<'a> {
pub min_x: i32,
pub min_y: i32,
pub max_x: i32,
pub max_y: i32,
board: &'a Board
}
impl<'a> Window<'a> {
pub fn new(board: &'a Board,... | match self.ys.next() {
Some(y) => {
let state = self.window.cell_state(self.x, y);
return Some((self.x, y, state))
},
None => {
self.ys = 0..self.window.max_y + 1;
self.x += 1;
... | if self.x == self.window.max_x + 1 {
return None;
} | random_line_split |
window.rs | use std::fmt;
use std::ops::Range;
use std::iter::IntoIterator;
use types::{State, BoardView};
use board::Board;
#[derive(Clone, Copy)]
pub struct Window<'a> {
pub min_x: i32,
pub min_y: i32,
pub max_x: i32,
pub max_y: i32,
board: &'a Board
}
impl<'a> Window<'a> {
pub fn new(board: &'a Board,... | <'b>(&'b self) -> Iter<'b> {
Iter {
window: *self,
x: self.min_x,
ys: self.min_y..self.max_y + 1
}
}
fn window<'b>(&'b self, min_x: i32, min_y: i32, max_x: i32, max_y: i32)
-> Window<'b> {
Window {
min_x: min_x,
... | iter | identifier_name |
100_doors_unoptimized.rs | // Implements http://rosettacode.org/wiki/100_doors
// this is the unoptimized version that performs all 100
// passes, as per the original description of the problem
#![feature(core)]
use std::iter::range_step_inclusive;
#[cfg(not(test))]
fn | () {
// states for the 100 doors
// uses a vector of booleans,
// where state==false means the door is closed
let mut doors = [false; 100];
solve(&mut doors);
for (idx, door) in doors.iter().enumerate() {
println!("door {} open: {}", idx+1, door);
}
}
// unoptimized solution for t... | main | identifier_name |
100_doors_unoptimized.rs | // Implements http://rosettacode.org/wiki/100_doors
// this is the unoptimized version that performs all 100
// passes, as per the original description of the problem
#![feature(core)]
use std::iter::range_step_inclusive;
#[cfg(not(test))]
fn main() {
// states for the 100 doors
// uses a vector of booleans,
... |
// test that the doors with index corresponding to
// a perfect square are now open
for i in 1..11 {
assert!(doors[i*i - 1]);
}
} | fn solution() {
let mut doors = [false;100];
solve(&mut doors); | random_line_split |
100_doors_unoptimized.rs | // Implements http://rosettacode.org/wiki/100_doors
// this is the unoptimized version that performs all 100
// passes, as per the original description of the problem
#![feature(core)]
use std::iter::range_step_inclusive;
#[cfg(not(test))]
fn main() {
// states for the 100 doors
// uses a vector of booleans,
... |
#[test]
fn solution() {
let mut doors = [false;100];
solve(&mut doors);
// test that the doors with index corresponding to
// a perfect square are now open
for i in 1..11 {
assert!(doors[i*i - 1]);
}
}
| {
for pass in 1..101 {
for door in range_step_inclusive(pass, 100, pass) {
// flip the state of the door
doors[door-1] = !doors[door-1]
}
}
} | identifier_body |
secret.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
}
| {
&self.inner
} | identifier_body |
secret.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (key: &[u8]) -> Self {
assert_eq!(32, key.len(), "Caller should provide 32-byte length slice");
let mut h = H256::default();
h.copy_from_slice(&key[0..32]);
Secret { inner: h }
}
pub fn from_slice(key: &[u8]) -> Result<Self, Error> {
let secret = key::SecretKey::from_slice(&super::SECP256K1, key)?;
Ok(s... | from_slice_unchecked | identifier_name |
secret.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | impl fmt::Debug for Secret {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Secret: 0x{:x}{:x}..{:x}{:x}", self.inner[0], self.inner[1], self.inner[30], self.inner[31])
}
}
impl Secret {
fn from_slice_unchecked(key: &[u8]) -> Self {
assert_eq!(32, key.len(), "Caller should provide 32-byte... | #[derive(Clone, PartialEq, Eq)]
pub struct Secret {
inner: H256,
}
| random_line_split |
package.rs | use super::module::module_from_declarations;
use crate::error::ValidationError;
use crate::parser::PackageDecl;
use crate::prelude::std_module;
use crate::repr::{ModuleIx, ModuleRepr, Package};
use crate::Location;
use cranelift_entity::PrimaryMap;
use std::collections::HashMap;
pub fn package_from_declarations(
p... |
}
}
Ok(pkg.build())
}
pub struct PackageBuilder {
name_decls: HashMap<String, (ModuleIx, Option<Location>)>,
repr: Package,
}
impl PackageBuilder {
pub fn new() -> Self {
let mut repr = Package {
names: PrimaryMap::new(),
modules: PrimaryMap::new(),
... | {
let module_ix = pkg.introduce_name(name, *location)?;
let module_repr = module_from_declarations(pkg.repr(), module_ix, &decls)?;
pkg.define_module(module_ix, module_repr);
} | conditional_block |
package.rs | use super::module::module_from_declarations;
use crate::error::ValidationError;
use crate::parser::PackageDecl;
use crate::prelude::std_module;
use crate::repr::{ModuleIx, ModuleRepr, Package};
use crate::Location;
use cranelift_entity::PrimaryMap;
use std::collections::HashMap;
pub fn package_from_declarations(
p... |
#[test]
fn no_mod_std_name() {
let err = pkg_("mod std {}").err().expect("error package");
assert_eq!(
err,
ValidationError::Syntax {
expected: "non-reserved module name",
location: Location { line: 1, column: 0 },
}
);... | let _bar = foo.datatype("bar").expect("foo::bar exists");
} | random_line_split |
package.rs | use super::module::module_from_declarations;
use crate::error::ValidationError;
use crate::parser::PackageDecl;
use crate::prelude::std_module;
use crate::repr::{ModuleIx, ModuleRepr, Package};
use crate::Location;
use cranelift_entity::PrimaryMap;
use std::collections::HashMap;
pub fn package_from_declarations(
p... |
pub fn define_module(&mut self, ix: ModuleIx, mod_repr: ModuleRepr) {
assert!(self.repr.names.is_valid(ix));
let pushed_ix = self.repr.modules.push(mod_repr);
assert_eq!(ix, pushed_ix);
}
pub fn build(self) -> Package {
self.repr
}
}
#[cfg(test)]
mod test {
use su... | {
&self.repr
} | identifier_body |
package.rs | use super::module::module_from_declarations;
use crate::error::ValidationError;
use crate::parser::PackageDecl;
use crate::prelude::std_module;
use crate::repr::{ModuleIx, ModuleRepr, Package};
use crate::Location;
use cranelift_entity::PrimaryMap;
use std::collections::HashMap;
pub fn | (
package_decls: &[PackageDecl],
) -> Result<Package, ValidationError> {
let mut pkg = PackageBuilder::new();
for decl in package_decls {
match decl {
PackageDecl::Module {
name,
location,
decls,
} => {
let modul... | package_from_declarations | identifier_name |
2-1-literals.rs | fn main() | // Use underscores to improve readibility!
println!("One million is written as {}", 1_000_000u32);
}
| {
// Addition with unsigned integer
println!("1 + 3 = {}", 1u32 + 3);
// Subtraction with signed integer
// Rust refuses to compile if there is an overflow
println!("1 - 3 = {}", 1i32 - 3);
// Boolean logic
println!("true AND false is {}", true && false);
println!("true OR false is {}"... | identifier_body |
2-1-literals.rs | fn | () {
// Addition with unsigned integer
println!("1 + 3 = {}", 1u32 + 3);
// Subtraction with signed integer
// Rust refuses to compile if there is an overflow
println!("1 - 3 = {}", 1i32 - 3);
// Boolean logic
println!("true AND false is {}", true && false);
println!("true OR false is ... | main | identifier_name |
2-1-literals.rs | fn main() {
// Addition with unsigned integer | // Rust refuses to compile if there is an overflow
println!("1 - 3 = {}", 1i32 - 3);
// Boolean logic
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT false is {}",!true);
// Bitwise operations
println!("0110 AND 0011 is {:0... | println!("1 + 3 = {}", 1u32 + 3);
// Subtraction with signed integer | random_line_split |
timer.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::time::{Duration, Instant};
use gotham::state::State;
use gotham_derive::StateData;
use hyper::{Body, Response};
use super::Middl... |
}
}
| {
let headers_duration = start.elapsed();
state.put(HeadersDuration(headers_duration));
} | conditional_block |
timer.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::time::{Duration, Instant};
use gotham::state::State;
use gotham_derive::StateData;
use hyper::{Body, Response};
use super::Middl... | #[async_trait::async_trait]
impl Middleware for TimerMiddleware {
async fn inbound(&self, state: &mut State) -> Option<Response<Body>> {
state.put(RequestStartTime(Instant::now()));
None
}
async fn outbound(&self, state: &mut State, _response: &mut Response<Body>) {
if let Some(Requ... | random_line_split | |
timer.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::time::{Duration, Instant};
use gotham::state::State;
use gotham_derive::StateData;
use hyper::{Body, Response};
use super::Middl... | (pub Instant);
#[derive(StateData, Debug, Copy, Clone)]
pub struct HeadersDuration(pub Duration);
#[derive(Clone)]
pub struct TimerMiddleware;
impl TimerMiddleware {
pub fn new() -> Self {
TimerMiddleware
}
}
#[async_trait::async_trait]
impl Middleware for TimerMiddleware {
async fn inbound(&sel... | RequestStartTime | identifier_name |
filter_profile.rs | #!/bin/bash
#![forbid(unsafe_code)]/* This line is ignored by bash
# This block is ignored by rustc
pushd $(dirname "$0")/../
source scripts/config.sh
RUSTC="$(pwd)/build/bin/cg_clif"
popd
PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0
#*/
//! This program filters away uni... |
const FREE: &str = "free";
if let Some(index) = stack.find(FREE) {
stack = &stack[..index + FREE.len()];
}
const TYPECK_ITEM_BODIES: &str = "rustc_typeck::check::typeck_item_bodies";
if let Some(index) = stack.find(TYPECK_ITEM_BODIES) {
stack = &stack[..... | stack = &stack[..index + MALLOC.len()];
} | random_line_split |
filter_profile.rs | #!/bin/bash
#![forbid(unsafe_code)]/* This line is ignored by bash
# This block is ignored by rustc
pushd $(dirname "$0")/../
source scripts/config.sh
RUSTC="$(pwd)/build/bin/cg_clif"
popd
PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0
#*/
//! This program filters away uni... | () -> Result<(), Box<dyn std::error::Error>> {
let profile_name = std::env::var("PROFILE").unwrap();
let output_name = std::env::var("OUTPUT").unwrap();
if profile_name.is_empty() || output_name.is_empty() {
println!("Usage:./filter_profile.rs <profile in stackcollapse format> <output file>");
... | main | identifier_name |
filter_profile.rs | #!/bin/bash
#![forbid(unsafe_code)]/* This line is ignored by bash
# This block is ignored by rustc
pushd $(dirname "$0")/../
source scripts/config.sh
RUSTC="$(pwd)/build/bin/cg_clif"
popd
PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0
#*/
//! This program filters away uni... |
const NORMALIZE_ERASING_LATE_BOUND_REGIONS: &str = "rustc_middle::ty::normalize_erasing_regions::<impl rustc_middle::ty::context::TyCtxt>::normalize_erasing_late_bound_regions";
if let Some(index) = stack.find(NORMALIZE_ERASING_LATE_BOUND_REGIONS) {
stack = &stack[..index + NORMALIZE_ERASI... | {
stack = &stack[..index + SUBST_AND_NORMALIZE_ERASING_REGIONS.len()];
} | conditional_block |
filter_profile.rs | #!/bin/bash
#![forbid(unsafe_code)]/* This line is ignored by bash
# This block is ignored by rustc
pushd $(dirname "$0")/../
source scripts/config.sh
RUSTC="$(pwd)/build/bin/cg_clif"
popd
PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0
#*/
//! This program filters away uni... | if!stack.contains("rustc_codegen_cranelift") {
continue;
}
if stack.contains("rustc_mir::monomorphize::partitioning::collect_and_partition_mono_items")
|| stack.contains("rustc_incremental::assert_dep_graph::assert_dep_graph")
|| stack.contains("rustc_symbol_... | {
let profile_name = std::env::var("PROFILE").unwrap();
let output_name = std::env::var("OUTPUT").unwrap();
if profile_name.is_empty() || output_name.is_empty() {
println!("Usage: ./filter_profile.rs <profile in stackcollapse format> <output file>");
std::process::exit(1);
}
let prof... | identifier_body |
fatdb.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
}
/// Itarator over inserted pairs of key values.
pub struct FatDBIterator<'db> {
trie_iterator: TrieDBIterator<'db>,
trie: &'db TrieDB<'db>,
}
impl<'db> FatDBIterator<'db> {
/// Creates new iterator.
pub fn new(trie: &'db TrieDB) -> super::Result<Self> {
Ok(FatDBIterator {
trie_iterator: TrieDBIterator::ne... | {
self.raw.get_with(&key.sha3(), query)
} | identifier_body |
fatdb.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | pub struct FatDB<'db> {
raw: TrieDB<'db>,
}
impl<'db> FatDB<'db> {
/// Create a new trie with the backing database `db` and empty `root`
/// Initialise to the state entailed by the genesis block.
/// This guarantees the trie is built correctly.
pub fn new(db: &'db HashDB, root: &'db H256) -> super::Result<Self> {... |
/// A `Trie` implementation which hashes keys and uses a generic `HashDB` backing database.
/// Additionaly it stores inserted hash-key mappings for later retrieval.
///
/// Use it as a `Trie` or `TrieMut` trait object. | random_line_split |
fatdb.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | <'a>(&'a self) -> super::Result<Box<TrieIterator<Item = TrieItem> + 'a>> {
FatDBIterator::new(&self.raw).map(|iter| Box::new(iter) as Box<_>)
}
fn root(&self) -> &H256 {
self.raw.root()
}
fn contains(&self, key: &[u8]) -> super::Result<bool> {
self.raw.contains(&key.sha3())
}
fn get_with<'a, 'key, Q: Que... | iter | identifier_name |
getat_func.rs | //! # getat_func
//!
//! Split function which returns only the requested item from the created array.
//!
#[cfg(test)]
#[path = "getat_func_test.rs"]
mod getat_func_test;
use envmnt;
pub(crate) fn invoke(function_args: &Vec<String>) -> Vec<String> |
let split_by_char = split_by.chars().next().unwrap();
let value = envmnt::get_or(&env_key, "");
if value.len() > index {
let splitted = value.split(split_by_char);
let splitted_vec: Vec<String> = splitted.map(|str_value| str_value.to_string()).collect();
let value = splitted_vec[... | {
if function_args.len() != 3 {
error!(
"split expects only 3 arguments (environment variable name, split by character, index)"
);
}
let env_key = function_args[0].clone();
let split_by = function_args[1].clone();
let index: usize = match function_args[2].parse() {
... | identifier_body |
getat_func.rs | //! # getat_func
//!
//! Split function which returns only the requested item from the created array.
//!
#[cfg(test)]
#[path = "getat_func_test.rs"]
mod getat_func_test;
use envmnt;
pub(crate) fn invoke(function_args: &Vec<String>) -> Vec<String> {
if function_args.len()!= 3 {
error!(
"split... |
let env_key = function_args[0].clone();
let split_by = function_args[1].clone();
let index: usize = match function_args[2].parse() {
Ok(value) => value,
Err(error) => {
error!("Invalid index value: {}", &error);
return vec![]; // should not get here
}
};
... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.