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 |
|---|---|---|---|---|
atom.rs | use pyo3::prelude::*;
use rayon::prelude::*;
use std::collections::HashMap;
use crate::becke_partitioning;
use crate::bragg;
use crate::bse;
use crate::lebedev;
use crate::radial;
#[pyfunction]
pub fn | (
basis_set: &str,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angular_points: usize,
proton_charges: Vec<i32>,
center_index: usize,
center_coordinates_bohr: Vec<(f64, f64, f64)>,
hardness: usize,
) -> (Vec<(f64, f64, f64)>, Vec<f64>) {
let (alpha_min, alpha_max) =
... | atom_grid_bse | identifier_name |
atom.rs | use pyo3::prelude::*;
use rayon::prelude::*;
use std::collections::HashMap;
use crate::becke_partitioning;
use crate::bragg;
use crate::bse;
use crate::lebedev;
use crate::radial;
#[pyfunction]
pub fn atom_grid_bse(
basis_set: &str,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angula... |
#[pyfunction]
pub fn atom_grid(
alpha_min: HashMap<usize, f64>,
alpha_max: f64,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angular_points: usize,
proton_charges: Vec<i32>,
center_index: usize,
center_coordinates_bohr: Vec<(f64, f64, f64)>,
hardness: usize,
) -> (... | {
let (alpha_min, alpha_max) =
bse::ang_min_and_max(basis_set, proton_charges[center_index] as usize);
atom_grid(
alpha_min,
alpha_max,
radial_precision,
min_num_angular_points,
max_num_angular_points,
proton_charges,
center_index,
center_... | identifier_body |
atom.rs | use pyo3::prelude::*;
use rayon::prelude::*;
use std::collections::HashMap;
use crate::becke_partitioning;
use crate::bragg;
use crate::bse;
use crate::lebedev;
use crate::radial;
#[pyfunction]
pub fn atom_grid_bse(
basis_set: &str,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angula... |
(coordinates, weights)
}
| {
let w_partitioning: Vec<f64> = coordinates
.par_iter()
.map(|c| {
becke_partitioning::partitioning_weight(
center_index,
¢er_coordinates_bohr,
&proton_charges,
*c,
ha... | conditional_block |
atom.rs | use pyo3::prelude::*;
use rayon::prelude::*;
use std::collections::HashMap;
use crate::becke_partitioning;
use crate::bragg;
use crate::bse;
use crate::lebedev;
use crate::radial;
#[pyfunction]
pub fn atom_grid_bse(
basis_set: &str,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angula... | num_angular = lebedev::get_closest_num_angular(num_angular);
if num_angular < min_num_angular_points {
num_angular = min_num_angular_points;
}
}
let (coordinates_angular, weights_angular) = lebedev::angular_grid(num_angular);
let wt = 4.0 * pi... | if r < rb {
num_angular = ((max_num_angular_points as f64) * r / rb) as usize; | random_line_split |
watchdog.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Dawid Ciężarkiewcz <dpc@ucore.info>
//
// 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/LICE... | fn unlock() {
use self::reg::WDOG_unlock_unlock::*;
reg::WDOG.unlock.set_unlock(UnlockSeq1);
reg::WDOG.unlock.set_unlock(UnlockSeq2);
// Enforce one cycle delay
nop();
}
/// Write refresh sequence to refresh watchdog
pub fn refresh() {
use self::reg::WDOG_refresh_refresh::*;
reg::WDOG.refresh.set_refres... | use self::State::*;
unlock();
match state {
Disabled => {
reg::WDOG.stctrlh.set_en(false);
},
Enabled => {
reg::WDOG.stctrlh.set_allowupdate(true);
},
}
}
| identifier_body |
watchdog.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Dawid Ciężarkiewcz <dpc@ucore.info>
//
// 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/LICE... | // limitations under the License.
//! Watchdog for Kinetis SIM module.
use util::support::nop;
#[path="../../util/ioreg.rs"] mod ioreg;
/// Watchdog state
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum State {
Disabled,
Enabled,
}
/// Init watchdog
pub fn init(state : State) {
use self::State::*;
u... | // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and | random_line_split |
watchdog.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Dawid Ciężarkiewcz <dpc@ucore.info>
//
// 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/LICE... | {
use self::reg::WDOG_refresh_refresh::*;
reg::WDOG.refresh.set_refresh(RefreshSeq1);
reg::WDOG.refresh.set_refresh(RefreshSeq2);
}
#[allow(dead_code)]
mod reg {
use volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(WDOG = {
/// Status and Control Register High
0x0 => reg16 stctrlh
{
... | fresh() | identifier_name |
reversi.rs |
use std::io::{Write, BufWriter};
static BOARD_SIZE: usize = 10; // 盤面のコマ+2
#[derive(Debug, Clone)]
pub enum PieceType {
Black,
White,
Sentinel,
Null,
}
fn flip_turn(t: PieceType) -> PieceType {
match t {
PieceType::Black => PieceType::White,
PieceType::White => PieceType::Black,
_ => PieceType::Null,
}
}... | == half && x == half + 1 ||
y == half + 1 && x == half {
v[y].push(PieceType::Black);
} else {
v[y].push(PieceType::Null);
}
}
}
Reversi {
board: v,
turn: PieceType::Black,
}
}
pub fn debug_board(&self) {
let w = super::std::io::stdout();
let mut w = BufWriter::new(w.lock(... | ].push(PieceType::White);
} else if y | conditional_block |
reversi.rs |
use std::io::{Write, BufWriter};
static BOARD_SIZE: usize = 10; // 盤面のコマ+2
#[derive(Debug, Clone)]
pub enum PieceType {
Black,
White,
Sentinel,
Null,
}
fn flip_turn(t: PieceType) -> PieceType {
match t {
PieceType::Black => PieceType::White,
PieceType::White => PieceType::Black,
_ => PieceType::Null,
}
}... | ve(Debug, Clone)]
pub struct Reversi {
board: Vec<Vec<PieceType>>,
pub turn: PieceType,
}
impl Reversi {
pub fn new() -> Self {
let mut v: Vec<Vec<PieceType>> = Vec::new();
let half = (BOARD_SIZE - 2) / 2;
for y in 0..BOARD_SIZE {
v.push(Vec::new());
for x in 0..BOARD_SIZE {
if y == 0 || x == 0 ||
... | = t
}
}
#[deri | identifier_body |
reversi.rs |
use std::io::{Write, BufWriter};
static BOARD_SIZE: usize = 10; // 盤面のコマ+2
#[derive(Debug, Clone)]
pub enum PieceType {
Black,
White,
Sentinel,
Null,
}
fn flip_turn(t: PieceType) -> PieceType {
match t {
PieceType::Black => PieceType::White,
PieceType::White => PieceType::Black,
_ => PieceType::Null,
}
}... | Vec<Vec<PieceType>>,
pub turn: PieceType,
}
impl Reversi {
pub fn new() -> Self {
let mut v: Vec<Vec<PieceType>> = Vec::new();
let half = (BOARD_SIZE - 2) / 2;
for y in 0..BOARD_SIZE {
v.push(Vec::new());
for x in 0..BOARD_SIZE {
if y == 0 || x == 0 ||
y == BOARD_SIZE - 1 || x == BOARD_SIZE - 1 ... | board: | identifier_name |
reversi.rs | use std::io::{Write, BufWriter};
static BOARD_SIZE: usize = 10; // 盤面のコマ+2
#[derive(Debug, Clone)]
pub enum PieceType {
Black,
White,
Sentinel,
Null,
}
fn flip_turn(t: PieceType) -> PieceType {
match t {
PieceType::Black => PieceType::White,
PieceType::White => PieceType::Black,
_ => PieceType::Null,
}
}
|
#[derive(Debug, Clone)]
pub struct Reversi {
board: Vec<Vec<PieceType>>,
pub turn: PieceType,
}
impl Reversi {
pub fn new() -> Self {
let mut v: Vec<Vec<PieceType>> = Vec::new();
let half = (BOARD_SIZE - 2) / 2;
for y in 0..BOARD_SIZE {
v.push(Vec::new());
for x in 0..BOARD_SIZE {
if y == 0 || x ==... | impl PartialEq for PieceType {
fn eq(&self, t: &PieceType) -> bool {
self == t
}
} | random_line_split |
tokens.rs | //* This file is part of the uutils coreutils package.
//*
//* (c) Roman Gafiyatullin <r.gafiyatullin@me.com>
//*
//* For the full copyright and license information, please view the LICENSE
//* file that was distributed with this source code.
//!
//! The following tokens are present in the expr grammar:
//! * integer ... | (strings: &[String]) -> Result<Vec<(usize, Token)>, String> {
let mut tokens_acc = Vec::with_capacity(strings.len());
let mut tok_idx = 1;
for s in strings {
let token_if_not_escaped = match s.as_ref() {
"(" => Token::ParOpen,
")" => Token::ParClose,
"^" => Toke... | strings_to_tokens | identifier_name |
tokens.rs | //* This file is part of the uutils coreutils package.
//*
//* (c) Roman Gafiyatullin <r.gafiyatullin@me.com>
//*
//* For the full copyright and license information, please view the LICENSE
//* file that was distributed with this source code.
//!
//! The following tokens are present in the expr grammar:
//! * integer ... | else {
acc.push((tok_idx, token));
}
}
| {
acc.pop();
acc.push((tok_idx, Token::new_value(s)));
} | conditional_block |
tokens.rs | //* This file is part of the uutils coreutils package.
//*
//* (c) Roman Gafiyatullin <r.gafiyatullin@me.com>
//*
//* For the full copyright and license information, please view the LICENSE
//* file that was distributed with this source code.
//!
//! The following tokens are present in the expr grammar:
//! * integer ... |
}
pub fn strings_to_tokens(strings: &[String]) -> Result<Vec<(usize, Token)>, String> {
let mut tokens_acc = Vec::with_capacity(strings.len());
let mut tok_idx = 1;
for s in strings {
let token_if_not_escaped = match s.as_ref() {
"(" => Token::ParOpen,
")" => Token::ParClo... | {
matches!(*self, Token::ParClose)
} | identifier_body |
tokens.rs | //* This file is part of the uutils coreutils package.
//*
//* (c) Roman Gafiyatullin <r.gafiyatullin@me.com>
//*
//* For the full copyright and license information, please view the LICENSE
//* file that was distributed with this source code.
//!
//! The following tokens are present in the expr grammar:
//! * integer ... | if debug_var == "1" {
println!("EXPR_DEBUG_TOKENS");
for token in tokens_acc {
println!("\t{:?}", token);
}
}
}
}
fn push_token_if_not_escaped(acc: &mut Vec<(usize, Token)>, tok_idx: usize, token: Token, s: &str) {
// Smells heuristics... :(
... | if let Ok(debug_var) = env::var("EXPR_DEBUG_TOKENS") { | random_line_split |
rscope.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 ... | (&self, _: Span, count: uint)
-> Result<Vec<ty::Region>,()> {
Ok(Vec::from_elem(count, self.region.clone()))
}
}
| anon_regions | identifier_name |
rscope.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 ... | } | random_line_split | |
borrowck-borrow-overloaded-auto-deref-mut.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn deref_imm_field(x: Own<Point>) {
let _i = &x.y;
}
fn deref_mut_field1(x: Own<Point>) {
let _i = &mut x.y; //~ ERROR cannot borrow
}
fn deref_mut_field2(mut x: Own<Point>) {
let _i = &mut x.y;
}
fn deref_extend_field<'a>(x: &'a Own<Point>) -> &'a int {
&x.y
}
fn deref_extend_mut_field1<'a>(x: ... | {
&mut self.y
} | identifier_body |
borrowck-borrow-overloaded-auto-deref-mut.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a>(x: &'a mut Own<Point>) {
x.y = 3;
}
fn assign_field4<'a>(x: &'a mut Own<Point>) {
let _p: &mut Point = &mut **x;
x.y = 3; //~ ERROR cannot borrow
}
// FIXME(eddyb) #12825 This shouldn't attempt to call deref_mut.
/*
fn deref_imm_method(x: Own<Point>) {
let _i = x.get();
}
*/
fn deref_mut_method1... | assign_field3 | identifier_name |
borrowck-borrow-overloaded-auto-deref-mut.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn assign_method1<'a>(x: Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method2<'a>(x: &'a Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method3<'a>(x: &'a mut Own<Point>) {
*x.y_mut() = 3;
}
pub fn main() {} |
fn deref_extend_mut_method2<'a>(x: &'a mut Own<Point>) -> &'a mut int {
x.y_mut()
}
| random_line_split |
get.rs | use super::with_path;
use util::*;
use hyper::client::Response;
use hyper::status::StatusCode;
fn with_query<F>(query: &str, f: F) where F: FnOnce(&mut Response) {
with_path(&format!("/get?{}", query), f)
}
fn assert_accepted(query: &str) {
with_query(query, |res| {
let s = read_body_to_string(res);
... | () {
assert_accepted("state=valid&state=foo")
}
}
mod rejects {
use super::assert_rejected;
#[test]
fn invalid() {
assert_rejected("state=foo")
}
#[test]
fn other_keys() {
assert_rejected("valid=valid")
}
#[test]
fn empty() {
assert_rejected(""... | first_valid | identifier_name |
get.rs | use super::with_path;
use util::*;
use hyper::client::Response;
use hyper::status::StatusCode;
fn with_query<F>(query: &str, f: F) where F: FnOnce(&mut Response) {
with_path(&format!("/get?{}", query), f)
}
fn assert_accepted(query: &str) {
with_query(query, |res| {
let s = read_body_to_string(res);
... |
}
mod rejects {
use super::assert_rejected;
#[test]
fn invalid() {
assert_rejected("state=foo")
}
#[test]
fn other_keys() {
assert_rejected("valid=valid")
}
#[test]
fn empty() {
assert_rejected("")
}
#[test]
fn second_valid() {
assert... | {
assert_accepted("state=valid&state=foo")
} | identifier_body |
get.rs | use super::with_path;
use util::*;
use hyper::client::Response;
use hyper::status::StatusCode;
fn with_query<F>(query: &str, f: F) where F: FnOnce(&mut Response) {
with_path(&format!("/get?{}", query), f)
}
fn assert_accepted(query: &str) {
with_query(query, |res| {
let s = read_body_to_string(res);
... | #[test]
fn invalid() {
assert_rejected("state=foo")
}
#[test]
fn other_keys() {
assert_rejected("valid=valid")
}
#[test]
fn empty() {
assert_rejected("")
}
#[test]
fn second_valid() {
assert_rejected("state=foo&state=valid")
}
} | use super::assert_rejected;
| random_line_split |
record_type.rs | use crate::library;
#[derive(PartialEq, Eq)]
pub enum | {
/// Boxed record that use g_boxed_copy, g_boxed_free.
/// Must have glib_get_type function
AutoBoxed,
/// Boxed record with custom copy/free functions
Boxed,
/// Referencecounted record
Refcounted,
//TODO: detect and generate direct records
//Direct,
}
impl RecordType {
pub f... | RecordType | identifier_name |
record_type.rs | use crate::library;
#[derive(PartialEq, Eq)]
pub enum RecordType {
/// Boxed record that use g_boxed_copy, g_boxed_free.
/// Must have glib_get_type function
AutoBoxed,
/// Boxed record with custom copy/free functions
Boxed,
/// Referencecounted record
Refcounted,
//TODO: detect and gen... |
if has_ref && has_unref {
RecordType::Refcounted
} else if has_copy && has_free {
RecordType::Boxed
} else {
RecordType::AutoBoxed
}
}
}
| {
let mut has_copy = false;
let mut has_free = false;
let mut has_ref = false;
let mut has_unref = false;
let mut has_destroy = false;
for func in &record.functions {
match &func.name[..] {
"copy" => has_copy = true,
"free" => h... | identifier_body |
record_type.rs | use crate::library;
#[derive(PartialEq, Eq)]
pub enum RecordType {
/// Boxed record that use g_boxed_copy, g_boxed_free.
/// Must have glib_get_type function
AutoBoxed,
/// Boxed record with custom copy/free functions
Boxed,
/// Referencecounted record
Refcounted,
//TODO: detect and gen... | } | } else {
RecordType::AutoBoxed
}
} | random_line_split |
lib.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
//!Load Cifar10
//!
//!Cifar10 Simple Loader
//!
//!Use image crate in CifarImage.
//!
//!##Examples
//!
//! Download CIFAR-10 binary version and extract.
//!
//!```
//!# extern crate cifar_10_loader;
//!# use cifar_10_l... | mod test; | random_line_split | |
complex_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use rustorm::query::Query;
use rustorm::query::{Filter,Equality};
use rustorm::dao::{Dao,IsDao};
use gen::bazaar::Product;
use gen::bazaar::product;
use gen::bazaar::Photo;
use gen::bazaar::photo;
use gen::bazaar::Review;
use g... | )
.GROUP_BY(&[category::name])
.HAVING(COUNT(&"*").GT(&1))
.HAVING(COUNT(&product::product_id).GT(&1))
.ORDER_BY(&[product::name.ASC(), product::created.DESC()])
.build(db.as_ref());
let expected = "
SELECT *
FROM bazaar.product
LEFT JOIN bazaar.product_categor... | random_line_split | |
complex_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use rustorm::query::Query;
use rustorm::query::{Filter,Equality};
use rustorm::dao::{Dao,IsDao};
use gen::bazaar::Product;
use gen::bazaar::product;
use gen::bazaar::Photo;
use gen::bazaar::photo;
use gen::bazaar::Review;
use g... | )
.GROUP_BY(&[category::name])
.HAVING(COUNT(&"*").GT(&1))
.HAVING(COUNT(&product::product_id).GT(&1))
.ORDER_BY(&[product::name.ASC(), product::created.DESC()])
.build(db.as_ref());
let expected = "
SELECT *
FROM bazaar.product
LEFT JOIN bazaar.product_categor... | {
let mut pool = ManagedPool::init("postgres://postgres:p0stgr3s@localhost/bazaar_v8",1).unwrap();
let db = pool.connect().unwrap();
let frag = SELECT_ALL().FROM(&bazaar::product)
.LEFT_JOIN(bazaar::product_category
.ON(
product_category::product_id.EQ(&product::product_id)
... | identifier_body |
complex_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use rustorm::query::Query;
use rustorm::query::{Filter,Equality};
use rustorm::dao::{Dao,IsDao};
use gen::bazaar::Product;
use gen::bazaar::product;
use gen::bazaar::Photo;
use gen::bazaar::photo;
use gen::bazaar::Review;
use g... | (){
let mut pool = ManagedPool::init("postgres://postgres:p0stgr3s@localhost/bazaar_v8",1).unwrap();
let db = pool.connect().unwrap();
let frag = SELECT_ALL().FROM(&bazaar::product)
.LEFT_JOIN(bazaar::product_category
.ON(
product_category::product_id.EQ(&product::product_id)
... | main | identifier_name |
atomic_usize.rs | use std::cell::UnsafeCell;
use std::fmt;
use std::ops;
/// `AtomicUsize` providing an additional `load_unsync` function.
pub(crate) struct AtomicUsize {
inner: UnsafeCell<std::sync::atomic::AtomicUsize>,
}
unsafe impl Send for AtomicUsize {}
unsafe impl Sync for AtomicUsize {}
impl AtomicUsize {
pub(crate) c... |
pub(crate) fn with_mut<R>(&mut self, f: impl FnOnce(&mut usize) -> R) -> R {
// safety: we have mutable access
f(unsafe { (*self.inner.get()).get_mut() })
}
}
impl ops::Deref for AtomicUsize {
type Target = std::sync::atomic::AtomicUsize;
fn deref(&self) -> &Self::Target {
// ... | } | random_line_split |
atomic_usize.rs | use std::cell::UnsafeCell;
use std::fmt;
use std::ops;
/// `AtomicUsize` providing an additional `load_unsync` function.
pub(crate) struct AtomicUsize {
inner: UnsafeCell<std::sync::atomic::AtomicUsize>,
}
unsafe impl Send for AtomicUsize {}
unsafe impl Sync for AtomicUsize {}
impl AtomicUsize {
pub(crate) c... |
pub(crate) fn with_mut<R>(&mut self, f: impl FnOnce(&mut usize) -> R) -> R {
// safety: we have mutable access
f(unsafe { (*self.inner.get()).get_mut() })
}
}
impl ops::Deref for AtomicUsize {
type Target = std::sync::atomic::AtomicUsize;
fn deref(&self) -> &Self::Target {
//... | {
*(*self.inner.get()).get_mut()
} | identifier_body |
atomic_usize.rs | use std::cell::UnsafeCell;
use std::fmt;
use std::ops;
/// `AtomicUsize` providing an additional `load_unsync` function.
pub(crate) struct AtomicUsize {
inner: UnsafeCell<std::sync::atomic::AtomicUsize>,
}
unsafe impl Send for AtomicUsize {}
unsafe impl Sync for AtomicUsize {}
impl AtomicUsize {
pub(crate) c... | (&mut self) -> &mut Self::Target {
// safety: we hold `&mut self`
unsafe { &mut *self.inner.get() }
}
}
impl fmt::Debug for AtomicUsize {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(fmt)
}
}
| deref_mut | identifier_name |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
#[cfg(feature = "js_backtrace")]
use backtrace::Backtrace;
... | (cx: *mut JSContext, global: &GlobalScope, result: Error) {
#[cfg(feature = "js_backtrace")]
{
capture_stack!(in(cx) let stack);
let js_stack = stack.and_then(|s| s.as_string(None));
let rust_stack = Backtrace::new();
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
*backt... | throw_dom_exception | identifier_name |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
#[cfg(feature = "js_backtrace")]
use backtrace::Backtrace;
... |
impl Error {
/// Convert this error value to a JS value, consuming it in the process.
pub unsafe fn to_jsval(
self,
cx: *mut JSContext,
global: &GlobalScope,
rval: MutableHandleValue,
) {
assert!(!JS_IsExceptionPending(cx));
throw_dom_exception(cx, global, s... | {
debug_assert!(!JS_IsExceptionPending(cx));
let error = format!(
"\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id)
);
throw_type_error(cx, &error);
} | identifier_body |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
#[cfg(feature = "js_backtrace")]
use backtrace::Backtrace;
... |
let filename = {
let filename = (*report)._base.filename as *const u8;
if!filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
let filename = from_raw_parts(filename, length as usize);
String::from_utf... | {
return None;
} | conditional_block |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
#[cfg(feature = "js_backtrace")]
use backtrace::Backtrace;
... | let filename = from_raw_parts(filename, length as usize);
String::from_utf8_lossy(filename).into_owned()
} else {
"none".to_string()
}
};
let lineno = (*report)._base.lineno;
let column = (*report)._base.column;
le... | let filename = (*report)._base.filename as *const u8;
if !filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap(); | random_line_split |
collection.rs | //! This module contains code to parse all supported collection formats.
use std::fs::File;
use std::io::Read;
use crate::level::*;
use crate::util::*;
enum FileFormat {
Ascii,
Xml,
}
/// A collection of levels. This type contains logic for parsing a collection file. Other than
/// that, it is simply a list... |
let level_strings: Vec<_> = content
.split(EMPTY_LINE)
.map(|x| x.trim_matches(&eol))
.filter(|x|!x.is_empty())
.collect();
let name = level_strings[0].lines().next().unwrap();
let description = level_strings[0]
.splitn(1, &eol)
... | let mut file = file;
// Read the collection’s file
let mut content = "".to_string();
file.read_to_string(&mut content)?; | random_line_split |
collection.rs | //! This module contains code to parse all supported collection formats.
use std::fs::File;
use std::io::Read;
use crate::level::*;
use crate::util::*;
enum FileFormat {
Ascii,
Xml,
}
/// A collection of levels. This type contains logic for parsing a collection file. Other than
/// that, it is simply a list... | self) -> Option<&str> {
match self.description {
Some(ref x) => Some(&x),
None => None,
}
}
pub fn first_level(&self) -> &Level {
&self.levels[0]
}
/// Get all levels.
pub fn levels(&self) -> &[Level] {
self.levels.as_ref()
}
pub fn ... | scription(& | identifier_name |
collection.rs | //! This module contains code to parse all supported collection formats.
use std::fs::File;
use std::io::Read;
use crate::level::*;
use crate::util::*;
enum FileFormat {
Ascii,
Xml,
}
/// A collection of levels. This type contains logic for parsing a collection file. Other than
/// that, it is simply a list... | },
Ok(Event::Text(ref e)) => match state {
State::Nothing => {}
State::Line if!parse_levels => {}
_ => {
let s = e.unescape_and_decode(&reader).unwrap();
match state {
... | conditional_block | |
chain.rs | extern crate futures;
extern crate tokio_core;
use std::net::TcpStream;
use std::thread;
use std::io::{Write, Read};
use futures::Future;
use futures::stream::Stream;
use tokio_core::io::read_to_end;
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;
macro_rules! t {
($e:expr) => (match $e {
... | () {
let mut l = t!(Core::new());
let srv = t!(TcpListener::bind(&t!("127.0.0.1:0".parse()), &l.handle()));
let addr = t!(srv.local_addr());
let t = thread::spawn(move || {
let mut s1 = TcpStream::connect(&addr).unwrap();
s1.write_all(b"foo ").unwrap();
let mut s2 = TcpStream::c... | chain_clients | identifier_name |
chain.rs | extern crate futures;
extern crate tokio_core;
use std::net::TcpStream;
use std::thread;
use std::io::{Write, Read};
use futures::Future;
use futures::stream::Stream;
use tokio_core::io::read_to_end;
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;
macro_rules! t {
($e:expr) => (match $e {
... | t.join().unwrap();
assert_eq!(data, b"foo bar baz");
} | random_line_split | |
chain.rs | extern crate futures;
extern crate tokio_core;
use std::net::TcpStream;
use std::thread;
use std::io::{Write, Read};
use futures::Future;
use futures::stream::Stream;
use tokio_core::io::read_to_end;
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;
macro_rules! t {
($e:expr) => (match $e {
... |
read_to_end(a.chain(b).chain(c), Vec::new())
});
let (_, data) = t!(l.run(copied));
t.join().unwrap();
assert_eq!(data, b"foo bar baz");
}
| {
let mut l = t!(Core::new());
let srv = t!(TcpListener::bind(&t!("127.0.0.1:0".parse()), &l.handle()));
let addr = t!(srv.local_addr());
let t = thread::spawn(move || {
let mut s1 = TcpStream::connect(&addr).unwrap();
s1.write_all(b"foo ").unwrap();
let mut s2 = TcpStream::conn... | identifier_body |
vmem_serialize.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use crate::otp::lc_state::LcSecded;
use crate::util::present::Present;
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt::Write;
use anyhow::{anyh... |
}
let word_with_ecc = secded.ecc_encode(word)?;
let mut word_str = String::new();
for byte in word_with_ecc.iter().rev() {
write!(word_str, "{:02x}", byte)?;
}
output.push(format!(
"{} // {:06x}: {}",
... | {
word_annotation.push(annotations[idx].clone());
} | conditional_block |
vmem_serialize.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use crate::otp::lc_state::LcSecded;
use crate::util::present::Present;
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt::Write;
use anyhow::{anyh... |
/// Add an item to this partition.
pub fn push_item(&mut self, item: VmemItem) {
self.items.push(item);
}
/// Produces a tuple containing OTP HEX lines with annotations.
fn write_to_buffer(&self, keys: &HashMap<String, Vec<u8>>) -> Result<(Vec<u8>, Vec<String>)> {
if self.size % 8... | {
self.size = size;
} | identifier_body |
vmem_serialize.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details. | // SPDX-License-Identifier: Apache-2.0
use crate::otp::lc_state::LcSecded;
use crate::util::present::Present;
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt::Write;
use anyhow::{anyhow, bail, ensure, Result};
use zerocopy::AsBytes;
enum ItemType {
Bytes(Vec<u8>),
Unvalued(usize),
}
... | random_line_split | |
vmem_serialize.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use crate::otp::lc_state::LcSecded;
use crate::util::present::Present;
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt::Write;
use anyhow::{anyh... | (&self) -> usize {
match &self.value {
ItemType::Bytes(b) => b.len(),
ItemType::Unvalued(size) => *size,
}
}
}
pub type DigestIV = u64;
pub type DigestCnst = u128;
/// Digest information for an OTP partition.
#[derive(PartialEq)]
pub enum DigestType {
Unlocked,
Soft... | size | identifier_name |
event_loop.rs | use std::sync::{Arc, Condvar, Mutex};
use std::thread::spawn;
use std::time::{Duration, Instant};
use super::schedule_queue::*;
use super::scheduler::*;
#[derive(Clone)]
pub struct EventLoop {
queue: Arc<(Mutex<ScheduleQueue<Box<Action + Send>>>, Condvar)>,
}
impl EventLoop {
/// Creates a new EventLoop
p... | () -> Self {
let queue = Arc::new((Mutex::new(ScheduleQueue::new()), Condvar::new()));
let scheduler = EventLoop { queue: queue.clone() };
spawn(move || {
loop {
let mut action = dequeue(&queue);
action.invoke();
}
});
sc... | new | identifier_name |
event_loop.rs | use std::sync::{Arc, Condvar, Mutex};
use std::thread::spawn;
use std::time::{Duration, Instant};
use super::schedule_queue::*;
use super::scheduler::*;
#[derive(Clone)]
pub struct EventLoop {
queue: Arc<(Mutex<ScheduleQueue<Box<Action + Send>>>, Condvar)>,
}
impl EventLoop {
/// Creates a new EventLoop
p... |
}
}
| {
action();
} | conditional_block |
event_loop.rs | use std::sync::{Arc, Condvar, Mutex};
use std::thread::spawn;
use std::time::{Duration, Instant};
use super::schedule_queue::*;
use super::scheduler::*;
#[derive(Clone)]
pub struct EventLoop {
queue: Arc<(Mutex<ScheduleQueue<Box<Action + Send>>>, Condvar)>,
}
impl EventLoop {
/// Creates a new EventLoop
p... | } else {
queue.enqueue(record);
continue;
}
}
} else {
queue = cvar.wait(queue).unwrap();
}
}
}
impl ParallelScheduler for EventLoop {
fn schedule<F>(&self, func: F, delay: Duration)
where F:... | let r = cvar.wait_timeout(queue, timeout).unwrap();
queue = r.0;
if r.1.timed_out() {
return record.0; | random_line_split |
event_loop.rs | use std::sync::{Arc, Condvar, Mutex};
use std::thread::spawn;
use std::time::{Duration, Instant};
use super::schedule_queue::*;
use super::scheduler::*;
#[derive(Clone)]
pub struct EventLoop {
queue: Arc<(Mutex<ScheduleQueue<Box<Action + Send>>>, Condvar)>,
}
impl EventLoop {
/// Creates a new EventLoop
p... |
}
| {
if let Some(action) = self.take() {
action();
}
} | identifier_body |
builder.rs | //! Cretonne instruction builder.
//!
//! A `Builder` provides a convenient interface for inserting instructions into a Cretonne
//! function. Many of its methods are generated from the meta language instruction definitions.
use ir;
use ir::types;
use ir::{InstructionData, DataFlowGraph};
use ir::{Opcode, Type, Inst, ... |
(self.inst, self.dfg)
}
}
#[cfg(test)]
mod tests {
use cursor::{Cursor, FuncCursor};
use ir::{Function, InstBuilder, ValueDef};
use ir::types::*;
use ir::condcodes::*;
#[test]
fn types() {
let mut func = Function::new();
let ebb0 = func.dfg.make_ebb();
let... | {
// The old result values were either detached or non-existent.
// Construct new ones.
self.dfg.make_inst_results(self.inst, ctrl_typevar);
} | conditional_block |
builder.rs | //! Cretonne instruction builder.
//!
//! A `Builder` provides a convenient interface for inserting instructions into a Cretonne
//! function. Many of its methods are generated from the meta language instruction definitions.
use ir;
use ir::types;
use ir::{InstructionData, DataFlowGraph};
use ir::{Opcode, Type, Inst, ... | inst = dfg.make_inst(data);
// Make an `Interator<Item = Option<Value>>`.
let ru = self.reuse.as_ref().iter().cloned();
dfg.make_inst_results_reusing(inst, ctrl_typevar, ru);
}
(inst, self.inserter.insert_built_inst(inst, ctrl_typevar))
}
}
/// Instru... | {
let dfg = self.inserter.data_flow_graph_mut(); | random_line_split |
builder.rs | //! Cretonne instruction builder.
//!
//! A `Builder` provides a convenient interface for inserting instructions into a Cretonne
//! function. Many of its methods are generated from the meta language instruction definitions.
use ir;
use ir::types;
use ir::{InstructionData, DataFlowGraph};
use ir::{Opcode, Type, Inst, ... | (&self) -> &DataFlowGraph {
self.inserter.data_flow_graph()
}
fn data_flow_graph_mut(&mut self) -> &mut DataFlowGraph {
self.inserter.data_flow_graph_mut()
}
fn build(mut self, data: InstructionData, ctrl_typevar: Type) -> (Inst, &'f mut DataFlowGraph) {
let inst;
{
... | data_flow_graph | identifier_name |
cursor.rs | extern crate sdl2;
use std::env;
use std::path::Path;
use sdl2::event::Event;
use sdl2::image::{LoadSurface, InitFlag};
use sdl2::keyboard::Keycode;
use sdl2::mouse::Cursor;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::surface::Surface;
pub fn run(png: &Path) -> Result<(), String> {
let sdl_context = ... | () -> Result<(), String> {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run /path/to/image.(png|jpg)")
} else {
run(Path::new(&args[1]))?;
}
Ok(())
}
| main | identifier_name |
cursor.rs | extern crate sdl2;
use std::env;
use std::path::Path; | use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::surface::Surface;
pub fn run(png: &Path) -> Result<(), String> {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let _image_context = sdl2::image::init(InitFlag::PNG | InitFlag::JPG)?;
let window = video_subsystem.win... | use sdl2::event::Event;
use sdl2::image::{LoadSurface, InitFlag};
use sdl2::keyboard::Keycode;
use sdl2::mouse::Cursor; | random_line_split |
cursor.rs | extern crate sdl2;
use std::env;
use std::path::Path;
use sdl2::event::Event;
use sdl2::image::{LoadSurface, InitFlag};
use sdl2::keyboard::Keycode;
use sdl2::mouse::Cursor;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::surface::Surface;
pub fn run(png: &Path) -> Result<(), String> {
let sdl_context = ... | {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run /path/to/image.(png|jpg)")
} else {
run(Path::new(&args[1]))?;
}
Ok(())
} | identifier_body | |
cursor.rs | extern crate sdl2;
use std::env;
use std::path::Path;
use sdl2::event::Event;
use sdl2::image::{LoadSurface, InitFlag};
use sdl2::keyboard::Keycode;
use sdl2::mouse::Cursor;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::surface::Surface;
pub fn run(png: &Path) -> Result<(), String> {
let sdl_context = ... |
}
}
}
Ok(())
}
fn main() -> Result<(), String> {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run /path/to/image.(png|jpg)")
} else {
run(Path::new(&args[1]))?;
}
Ok(())
}
| {} | conditional_block |
thrift.rs | // Copyright 2019-2020 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
#![allow(dead_code)]
use crate::codec::ParseError;
pub const STOP: u8 = 0;
pub const VOID: u8 = 1;
pub const BOOL: u8 = 2;
pub const BYTE: u8 = 3;
pub const DOUBLE: u8 = 4;
pub const I... | (&self) -> usize {
self.buffer.len()
}
/// add protocol version to buffer
pub fn protocol_header(&mut self) -> &Self {
self.buffer.extend_from_slice(&[128, 1, 0, 1]);
self
}
/// write the framed length to the buffer
#[inline]
pub fn frame(&mut self) -> &Self {
... | len | identifier_name |
thrift.rs | // Copyright 2019-2020 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
#![allow(dead_code)]
use crate::codec::ParseError;
pub const STOP: u8 = 0;
pub const VOID: u8 = 1;
pub const BOOL: u8 = 2;
pub const BYTE: u8 = 3;
pub const DOUBLE: u8 = 4;
pub const I... | }
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn ping() {
let mut buffer = ThriftBuffer::new();
// new buffer has 4 bytes to hold framing later
assert_eq!(buffer.len(), 4);
assert_eq!(buffer.as_bytes(), &[0, 0, 0, 0]);
buffer.protocol_header();
ass... | Err(ParseError::Incomplete) | random_line_split |
thrift.rs | // Copyright 2019-2020 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
#![allow(dead_code)]
use crate::codec::ParseError;
pub const STOP: u8 = 0;
pub const VOID: u8 = 1;
pub const BOOL: u8 = 2;
pub const BYTE: u8 = 3;
pub const DOUBLE: u8 = 4;
pub const I... | else {
Err(ParseError::Incomplete)
}
}
None => Err(ParseError::Unknown),
}
} else {
Err(ParseError::Incomplete)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn ping() {
let mut buffer = ThriftBuffer::new();
... | {
Ok(())
} | conditional_block |
thrift.rs | // Copyright 2019-2020 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
#![allow(dead_code)]
use crate::codec::ParseError;
pub const STOP: u8 = 0;
pub const VOID: u8 = 1;
pub const BOOL: u8 = 2;
pub const BYTE: u8 = 3;
pub const DOUBLE: u8 = 4;
pub const I... |
/// add protocol version to buffer
pub fn protocol_header(&mut self) -> &Self {
self.buffer.extend_from_slice(&[128, 1, 0, 1]);
self
}
/// write the framed length to the buffer
#[inline]
pub fn frame(&mut self) -> &Self {
let bytes = self.buffer.len() - 4;
for ... | {
self.buffer.len()
} | identifier_body |
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 http://mozilla.org/MPL/2.0/. */
use selectors;
use servo_arc::Arc;
use style;
use style::applicable_declarations::ApplicableDeclarationBlock;
use ... | if cfg!(rustc_has_pr45225) { 40 } else { 48 });
size_of_test!(test_size_of_specified_image_layer, specified::image::ImageLayer,
if cfg!(rustc_has_pr45225) { 40 } else { 48 }); | random_line_split | |
main.rs | use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
... | let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
// ANCHOR_END: ch19
println!("You guessed: {}", guess);
// --snip--
// ANCHOR_END: here
match guess.cmp(&secret_number) {
Ordering::Less => ... |
// ANCHOR: ch19 | random_line_split |
main.rs | use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() | let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
// ANCHOR_END: ch19
println!("You guessed: {}", guess);
// --snip--
// ANCHOR_END: here
match guess.cmp(&secret_number) {
Ordering::Less => ... | {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
// ANCHOR: here
// --snip--
io::stdin(... | identifier_body |
main.rs | use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn | () {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
// ANCHOR: here
// --snip--
io::std... | main | identifier_name |
fuzzing.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
constants,
peer::Peer,
protocols::wire::{
handshake::v1::{MessagingProtocolVersion, SupportedProtocols},
messaging::v1::{NetworkMessage, NetworkMessageSink},
},
testutils::fake_socket::Re... | // for all network notifs to drain out and finish.
drop(peer_reqs_tx);
peer_notifs_rx.collect::<Vec<_>>().await;
});
}
#[test]
fn test_peer_fuzzers() {
let mut value_gen = ValueGenerator::deterministic();
for _ in 0..50 {
let corpus = generate_corpus(&mut value_gen);
... | // ACK the "remote" d/c and drop our handle to the Peer actor. Then wait | random_line_split |
fuzzing.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
constants,
peer::Peer,
protocols::wire::{
handshake::v1::{MessagingProtocolVersion, SupportedProtocols},
messaging::v1::{NetworkMessage, NetworkMessageSink},
},
testutils::fake_socket::Re... | buf
}
/// Fuzz the `Peer` actor's inbound message handling.
///
/// For each fuzzer iteration, we spin up a new `Peer` actor and pipe the raw
/// fuzzer data into it. This mostly tests that the `Peer` inbound message handling
/// doesn't panic or leak memory when reading, deserializing, and handling messages
/// ... | {
let network_msgs = gen.generate(vec(any::<NetworkMessage>(), 1..20));
let (write_socket, mut read_socket) = MemorySocket::new_pair();
let mut writer = NetworkMessageSink::new(write_socket, constants::MAX_FRAME_SIZE, None);
// Write the `NetworkMessage`s to a fake socket
let f_send = async move {... | identifier_body |
fuzzing.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
constants,
peer::Peer,
protocols::wire::{
handshake::v1::{MessagingProtocolVersion, SupportedProtocols},
messaging::v1::{NetworkMessage, NetworkMessageSink},
},
testutils::fake_socket::Re... | () {
let mut value_gen = ValueGenerator::deterministic();
for _ in 0..50 {
let corpus = generate_corpus(&mut value_gen);
fuzz(&corpus);
}
}
| test_peer_fuzzers | identifier_name |
owned_slice.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/. */
#![allow(unsafe_code)]
//! A replacement for `Box<[T]>` that cbindgen can understand.
use malloc_size_of::{Mall... | (mut b: Box<[T]>) -> Self {
let len = b.len();
let ptr = unsafe { NonNull::new_unchecked(b.as_mut_ptr()) };
mem::forget(b);
Self {
len,
ptr,
_phantom: PhantomData,
}
}
}
impl<T> From<Vec<T>> for OwnedSlice<T> {
#[inline]
fn from(b:... | from | identifier_name |
owned_slice.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/. */
#![allow(unsafe_code)]
//! A replacement for `Box<[T]>` that cbindgen can understand.
use malloc_size_of::{Mall... |
}
impl<T> From<Box<[T]>> for OwnedSlice<T> {
#[inline]
fn from(mut b: Box<[T]>) -> Self {
let len = b.len();
let ptr = unsafe { NonNull::new_unchecked(b.as_mut_ptr()) };
mem::forget(b);
Self {
len,
ptr,
_phantom: PhantomData,
}
}
... | {
unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
} | identifier_body |
owned_slice.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 malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::ptr::NonNull;
use std::{fmt, iter, mem, slice};
use to_shmem::{SharedMemoryBuilder, ToShmem};
/// A struct that basically replaces a `Box<[T]>`, but which cbindgen can
/// u... | #![allow(unsafe_code)]
//! A replacement for `Box<[T]>` that cbindgen can understand.
| random_line_split |
owned_slice.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/. */
#![allow(unsafe_code)]
//! A replacement for `Box<[T]>` that cbindgen can understand.
use malloc_size_of::{Mall... |
}
}
unsafe impl<T: Sized + Send> Send for OwnedSlice<T> {}
unsafe impl<T: Sized + Sync> Sync for OwnedSlice<T> {}
impl<T: Clone> Clone for OwnedSlice<T> {
#[inline]
fn clone(&self) -> Self {
Self::from_slice(&**self)
}
}
impl<T: fmt::Debug> fmt::Debug for OwnedSlice<T> {
fn fmt(&self, fo... | {
let _ = mem::replace(self, Self::default()).into_vec();
} | conditional_block |
lib.rs | #[macro_use]
extern crate prodbg_api;
use prodbg_api::*;
struct Line {
opcode: String,
regs_write: String,
regs_read: String,
address: u64,
}
///
/// Breakpoint
///
struct Breakpoint {
address: u64,
}
///
/// Holds colors use for the disassembly view. This should be possible to configure later o... |
// need to fetch more data here also
if pos >= self.lines.len() as i32 {
return;
}
self.cursor = self.lines[pos as usize].address;
return;
}
}
}
fn render_arrow(ui: &Ui, pos_x: f32, pos_y:... | {
return;
} | conditional_block |
lib.rs | #[macro_use]
extern crate prodbg_api;
use prodbg_api::*;
struct Line {
opcode: String,
regs_write: String,
regs_read: String,
address: u64,
}
///
/// Breakpoint
///
struct Breakpoint {
address: u64,
}
///
/// Holds colors use for the disassembly view. This should be possible to configure later o... | (&mut self, writer: &mut Writer) {
let address = self.cursor;
for i in (0..self.breakpoints.len()).rev() {
if self.breakpoints[i].address == address {
writer.event_begin(EVENT_DELETE_BREAKPOINT as u16);
writer.write_u64("address", address);
wr... | toggle_breakpoint | identifier_name |
lib.rs | #[macro_use]
extern crate prodbg_api;
| opcode: String,
regs_write: String,
regs_read: String,
address: u64,
}
///
/// Breakpoint
///
struct Breakpoint {
address: u64,
}
///
/// Holds colors use for the disassembly view. This should be possible to configure later on.
///
/*
struct Colors {
breakpoint: Color,
step_cursor: Color,
... | use prodbg_api::*;
struct Line { | random_line_split |
lib.rs | #[macro_use]
extern crate prodbg_api;
use prodbg_api::*;
struct Line {
opcode: String,
regs_write: String,
regs_read: String,
address: u64,
}
///
/// Breakpoint
///
struct Breakpoint {
address: u64,
}
///
/// Holds colors use for the disassembly view. This should be possible to configure later o... | {
define_view_plugin!(PLUGIN, b"Disassembly2 View", DisassemblyView);
plugin_handler.register_view(&PLUGIN);
} | identifier_body | |
account.rs | extern crate meg;
extern crate log;
use log::*;
use std::env;
use std::clone::Clone;
use turbo::util::{CliResult, Config};
use self::meg::ops::meg_account_create as Act;
use self::meg::ops::meg_account_show as Show;
#[derive(RustcDecodable, Clone)]
pub struct Options {
pub flag_create: String,
pub flag_show: boo... |
} | }
}
return Ok(None) | random_line_split |
account.rs | extern crate meg;
extern crate log;
use log::*;
use std::env;
use std::clone::Clone;
use turbo::util::{CliResult, Config};
use self::meg::ops::meg_account_create as Act;
use self::meg::ops::meg_account_show as Show;
#[derive(RustcDecodable, Clone)]
pub struct | {
pub flag_create: String,
pub flag_show: bool,
pub flag_verbose: bool,
}
pub const USAGE: &'static str = "
Usage:
meg account [options]
Options:
-h, --help Print this message
--create EMAIL Provide an email to create a new account
--show View your account d... | Options | identifier_name |
lib.rs | #![feature(core)]
/// Generate a new iterable witn a list comprehension. This macro tries to follow the syntax of | /// Python's list comprehensions. This is a very flexable macro that allows the generation of any
/// iterable that implements `std::iter::FromIterator`. The resulting type will be determined by
/// the type of the variable that you are attempting to assign to. You can create a `Vec`:
///
/// ```ignore
/// let x: Vec<i... | random_line_split | |
executive.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... | use machine::EthereumMachine as Machine;
#[derive(Debug, PartialEq, Clone)]
struct CallCreate {
data: Bytes,
destination: Option<Address>,
gas_limit: U256,
value: U256
}
impl From<ethjson::vm::Call> for CallCreate {
fn from(c: ethjson::vm::Call) -> Self {
let dst: Option<ethjson::hash::Address> = c.destination... | use rlp::RlpStream;
use hash::keccak; | random_line_split |
executive.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... | ;
macro_rules! try_fail {
($e: expr) => {
match $e {
Ok(x) => x,
Err(e) => {
let msg = format!("Internal error: {}", e);
fail_unless(false, &msg);
continue
}
}
}
}
let out_of_gas = vm.out_of_gas();
let mut state = get_temp_state();
state.populate_from(From::fro... | {
failed.push(format!("[{}] {}: {}", vm_type, name, s));
fail = true
} | conditional_block |
executive.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, address: &Address) -> vm::Result<usize> {
self.ext.extcodesize(address)
}
fn log(&mut self, topics: Vec<H256>, data: &[u8]) -> vm::Result<()> {
self.ext.log(topics, data)
}
fn ret(self, gas: &U256, data: &ReturnData, apply_state: bool) -> Result<U256, vm::Error> {
self.ext.ret(gas, data, apply_state... | extcodesize | identifier_name |
executive.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... |
fn env_info(&self) -> &EnvInfo {
self.ext.env_info()
}
fn depth(&self) -> usize {
0
}
fn is_static(&self) -> bool {
false
}
fn inc_sstore_clears(&mut self) {
self.ext.inc_sstore_clears()
}
}
fn do_json_test(json_data: &[u8]) -> Vec<String> {
let vms = VMType::all();
vms
.iter()
.flat_map(|vm... | {
self.ext.schedule()
} | identifier_body |
300-custom-types.rs | #[derive(Debug)]
struct Person {
name: String,
age: u8,
}
// A unit struct
struct Unit;
// A tuple struct
struct | (i32, f32);
// A struct with two fields
struct Point {
x: f32,
y: f32,
}
// Structs can be reused as fields of another struct
#[allow(dead_code)]
struct Rectangle {
// A rectangle can be specified by where the top left and bottom right
// corners are in space.
top_left: Point,
bottom_right: Po... | Pair | identifier_name |
300-custom-types.rs | #[derive(Debug)]
struct Person {
name: String,
age: u8,
}
// A unit struct
struct Unit;
// A tuple struct
struct Pair(i32, f32);
// A struct with two fields
struct Point {
x: f32,
y: f32,
}
// Structs can be reused as fields of another struct
#[allow(dead_code)]
struct Rectangle {
// A rectangle... |
// Access the fields of the point
println!("point coordinates: ({}, {})", point.x, point.y);
// Make a new point by using struct update syntax to use the fields of our
// other one
let bottom_right = Point { x: 5.2,..point };
// `bottom_right.y` will be the same as `point.y` because we used t... | let point: Point = Point { x: 10.3, y: 0.4 }; | random_line_split |
300-custom-types.rs | #[derive(Debug)]
struct Person {
name: String,
age: u8,
}
// A unit struct
struct Unit;
// A tuple struct
struct Pair(i32, f32);
// A struct with two fields
struct Point {
x: f32,
y: f32,
}
// Structs can be reused as fields of another struct
#[allow(dead_code)]
struct Rectangle {
// A rectangle... | // from `point`
println!("second point: ({}, {})", bottom_right.x, bottom_right.y);
// Destructure the point using a `let` binding
let Point {
x: left_edge,
y: top_edge,
} = point;
let _rectangle = Rectangle {
// struct instantiation is an expression too
top_lef... | {
// Create struct with field init shorthand
let name = String::from("Peter");
let age = 27;
let peter = Person { name, age };
// Print debug struct
println!("{:?}", peter);
// Instantiate a `Point`
let point: Point = Point { x: 10.3, y: 0.4 };
// Access the fields of the point
... | identifier_body |
as_unsigned.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::slice::IntSliceExt;
// pub trait IntSliceExt<U, S> {
// /// Converts the slice to an immutable slice of unsigned integers with the same width.
// fn as_unsigned<'a>(&'a self) -> &'a [U];
// /// Converts the slice t... |
}
| {
let slice: &[T] = &[0xffffffffffffffff];
let as_unsigned: &[U] = slice.as_unsigned();
assert_eq!(as_unsigned[0], 18446744073709551615);
} | identifier_body |
as_unsigned.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::slice::IntSliceExt;
// pub trait IntSliceExt<U, S> {
// /// Converts the slice to an immutable slice of unsigned integers with the same width.
// fn as_unsigned<'a>(&'a self) -> &'a [U];
// /// Converts the slice t... | () {
let slice: &[T] = &[0xffffffffffffffff];
let as_unsigned: &[U] = slice.as_unsigned();
assert_eq!(as_unsigned[0], 18446744073709551615);
}
}
| as_unsigned_test1 | identifier_name |
as_unsigned.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::slice::IntSliceExt;
// pub trait IntSliceExt<U, S> {
// /// Converts the slice to an immutable slice of unsigned integers with the same width.
// fn as_unsigned<'a>(&'a self) -> &'a [U];
// /// Converts the slice t... |
assert_eq!(as_unsigned[0], 18446744073709551615);
}
} | #[test]
fn as_unsigned_test1() {
let slice: &[T] = &[0xffffffffffffffff];
let as_unsigned: &[U] = slice.as_unsigned(); | random_line_split |
strconv.rs | ..3] = ['N' as u8, 'a' as u8, 'N' as u8];
/**
* Converts an integral number to its string representation as a byte vector.
* This is meant to be a common base implementation for all integral string
* conversion functions like `to_str()` or `to_str_radix()`.
*
* # Arguments
* - `num` - The number to con... | * `to_str_bytes_common()`, for details see there.
*/
#[inline]
pub fn float_to_str_common<T:NumCast+Zero+One+Eq+Ord+NumStrConv+Float+Round+
Div<T,T>+Neg<T>+Rem<T,T>+Mul<T,T>>(
num: T, radix: uint, negative_zero: bool,
sign: SignFormat, digits: SignificantDigits) -> (~str, ... | }
/**
* Converts a number to its string representation. This is a wrapper for | random_line_split |
strconv.rs | // calculate new digits while
// - there is no limit and there are digits left
// - or there is a limit, it's not reached yet and
// - it's exact
// - or it's a maximum, and there are still digits left
while (!limit_digits && deccum!= _0)
|| (limit_digits && ... | {
let mut rng = XorShiftRng::new();
do bh.iter {
rng.gen::<uint>().to_str();
}
} | identifier_body | |
strconv.rs | for all integral string
* conversion functions like `to_str()` or `to_str_radix()`.
*
* # Arguments
* - `num` - The number to convert. Accepts any number that
* implements the numeric traits.
* - `radix` - Base to use. Accepts only the values 2-36.
* - `sign` - How... | {
i += 1u; // skip the '.'
break; // start of fractional part
} | conditional_block | |
strconv.rs | - `DigExact(uint)`: Exactly N digits.
*
* # Return value
* A tuple containing the byte vector, and a boolean flag indicating
* whether it represents a special value like `inf`, `-inf`, `NaN` or not.
* It returns a tuple because there can be ambiguity between a special value
* and a number representation at high... | from_str_common | identifier_name | |
mod.rs | /*
use std::fmt;
use std::io::{self, Write};
use std::marker::PhantomData;
use std::sync::mpsc;
use url::Url;
use tick;
use time::now_utc;
use header::{self, Headers};
use http::{self, conn};
use method::Method;
use net::{Fresh, Streaming};
use status::StatusCode;
use version::HttpVersion;
*/
pub use self::decode::D... | }
}
*/ | headers: headers,
raw_status: raw_status,
version: head.version,
})
*/ | random_line_split |
decode.rs | use std::{iter, fs, path};
use image::ImageFormat;
use criterion::{Criterion, criterion_group, criterion_main};
#[derive(Clone, Copy)]
struct BenchDef {
dir: &'static [&'static str],
files: &'static [&'static str],
format: ImageFormat,
}
fn load_all(c: &mut Criterion) | files: &[
"alpha_gif_a.gif",
"sample_1.gif",
],
format: ImageFormat::Gif,
},
BenchDef {
dir: &["hdr", "images"],
files: &[
"image1.hdr",
"rgbr4x4.hdr",
],
f... | {
const BENCH_DEFS: &'static [BenchDef] = &[
BenchDef {
dir: &["bmp", "images"],
files: &[
"Core_1_Bit.bmp",
"Core_4_Bit.bmp",
"Core_8_Bit.bmp",
"rgb16.bmp",
"rgb24.bmp",
"rgb32.bmp",
... | identifier_body |
decode.rs | use std::{iter, fs, path};
use image::ImageFormat;
use criterion::{Criterion, criterion_group, criterion_main};
#[derive(Clone, Copy)]
struct BenchDef {
dir: &'static [&'static str],
files: &'static [&'static str],
format: ImageFormat,
}
fn | (c: &mut Criterion) {
const BENCH_DEFS: &'static [BenchDef] = &[
BenchDef {
dir: &["bmp", "images"],
files: &[
"Core_1_Bit.bmp",
"Core_4_Bit.bmp",
"Core_8_Bit.bmp",
"rgb16.bmp",
"rgb24.bmp",
... | load_all | identifier_name |
decode.rs | use std::{iter, fs, path};
use image::ImageFormat;
use criterion::{Criterion, criterion_group, criterion_main};
#[derive(Clone, Copy)]
struct BenchDef {
dir: &'static [&'static str],
files: &'static [&'static str],
format: ImageFormat,
}
fn load_all(c: &mut Criterion) {
const BENCH_DEFS: &'static [Be... | format: ImageFormat::Ico,
},
BenchDef {
dir: &["jpg", "progressive"],
files: &[
"3.jpg",
"cat.jpg",
"test.jpg",
],
format: ImageFormat::Jpeg,
},
// TODO: pnm
// TODO: png
... | random_line_split | |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible};
use dom::bindings::glob... |
}
Ok(callable.ptr)
}
}
/// Wraps the reflector for `p` into the compartment of `cx`.
pub fn wrap_call_this_object<T: Reflectable>(cx: *mut JSContext,
p: &T,
rval: MutableHandleObject) {
rval.set(p.reflect... | {
return Err(Error::Type(format!("The value of the {} property is not callable",
name)));
} | conditional_block |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible};
use dom::bindings::glob... | let cx = global.r().get_cx();
unsafe {
JS_BeginRequest(cx);
}
let exception_compartment = unsafe {
GetGlobalForObjectCrossCompartment(callback.callback())
};
CallSetup {
exception_compartment: RootedObject::new_with_addr(cx,
... | pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup {
let global = global_root_from_object(callback.callback()); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.