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
translation_simba.rs
use simba::simd::SimdValue; use crate::base::allocator::Allocator; use crate::base::dimension::DimName; use crate::base::{DefaultAllocator, VectorN}; use crate::Scalar; use crate::geometry::Translation; impl<N: Scalar + SimdValue, D: DimName> SimdValue for Translation<N, D> where N::Element: Scalar, DefaultA...
#[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { self.vector.replace_unchecked(i, val.vector) } #[inline] fn select(self, cond: Self::SimdBool, other: Self) -> Self { self.vector.select(cond, other.vector).into() } }
{ self.vector.replace(i, val.vector) }
identifier_body
translation_simba.rs
use simba::simd::SimdValue; use crate::base::allocator::Allocator; use crate::base::dimension::DimName; use crate::base::{DefaultAllocator, VectorN}; use crate::Scalar; use crate::geometry::Translation; impl<N: Scalar + SimdValue, D: DimName> SimdValue for Translation<N, D> where N::Element: Scalar, DefaultA...
self.vector.extract(i).into() } #[inline] unsafe fn extract_unchecked(&self, i: usize) -> Self::Element { self.vector.extract_unchecked(i).into() } #[inline] fn replace(&mut self, i: usize, val: Self::Element) { self.vector.replace(i, val.vector) } #[inline] ...
VectorN::splat(val.vector).into() } #[inline] fn extract(&self, i: usize) -> Self::Element {
random_line_split
translation_simba.rs
use simba::simd::SimdValue; use crate::base::allocator::Allocator; use crate::base::dimension::DimName; use crate::base::{DefaultAllocator, VectorN}; use crate::Scalar; use crate::geometry::Translation; impl<N: Scalar + SimdValue, D: DimName> SimdValue for Translation<N, D> where N::Element: Scalar, DefaultA...
(&mut self, i: usize, val: Self::Element) { self.vector.replace(i, val.vector) } #[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { self.vector.replace_unchecked(i, val.vector) } #[inline] fn select(self, cond: Self::SimdBool, other: Self) -> Self ...
replace
identifier_name
main.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #[macro_use] extern crate clap; extern crate reqwest; #[macro_use] extern crate serde_derive; extern crate toml; extern crate indicatif; #[macro_use] extern crate lazy_static; #[cfg(test)] extern crate hyper; use clap...
let ignored: IgnoredRepo = match toml::from_str(&buffer) { Ok(ignored_repos) => ignored_repos, Err(e) => { println!( "Couldn't parse toml from ignoredrepos.toml, not ignoring any repos. Reason: {}", e ); return Vec::new(); }...
random_line_split
main.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #[macro_use] extern crate clap; extern crate reqwest; #[macro_use] extern crate serde_derive; extern crate toml; extern crate indicatif; #[macro_use] extern crate lazy_static; #[cfg(test)] extern crate hyper; use clap...
() { assert_eq!( true, suggest_org_arg("https://api.github.com/orgs/ORG-HERE/").is_err() ); assert_eq!( true, suggest_org_arg("http://api.github.com/orgs/ORG-HERE/").is_err() ); assert_eq!( true, suggest_org_...
suggestion_for_org_sad
identifier_name
main.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #[macro_use] extern crate clap; extern crate reqwest; #[macro_use] extern crate serde_derive; extern crate toml; extern crate indicatif; #[macro_use] extern crate lazy_static; #[cfg(test)] extern crate hyper; use clap...
#[cfg(test)] mod tests { use super::*; #[test] fn get_ignored_repos_happy_path() { let ignored_repositories = vec!["calagator".to_owned(), "moe".to_owned()]; assert_eq!(ignored_repositories, ignored_repos()); } #[test] fn handle_malformed_org() { assert_eq!( ...
{ println!("{}", message); ::std::process::exit(exit_code); }
identifier_body
volumes.rs
use std::path::PathBuf; use std::collections::BTreeMap; use quire::validate as V; use quire::ast::{Ast, Tag}; use libc::{uid_t, gid_t}; #[derive(RustcDecodable, Clone, PartialEq, Eq)] pub struct SnapshotInfo { pub size: usize, pub owner_uid: Option<uid_t>, pub owner_gid: Option<gid_t>, pub container:...
V::Directory::new().is_absolute(false), V::Structure::new() .member("mode", V::Numeric::new() .min(0).max(0o1777).default(0o755)) )) .member("files", V::Mapping::new( V::Directory::new().is_absolute(...
random_line_split
volumes.rs
use std::path::PathBuf; use std::collections::BTreeMap; use quire::validate as V; use quire::ast::{Ast, Tag}; use libc::{uid_t, gid_t}; #[derive(RustcDecodable, Clone, PartialEq, Eq)] pub struct SnapshotInfo { pub size: usize, pub owner_uid: Option<uid_t>, pub owner_gid: Option<gid_t>, pub container:...
{ pub name: String, pub owner_uid: uid_t, pub owner_gid: gid_t, pub init_command: Option<String>, } #[derive(RustcDecodable, Clone, PartialEq, Eq)] pub enum Volume { Tmpfs(TmpfsInfo), BindRW(PathBuf), BindRO(PathBuf), Empty, VaggaBin, Snapshot(SnapshotInfo), Container(Strin...
PersistentInfo
identifier_name
info_result.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
map_info, map_info_str, map_info_err, map_info_err_str, |s| { info!("{}", s); } );
InfoResult,
random_line_split
fuzz_target_1.rs
#![no_main] #[macro_use] extern crate libfuzzer_sys; extern crate quick_xml;
fuzz_target!(|data: &[u8]| { // fuzzed code goes here let cursor = Cursor::new(data); let mut reader = Reader::from_reader(cursor); let mut buf = vec![]; loop { match reader.read_event(&mut buf) { Ok(Event::Start(ref e)) | Ok(Event::Empty(ref e))=> { if e.unescape...
use quick_xml::Reader; use quick_xml::events::Event; use std::io::Cursor;
random_line_split
cabi_arm.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
let align = align_fn(ty); let size = ty_size(ty, align_fn); let llty = if align <= 4 { Type::array(&Type::i32(ccx), ((size + 3) / 4) as u64) } else { Type::array(&Type::i64(ccx), ((size + 7) / 8) as u64) }; ArgType::direct(ty, Some(llty), None, None) } fn is_reg_ty(ty: Type) -> ...
random_line_split
cabi_arm.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn is_reg_ty(ty: Type) -> bool { match ty.kind() { Integer | Pointer | Float | Double | Vector => true, _ => false } } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ...
{ if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; return ArgType::direct(ty, None, None, attr); } let align = align_fn(ty); let size = ty_size(ty, align_fn); let llty = if align <= 4 { Type::array(&Type::i32(ccx), ((size + 3) / 4) a...
identifier_body
cabi_arm.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(ty: Type) -> uint { match ty.kind() { Integer => ((ty.int_width() as uint) + 7) / 8, Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_...
general_ty_align
identifier_name
main.rs
extern crate libc; extern crate scaly; use libc::c_char; use libc::c_int; use scaly::containers::{Array, Ref, String, Vector}; use scaly::memory::Heap; use scaly::memory::Page; use scaly::memory::Region; use scaly::memory::StackBucket; use std::ffi::CString; mod scalyc; // Rust's main which converts args back to C...
.map(|arg| arg.as_ptr()) .collect::<Vec<*const c_char>>(); _main(c_args.len() as c_int, c_args.as_ptr()); } // C style main function which converts args to Scaly's main convention (would be provided by the LLVM backend) fn _main(argc: c_int, argv: *const *const c_char) { let _r = Region::create_f...
.map(|arg| CString::new(arg).unwrap()) .collect::<Vec<CString>>(); let c_args = args .iter()
random_line_split
main.rs
extern crate libc; extern crate scaly; use libc::c_char; use libc::c_int; use scaly::containers::{Array, Ref, String, Vector}; use scaly::memory::Heap; use scaly::memory::Page; use scaly::memory::Region; use scaly::memory::StackBucket; use std::ffi::CString; mod scalyc; // Rust's main which converts args back to C...
(argc: c_int, argv: *const *const c_char) { let _r = Region::create_from_page(Page::get(StackBucket::create(&mut Heap::create()) as usize)); _scalyc_main(&_r, { let _r_1 = Region::create(&_r); let mut arguments: Ref<Array<String>> = Ref::new(_r_1.page, Array::new()); for n in 0..argc { ...
_main
identifier_name
main.rs
extern crate libc; extern crate scaly; use libc::c_char; use libc::c_int; use scaly::containers::{Array, Ref, String, Vector}; use scaly::memory::Heap; use scaly::memory::Page; use scaly::memory::Region; use scaly::memory::StackBucket; use std::ffi::CString; mod scalyc; // Rust's main which converts args back to C...
unsafe { let arg = argv.offset(n as isize); let s = String::from_c_string(_r.page, *arg); (*arguments).add(s); } } Ref::new(_r.page, Vector::from_array(_r.page, arguments)) }); } fn _scalyc_main(_pr: &Region, arguments: Ref<V...
{ continue; }
conditional_block
main.rs
extern crate libc; extern crate scaly; use libc::c_char; use libc::c_int; use scaly::containers::{Array, Ref, String, Vector}; use scaly::memory::Heap; use scaly::memory::Page; use scaly::memory::Region; use scaly::memory::StackBucket; use std::ffi::CString; mod scalyc; // Rust's main which converts args back to C...
{ use scalyc::compiler::Compiler; let _r = Region::create(_pr); let compiler = Ref::new(_r.page, Compiler::new(_r.page, arguments)); (*compiler).compile(&_r, _r.page, _r.page); }
identifier_body
hex.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...
#[test] pub fn test_from_hex_invalid_char() { assert!("66y6".from_hex().is_err()); } #[test] pub fn test_from_hex_ignores_whitespace() { assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(), b"foobar"); } #[test] pub fn test_to_hex_all_bytes() { ...
{ assert!("666".from_hex().is_err()); assert!("66 6".from_hex().is_err()); }
identifier_body
hex.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...
use std::fmt; use std::error; /// A trait for converting a value to hexadecimal encoding pub trait ToHex { /// Converts the value of `self` to a hex value, returning the owned /// string. fn to_hex(&self) -> String; } const CHARS: &'static [u8] = b"0123456789abcdef"; impl ToHex for [u8] { /// Turn a ...
//! Hex binary-to-text encoding pub use self::FromHexError::*;
random_line_split
hex.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...
(&self) -> Result<Vec<u8>, FromHexError> { // This may be an overestimate if there is any whitespace let mut b = Vec::with_capacity(self.len() / 2); let mut modulus = 0; let mut buf = 0; for (idx, byte) in self.bytes().enumerate() { buf <<= 4; match byte...
from_hex
identifier_name
40.rs
/* Problem 40: Champernowne's constant * * An irrational decimal fraction is created by concatenating the positive integers: * * 0.123456789101112131415161718192021... * * It can be seen that the 12th digit of the fractional part is 1. * * If dn represents the nth digit of the fractional part, find the value of...
let result: u32 = [1, 10, 100, 1000, 10000, 100000, 1000000] .iter() .map(|&position| { (1..) .flat_map(digits::new::<_, u32>) .nth(position as usize - 1) .unwrap() }) .fold(1, |acc, n| acc * n); println!("{}", result); }
{
identifier_name
40.rs
/* Problem 40: Champernowne's constant * * An irrational decimal fraction is created by concatenating the positive integers: * * 0.123456789101112131415161718192021... * * It can be seen that the 12th digit of the fractional part is 1. * * If dn represents the nth digit of the fractional part, find the value of...
* * d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 */ use shared::digits; fn main() { let result: u32 = [1, 10, 100, 1000, 10000, 100000, 1000000] .iter() .map(|&position| { (1..) .flat_map(digits::new::<_, u32>) .nth(position as usize - 1) ...
random_line_split
40.rs
/* Problem 40: Champernowne's constant * * An irrational decimal fraction is created by concatenating the positive integers: * * 0.123456789101112131415161718192021... * * It can be seen that the 12th digit of the fractional part is 1. * * If dn represents the nth digit of the fractional part, find the value of...
let result: u32 = [1, 10, 100, 1000, 10000, 100000, 1000000] .iter() .map(|&position| { (1..) .flat_map(digits::new::<_, u32>) .nth(position as usize - 1) .unwrap() }) .fold(1, |acc, n| acc * n); println!("{}", result); }
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. use dom::bindings::codegen::PrototypeList::proto_id_to_name...
/// Format string used to throw javascript errors. static ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [ '{' as libc::c_char, '0' as libc::c_char, '}' as libc::c_char, 0 as libc::c_char, ]; /// Format string struct used to throw `TypeError`s. static mut TYPE_ERROR_FORMAT_STRING: JSErrorFormatStrin...
{ debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0); 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. use dom::bindings::codegen::PrototypeList::proto_id_to_name...
debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0); let error = format!("\"this\" object does not implement interface {}.", proto_id_to_name(proto_id)); throw_type_error(cx, &error); } /// Format string used to throw javascript errors. static ERROR_FORMAT_STRING_STRING: [libc:...
random_line_split
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. use dom::bindings::codegen::PrototypeList::proto_id_to_name...
, Error::Range(message) => { assert!(unsafe { JS_IsExceptionPending(cx) } == 0); throw_range_error(cx, &message); return; }, Error::JSFailed => { assert!(unsafe { JS_IsExceptionPending(cx) } == 1); return; } }; assert!(...
{ assert!(unsafe { JS_IsExceptionPending(cx) } == 0); throw_type_error(cx, &message); return; }
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. use dom::bindings::codegen::PrototypeList::proto_id_to_name...
{ /// IndexSizeError DOMException IndexSize, /// NotFoundError DOMException NotFound, /// HierarchyRequestError DOMException HierarchyRequest, /// WrongDocumentError DOMException WrongDocument, /// InvalidCharacterError DOMException InvalidCharacter, /// NotSupportedError DO...
Error
identifier_name
pointer.rs
// Copyright 2019 Jeremy Wall // // 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 ...
(&mut self, ptr: usize) -> Result<(), Error> { if ptr < self.pos_map.len() { self.ptr = Some(ptr); return Ok(()); } Err(Error::new( format!("FAULT!!! Invalid Jump!"), match self.pos() { Some(pos) => pos.clone(), None...
jump
identifier_name
pointer.rs
// Copyright 2019 Jeremy Wall // // 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 ...
)) } pub fn op(&self) -> Option<&Op> { if let Some(i) = self.ptr { return self.pos_map.ops.get(i); } None } pub fn pos(&self) -> Option<&Position> { if let Some(i) = self.ptr { return self.pos_map.pos.get(i); } None } ...
match self.pos() { Some(pos) => pos.clone(), None => Position::new(0, 0, 0), },
random_line_split
pointer.rs
// Copyright 2019 Jeremy Wall // // 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 ...
pub fn op(&self) -> Option<&Op> { if let Some(i) = self.ptr { return self.pos_map.ops.get(i); } None } pub fn pos(&self) -> Option<&Position> { if let Some(i) = self.ptr { return self.pos_map.pos.get(i); } None } pub fn idx(...
{ if ptr < self.pos_map.len() { self.ptr = Some(ptr); return Ok(()); } Err(Error::new( format!("FAULT!!! Invalid Jump!"), match self.pos() { Some(pos) => pos.clone(), None => Position::new(0, 0, 0), }, ...
identifier_body
mod.rs
// Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com> // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not...
pub fn actions(mut self, actions: Vec<ActionType>) -> ContextConfigBuilder { self.actions = actions; self } pub fn name(mut self, name: String) -> ContextConfigBuilder { self.name = Some(name); self } pub fn patterns(mut self, patterns: Vec<String>) -> ContextConf...
{ self.context_id = context_id; self }
identifier_body
mod.rs
// Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com> // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not...
name: Option<String>, uuid: Uuid, conditions: Conditions, context_id: Option<Vec<String>>, actions: Vec<ActionType>, patterns: Vec<String> } impl ContextConfigBuilder { pub fn new(uuid: Uuid, conditions: Conditions) -> ContextConfigBuilder { ContextConfigBuilder { name: ...
pub struct ContextConfigBuilder {
random_line_split
mod.rs
// Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com> // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not...
(mut self, patterns: Vec<String>) -> ContextConfigBuilder { self.patterns = patterns; self } pub fn build(self) -> ContextConfig { ContextConfig { name: self.name, uuid: self.uuid, conditions: self.conditions, context_id: self.context_id, ...
patterns
identifier_name
mod.rs
//! Example nonlinear PDEs pub mod kse; pub mod she; pub use self::kse::KSE; pub use self::she::SWE; use fftw::array::*;
/// Pair of one-dimensional Real/Complex aligned arrays pub struct Pair { pub r: AlignedVec<f64>, pub c: AlignedVec<c64>, r2c: R2CPlan64, c2r: C2RPlan64, } impl Pair { pub fn new(n: usize) -> Self { let nf = n / 2 + 1; let mut r = AlignedVec::new(n); let mut c = AlignedVec::...
use fftw::plan::*; use fftw::types::*; use ndarray::*;
random_line_split
mod.rs
//! Example nonlinear PDEs pub mod kse; pub mod she; pub use self::kse::KSE; pub use self::she::SWE; use fftw::array::*; use fftw::plan::*; use fftw::types::*; use ndarray::*; /// Pair of one-dimensional Real/Complex aligned arrays pub struct Pair { pub r: AlignedVec<f64>, pub c: AlignedVec<c64>, r2c: R...
pub fn real_view_mut(&mut self) -> ArrayViewMut1<f64> { ArrayViewMut::from_shape(self.r.len(), &mut self.r).unwrap() } pub fn coeff_view_mut(&mut self) -> ArrayViewMut1<c64> { ArrayViewMut::from_shape(self.c.len(), &mut self.c).unwrap() } } impl Clone for Pair { fn clone(&self) -...
{ ArrayView::from_shape(self.c.len(), &self.c).unwrap() }
identifier_body
mod.rs
//! Example nonlinear PDEs pub mod kse; pub mod she; pub use self::kse::KSE; pub use self::she::SWE; use fftw::array::*; use fftw::plan::*; use fftw::types::*; use ndarray::*; /// Pair of one-dimensional Real/Complex aligned arrays pub struct Pair { pub r: AlignedVec<f64>, pub c: AlignedVec<c64>, r2c: R...
(&mut self) { self.r2c.r2c(&mut self.r, &mut self.c).unwrap(); let n = 1.0 / self.r.len() as f64; for v in self.c.iter_mut() { *v *= n; } } pub fn c2r(&mut self) { self.c2r.c2r(&mut self.c, &mut self.r).unwrap(); } pub fn to_r<'a, 'b>(&'a mut self, c:...
r2c
identifier_name
renderer.rs
use log::{debug, error}; use std::{thread, time::Duration}; use crate::args::Args; use crate::context::Context; use crate::process; pub fn
(args: Args, context: Context) { thread::spawn(move || { let visualizations_dir = context.data_dir.join("visualizations"); loop { match visualizations_dir.read_dir() { Ok(read_dir) => { for dir_entry_result in read_dir { match ...
start
identifier_name
renderer.rs
use log::{debug, error}; use std::{thread, time::Duration}; use crate::args::Args; use crate::context::Context; use crate::process; pub fn start(args: Args, context: Context)
let blender_output = process::debug_output(output); error!("The blender child process returned an error exit code.\n\n{}", blender_output) } Err(_) => error!("The blend...
{ thread::spawn(move || { let visualizations_dir = context.data_dir.join("visualizations"); loop { match visualizations_dir.read_dir() { Ok(read_dir) => { for dir_entry_result in read_dir { match dir_entry_result { ...
identifier_body
renderer.rs
use log::{debug, error}; use std::{thread, time::Duration}; use crate::args::Args; use crate::context::Context; use crate::process; pub fn start(args: Args, context: Context) { thread::spawn(move || { let visualizations_dir = context.data_dir.join("visualizations"); loop { match visua...
debug!("The blender child process finished"); } else { let blender_output = process::debug_output(output); error!("The blender child process returned an error exit ...
Ok(output) => if output.status.success() {
random_line_split
uint.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
use rustc_serialize::hex::ToHex; use serde; use util::{U256 as EthU256, Uint}; macro_rules! impl_uint { ($name: ident, $other: ident, $size: expr) => { /// Uint serialization. #[derive(Debug, Default, Clone, Copy, PartialEq, Hash)] pub struct $name($other); impl Eq for $name { } impl<T> From<T> for $name ...
use std::cmp; use std::str::FromStr;
random_line_split
uint.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
() { let deserialized1: Res = serde_json::from_str(r#""""#); let deserialized2: Res = serde_json::from_str(r#""0""#); let deserialized3: Res = serde_json::from_str(r#""10""#); let deserialized4: Res = serde_json::from_str(r#""1000000""#); let deserialized5: Res = serde_json::from_str(r#""1000000000000000000""...
should_fail_to_deserialize_decimals
identifier_name
uint.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
#[test] fn should_deserialize_u256() { let deserialized1: U256 = serde_json::from_str(r#""0x""#).unwrap(); let deserialized2: U256 = serde_json::from_str(r#""0x0""#).unwrap(); let deserialized3: U256 = serde_json::from_str(r#""0x1""#).unwrap(); let deserialized4: U256 = serde_json::from_str(r#""0x01""#).unw...
{ let deserialized1: Res = serde_json::from_str(r#""""#); let deserialized2: Res = serde_json::from_str(r#""0""#); let deserialized3: Res = serde_json::from_str(r#""10""#); let deserialized4: Res = serde_json::from_str(r#""1000000""#); let deserialized5: Res = serde_json::from_str(r#""1000000000000000000""#);...
identifier_body
formatting.rs
pub mod placeholder; pub mod prefix; pub mod unit; pub mod value; use std::borrow::Borrow; use std::collections::HashMap; use std::fmt; use std::hash::Hash; use serde::de::{MapAccess, Visitor}; use serde::{de, Deserialize, Deserializer}; use crate::errors::*; use placeholder::unexpected_token; use placeholder::Place...
/// Handle configs like: /// /// ```toml /// format = "{layout}" /// ``` fn visit_str<E>(self, full: &str) -> StdResult<FormatTemplate, E> where E: de::Error, { FormatTemplate::new(full, Non...
{ formatter.write_str("format structure") }
identifier_body
formatting.rs
pub mod placeholder; pub mod prefix; pub mod unit; pub mod value; use std::borrow::Borrow; use std::collections::HashMap; use std::fmt; use std::hash::Hash; use serde::de::{MapAccess, Visitor}; use serde::{de, Deserialize, Deserializer}; use crate::errors::*; use placeholder::unexpected_token; use placeholder::Place...
() { let format = FormatTemplate::new("some text {foo} {bar:1} foobar", None); assert!(format.is_ok()); let format = format.unwrap(); assert!(format.contains("foo")); assert!(format.contains("bar")); assert!(!format.contains("foobar")); assert!(!format.contains("r...
contains
identifier_name
formatting.rs
pub mod placeholder; pub mod prefix; pub mod unit; pub mod value; use std::borrow::Borrow; use std::collections::HashMap; use std::fmt; use std::hash::Hash; use serde::de::{MapAccess, Visitor}; use serde::{de, Deserialize, Deserializer}; use crate::errors::*; use placeholder::unexpected_token; use placeholder::Place...
false } fn tokens_from_string(mut s: &str) -> Result<Vec<Token>> { let mut tokens = vec![]; // Push text into tokens vector. Check the text for correctness and don't push empty strings let push_text = |tokens: &mut Vec<Token>, x: &str| { if x.contains('{') { ...
} } } }
random_line_split
engine.rs
use fact_db::FactDB; use std::collections::hash_map::HashMap; use native_types::*; pub struct Engine { fact_db : Box<FactDB + Send>, funcs : HashMap<String, HFunc> } #[derive(Debug)] pub enum Error { Invalid(String), Internal(String), Type(String), Db(String) } use self::Error::*; fn substitute(clause ...
Iterate(_) => unimplemented!() } } } for head_clause in rule.head.iter() { assert!(self.new_fact(&substitute(&head_clause, &ans)).is_ok()); } } } } SearchInvalid(s) => panic!("Internal invali...
{ //Definition should be next to be defined. assert!(n as usize == ans.len()); ans.push(rhs.clone()); }
conditional_block
engine.rs
use fact_db::FactDB; use std::collections::hash_map::HashMap; use native_types::*; pub struct Engine { fact_db : Box<FactDB + Send>, funcs : HashMap<String, HFunc> } #[derive(Debug)] pub enum Error { Invalid(String), Internal(String), Type(String), Db(String) } use self::Error::*; fn substitute(clause ...
pub fn reg_func(&mut self, name : String, func : HFunc) { self.funcs.insert(name, func); } }
} }
random_line_split
engine.rs
use fact_db::FactDB; use std::collections::hash_map::HashMap; use native_types::*; pub struct Engine { fact_db : Box<FactDB + Send>, funcs : HashMap<String, HFunc> } #[derive(Debug)] pub enum Error { Invalid(String), Internal(String), Type(String), Db(String) } use self::Error::*; fn substitute(clause ...
(&mut self, rule : &Rule) { use fact_db::SearchResponse::*; match self.fact_db.search_facts(&rule.body) { SearchAns(anss) => { //TODO: support anything other than one match, then wheres 'ans: for ans in anss { if self.fact_db.rule_cache_miss(&rule, &ans) { let mut ans...
run_rule
identifier_name
set.rs
use liner::KeyBindings; use shell::Shell; use shell::flags::*; use std::io::{self, Write}; use std::iter; const HELP: &'static str = r#"NAME set - Set or unset values of shell options and positional parameters. SYNOPSIS set [ --help ] [-e | +e] [-x | +x] [-o [vi | emacs]] [- | --] [STRING]... DESCRIPTION ...
} else if arg.starts_with('-') { if arg.len() == 1 { positionals = Some(RetainIfNone); break; } for flag in arg.bytes().skip(1) { match flag { b'e' => shell.flags |= ERR_EXIT, b'o' => mat...
{ return 0; }
conditional_block
set.rs
use liner::KeyBindings; use shell::Shell; use shell::flags::*; use std::io::{self, Write};
const HELP: &'static str = r#"NAME set - Set or unset values of shell options and positional parameters. SYNOPSIS set [ --help ] [-e | +e] [-x | +x] [-o [vi | emacs]] [- | --] [STRING]... DESCRIPTION Shell options may be set using the '-' character, and unset using the '+' character. OPTIONS -e Exi...
use std::iter;
random_line_split
set.rs
use liner::KeyBindings; use shell::Shell; use shell::flags::*; use std::io::{self, Write}; use std::iter; const HELP: &'static str = r#"NAME set - Set or unset values of shell options and positional parameters. SYNOPSIS set [ --help ] [-e | +e] [-x | +x] [-o [vi | emacs]] [- | --] [STRING]... DESCRIPTION ...
(args: &[&str], shell: &mut Shell) -> i32 { let stdout = io::stdout(); let stderr = io::stderr(); let mut args_iter = args.iter(); let mut positionals = None; while let Some(arg) = args_iter.next() { if arg.starts_with("--") { if arg.len() == 2 { positionals = So...
set
identifier_name
mod.rs
// Copyright 2020 The Exonum Team // // 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...
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> { ensure!( u16::try_from(pb).is_ok(), "{} is out of range for valid ValidatorId", pb ); Ok(Self(pb as u16)) } }
{ u32::from(self.0) }
identifier_body
mod.rs
// Copyright 2020 The Exonum Team // // 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...
(&self) -> Self::ProtoStruct { self.0 } fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> { Ok(Self(pb)) } } impl ProtobufConvert for Round { type ProtoStruct = u32; fn to_pb(&self) -> Self::ProtoStruct { self.0 } fn from_pb(pb: Self::ProtoStruct) -> Result...
to_pb
identifier_name
mod.rs
// Copyright 2020 The Exonum Team // // 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...
u16::try_from(pb).is_ok(), "{} is out of range for valid ValidatorId", pb ); Ok(Self(pb as u16)) } }
ensure!(
random_line_split
mod.rs
prelude!(); use ::vga; use super::pic::{PIC_1, PIC_2}; mod item; pub use self::item::*; mod idt_ptr; pub use self::idt_ptr::*; extern "C" { fn interrupt0(); fn interrupt1(); } extern { fn __kernel_timer_tick(); } const IDT_SIZE: usize = 64; static mut IDT_TABLE: [IdtItem; IDT_SIZE] = [IdtItem::new();...
vga::print(b"!! Interrupt!!"); println!("!! Interrupt: {:#x}, Error code: {:#x}", num, error_code); if PIC_1.has_interrupt(num) { PIC_1.end_of_interrupt(); } if PIC_2.has_interrupt(num) { PIC_1.end_of_interrupt(); PIC_2.end_of_interrupt(); } } pub unsafe fn init() { ...
{ __kernel_timer_tick(); // it will send EOI itself return; }
conditional_block
mod.rs
prelude!(); use ::vga; use super::pic::{PIC_1, PIC_2}; mod item;
pub use self::item::*; mod idt_ptr; pub use self::idt_ptr::*; extern "C" { fn interrupt0(); fn interrupt1(); } extern { fn __kernel_timer_tick(); } const IDT_SIZE: usize = 64; static mut IDT_TABLE: [IdtItem; IDT_SIZE] = [IdtItem::new(); IDT_SIZE]; #[no_mangle] pub unsafe extern "C" fn handle_interrupt(...
random_line_split
mod.rs
prelude!(); use ::vga; use super::pic::{PIC_1, PIC_2}; mod item; pub use self::item::*; mod idt_ptr; pub use self::idt_ptr::*; extern "C" { fn interrupt0(); fn interrupt1(); } extern { fn __kernel_timer_tick(); } const IDT_SIZE: usize = 64; static mut IDT_TABLE: [IdtItem; IDT_SIZE] = [IdtItem::new();...
{ let diff = interrupt1 as usize - interrupt0 as usize; for i in 0..IDT_SIZE { IDT_TABLE[i].set_offset(interrupt0 as usize + diff * i); } // 0 pic interrupt is used by thread scheduler // { // FIXME // let idx = PIC_1.get_interrupt_idt_num(0) as usize; // IDT_TABLE[idx].type_at...
identifier_body
mod.rs
prelude!(); use ::vga; use super::pic::{PIC_1, PIC_2}; mod item; pub use self::item::*; mod idt_ptr; pub use self::idt_ptr::*; extern "C" { fn interrupt0(); fn interrupt1(); } extern { fn __kernel_timer_tick(); } const IDT_SIZE: usize = 64; static mut IDT_TABLE: [IdtItem; IDT_SIZE] = [IdtItem::new();...
() { let diff = interrupt1 as usize - interrupt0 as usize; for i in 0..IDT_SIZE { IDT_TABLE[i].set_offset(interrupt0 as usize + diff * i); } // 0 pic interrupt is used by thread scheduler // { // FIXME // let idx = PIC_1.get_interrupt_idt_num(0) as usize; // IDT_TABLE[idx].type...
init
identifier_name
eval_paths.rs
use std::time::{Instant, Duration}; use rand::Rng; use crate::progress::Progress; use crate::sim::TestPacket; use crate::dijkstra::Dijkstra; use crate::graph::*; /* * Test if all paths allow for routing. * This test does not allow the state of the routing algorithm to change. */ pub struct EvalPaths { show_progr...
} pub fn stretch(&self) -> f32 { (self.route_costs_sum as f32) / (self.route_costs_min_sum as f32) } pub fn arrived(&self) -> f32 { 100.0 * (self.packets_arrived as f32) / (self.packets_send as f32) } pub fn connectivity(&self) -> f32 { 100.0 * (self.nodes_connected as f32) / (self.nodes_connected + self...
random_line_split
eval_paths.rs
use std::time::{Instant, Duration}; use rand::Rng; use crate::progress::Progress; use crate::sim::TestPacket; use crate::dijkstra::Dijkstra; use crate::graph::*; /* * Test if all paths allow for routing. * This test does not allow the state of the routing algorithm to change. */ pub struct EvalPaths { show_progr...
(&mut self) { self.dijkstra.clear(); self.clear_stats(); } pub fn show_progress(&mut self, show_progress: bool) { self.show_progress = true; } fn test_path(&mut self, graph: &Graph, mut route: impl FnMut(&TestPacket) -> Option<u32>, source: ID, target: ID, costs_min: u32) { // maximum stretch we record...
clear
identifier_name
eval_paths.rs
use std::time::{Instant, Duration}; use rand::Rng; use crate::progress::Progress; use crate::sim::TestPacket; use crate::dijkstra::Dijkstra; use crate::graph::*; /* * Test if all paths allow for routing. * This test does not allow the state of the routing algorithm to change. */ pub struct EvalPaths { show_progr...
else { // invalid next hop self.packets_lost += 1; break; } } else { // no next hop self.packets_lost += 1; break; } } self.route_costs_sum += path_costs; self.route_costs_min_sum += costs_min; } pub fn run_samples(&mut self, graph: &Graph, mut route: impl FnMut(&TestPack...
{ path_costs += link.cost() as u32; if next == packet.destination { // packet arrived self.packets_arrived += 1; break; } else { // forward packet packet.transmitter = packet.receiver; packet.receiver = next; } }
conditional_block
endian.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
(&self) -> f32 { unsafe { mem::transmute(mem::transmute::<f32, u32>(*self).to_le()) } } fn set(&mut self, value : f32) { *self = unsafe { mem::transmute(mem::transmute::<f32, u32>(value).to_le()) }; } } impl Endian for f64 { fn get(&self) -> f64 { unsafe { mem::transmute(mem::tr...
get
identifier_name
endian.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
}
random_line_split
console.rs
// Copyright (c) 2019 Jason White // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, d...
(mut self) -> Result<(), io::Error> { for task in self.tasks.iter_mut() { task.pb .finish_with_message(&style("Done").dim().to_string()); } self.tick_thread.join().unwrap(); self.pb_thread.join().unwrap()?; Ok(()) } pub fn end_build( ...
finish
identifier_name
console.rs
// Copyright (c) 2019 Jason White // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, d...
start_time: timestamp, pb_thread, tick_thread, name, } } pub fn finish(mut self) -> Result<(), io::Error> { for task in self.tasks.iter_mut() { task.pb .finish_with_message(&style("Done").dim().to_string()); } ...
}); Inner { tasks,
random_line_split
console.rs
// Copyright (c) 2019 Jason White // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, d...
for task in &self.tasks { task.pb.set_style(Console::style_idle()); } self.tasks[0].pb.println(&msg); self.finish() } pub fn begin_task( &mut self, timestamp: Timestamp, event: BeginTaskEvent, ) -> Result<(), io::Error> { let mu...
{ let duration = (timestamp - self.start_time).to_std().unwrap(); let duration = format_duration(duration); let msg = match event.result { Ok(()) => format!( "{} {} in {}", style("Finished").bold().green(), style(&self.name).yellow(), ...
identifier_body
console.rs
// Copyright (c) 2019 Jason White // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, d...
} Event::EndTask(event) => { if let Some(inner) = &mut self.inner { inner.end_task(timestamp, event)?; } } Event::Delete(event) => { if let Some(inner) = &mut self.inner { inner.delete(time...
inner.tasks[event.id].buf.extend(event.chunk); }
conditional_block
align_of_val.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::mem::align_of_val; use core::default::Default; // pub fn align_of_val<T:?Sized>(val: &T) -> usize { // unsafe { intrinsics::min_align_of_val(val) } // } macro_rules! align_of_val_test { ($T:ty, $size:expr) => ({ ...
}
{ align_of_val_test!( (u8), 1 ); align_of_val_test!( (u8, u16), 2 ); align_of_val_test!( (u8, u16, u32), 4 ); align_of_val_test!( (u8, u16, u32, u64), 8 ); }
identifier_body
align_of_val.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::mem::align_of_val; use core::default::Default; // pub fn align_of_val<T:?Sized>(val: &T) -> usize { // unsafe { intrinsics::min_align_of_val(val) } // } macro_rules! align_of_val_test { ($T:ty, $size:expr) => ({ ...
() { align_of_val_test!( (u8), 1 ); align_of_val_test!( (u8, u16), 2 ); align_of_val_test!( (u8, u16, u32), 4 ); align_of_val_test!( (u8, u16, u32, u64), 8 ); } }
align_of_val_test2
identifier_name
align_of_val.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::mem::align_of_val; use core::default::Default; // pub fn align_of_val<T:?Sized>(val: &T) -> usize { // unsafe { intrinsics::min_align_of_val(val) } // } macro_rules! align_of_val_test { ($T:ty, $size:expr) => ({ ...
align_of_val_test!( (u8, u16, u32, u64), 8 ); } }
random_line_split
mod.rs
//! Variable header in MQTT use std::io; use std::string::FromUtf8Error; use crate::topic_name::{TopicNameDecodeError, TopicNameError}; pub use self::connect_ack_flags::ConnackFlags; pub use self::connect_flags::ConnectFlags; pub use self::connect_ret_code::ConnectReturnCode;
pub use self::packet_identifier::PacketIdentifier; pub use self::protocol_level::ProtocolLevel; pub use self::protocol_name::ProtocolName; pub use self::topic_name::TopicNameHeader; mod connect_ack_flags; mod connect_flags; mod connect_ret_code; mod keep_alive; mod packet_identifier; pub mod protocol_level; mod protoc...
pub use self::keep_alive::KeepAlive;
random_line_split
mod.rs
//! Variable header in MQTT use std::io; use std::string::FromUtf8Error; use crate::topic_name::{TopicNameDecodeError, TopicNameError}; pub use self::connect_ack_flags::ConnackFlags; pub use self::connect_flags::ConnectFlags; pub use self::connect_ret_code::ConnectReturnCode; pub use self::keep_alive::KeepAlive; pub...
(err: TopicNameDecodeError) -> VariableHeaderError { match err { TopicNameDecodeError::IoError(e) => Self::IoError(e), TopicNameDecodeError::InvalidTopicName(e) => Self::TopicNameError(e), } } }
from
identifier_name
mod.rs
//! Variable header in MQTT use std::io; use std::string::FromUtf8Error; use crate::topic_name::{TopicNameDecodeError, TopicNameError}; pub use self::connect_ack_flags::ConnackFlags; pub use self::connect_flags::ConnectFlags; pub use self::connect_ret_code::ConnectReturnCode; pub use self::keep_alive::KeepAlive; pub...
}
{ match err { TopicNameDecodeError::IoError(e) => Self::IoError(e), TopicNameDecodeError::InvalidTopicName(e) => Self::TopicNameError(e), } }
identifier_body
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
// track some statistics creatures_met += 1; if other_creature.name == name { evil_clones_met += 1; } } None => break } } // log creatures met and evil clones of self let report = format!("{}{:...
// log and change, or quit match rendezvous.next() { Some(other_creature) => { color = transform(color, other_creature.color);
random_line_split
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
fn show_digit(nn: uint) -> &'static str { match nn { 0 => {" zero"} 1 => {" one"} 2 => {" two"} 3 => {" three"} 4 => {" four"} 5 => {" five"} 6 => {" six"} 7 => {" seven"} 8 => {" eight"} 9 => {" nine"} _ => {panic!("expected ...
{ let mut out = String::new(); for col in &set { out.push(' '); out.push_str(&format!("{:?}", col)); } out }
identifier_body
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
8 => {" eight"} 9 => {" nine"} _ => {panic!("expected digits from 0 to 9...")} } } struct Number(uint); impl fmt::Debug for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut out = vec![]; let Number(mut num) = *self; if num == 0 { out.push(...
{" seven"}
conditional_block
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
(aa: Color, bb: Color) -> Color { match (aa, bb) { (Red, Red ) => { Red } (Red, Yellow) => { Blue } (Red, Blue ) => { Yellow } (Yellow, Red ) => { Blue } (Yellow, Yellow) => { Yellow } (Yellow, Blue ) => { Red } (Blue, Red ) => { Y...
transform
identifier_name
iter.rs
use std::mem; struct
{ curr: uint, next: uint, } // Implement 'Iterator' for 'Fibonacci' impl Iterator<uint> for Fibonacci { // The 'Iterator' trait only requires the 'next' method to be defined. The // return type is 'Option<T>', 'None' is returned when the 'Iterator' is // over, otherwise the next value is returned ...
Fibonacci
identifier_name
iter.rs
use std::mem; struct Fibonacci { curr: uint, next: uint, } // Implement 'Iterator' for 'Fibonacci' impl Iterator<uint> for Fibonacci { // The 'Iterator' trait only requires the 'next' method to be defined. The // return type is 'Option<T>', 'None' is returned when the 'Iterator' is // over, otherw...
} // Returns a fibonacci sequence generator fn fibonacci() -> Fibonacci { Fibonacci { curr: 1, next: 1 } } fn main() { // Iterator that generates: 0, 1 and 2 let mut sequence = range(0u, 3); println!("Four consecutive `next` calls on range(0, 3)") println!("> {}", sequence.next()); println!(...
{ let new_next = self.curr + self.next; let new_curr = mem::replace(&mut self.next, new_next); // 'Some' is always returned, this is an infinite value generator Some(mem::replace(&mut self.curr, new_curr)) }
identifier_body
iter.rs
use std::mem; struct Fibonacci { curr: uint, next: uint, } // Implement 'Iterator' for 'Fibonacci' impl Iterator<uint> for Fibonacci { // The 'Iterator' trait only requires the 'next' method to be defined. The // return type is 'Option<T>', 'None' is returned when the 'Iterator' is // over, otherw...
let mut sequence = range(0u, 3); println!("Four consecutive `next` calls on range(0, 3)") println!("> {}", sequence.next()); println!("> {}", sequence.next()); println!("> {}", sequence.next()); println!("> {}", sequence.next()); // The for construct will iterate an 'Iterator' until it ret...
// Iterator that generates: 0, 1 and 2
random_line_split
build.rs
// Copyright 2014 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. #[cfg(feature = "serde")] use bindgen; use fs_utils::copy::copy_directory; use glob::glob; use std::env; use std::fs; u...
} let use_lzma = env::var("CARGO_FEATURE_LZMA").is_ok(); if use_lzma { if let Ok(inc) = env::var("DEP_LZMA_INCLUDE").map(PathBuf::from) { cfg.include(inc); lib_list += " -llzma"; config_lines.push("#define HAVE_LIBBZ2 1"); config_lines.push("#ifndef _...
panic!("no DEP_LIBDEFLATE_INCLUDE"); }
conditional_block
build.rs
// Copyright 2014 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. #[cfg(feature = "serde")] use bindgen; use fs_utils::copy::copy_directory; use glob::glob; use std::env; use std::fs; u...
"htscodecs/htscodecs/fqzcomp_qual.c", "htscodecs/htscodecs/htscodecs.c", "htscodecs/htscodecs/pack.c", "htscodecs/htscodecs/rANS_static4x16pr.c", "htscodecs/htscodecs/rANS_static.c", "htscodecs/htscodecs/rle.c", "htscodecs/htscodecs/tokenise_name3.c", ]; fn main() { let out = PathBuf::f...
"cram/mFILE.c", "cram/open_trace_file.c", "cram/pooled_alloc.c", "cram/string_alloc.c", "htscodecs/htscodecs/arith_dynamic.c",
random_line_split
build.rs
// Copyright 2014 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. #[cfg(feature = "serde")] use bindgen; use fs_utils::copy::copy_directory; use glob::glob; use std::env; use std::fs; u...
let c_file = out_htslib.join(f); cfg.file(&c_file); println!("cargo:rerun-if-changed={}", htslib.join(f).display()); } cfg.include(out.join("htslib")); let want_static = cfg!(feature = "static") || env::var("HTS_STATIC").is_ok(); if want_static { cfg.warnings(false).st...
let out = PathBuf::from(env::var("OUT_DIR").unwrap()); let htslib_copy = out.join("htslib"); if htslib_copy.exists() { std::fs::remove_dir_all(htslib_copy).unwrap(); } copy_directory("htslib", &out).unwrap(); // In build.rs cfg(target_os) does not give the target when cross-compiling;...
identifier_body
build.rs
// Copyright 2014 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. #[cfg(feature = "serde")] use bindgen; use fs_utils::copy::copy_directory; use glob::glob; use std::env; use std::fs; u...
) { let out = PathBuf::from(env::var("OUT_DIR").unwrap()); let htslib_copy = out.join("htslib"); if htslib_copy.exists() { std::fs::remove_dir_all(htslib_copy).unwrap(); } copy_directory("htslib", &out).unwrap(); // In build.rs cfg(target_os) does not give the target when cross-compili...
ain(
identifier_name
lib.rs
/* Copyright (C) 2015 Yutaka Kamei */ #![feature(test)] extern crate urlparse; extern crate test; use urlparse::*; use test::Bencher; #[bench] fn bench_quote(b: &mut Bencher) { b.iter(|| quote("/a/テスト!/", &[b'/'])); } #[bench] fn bench_quote_plus(b: &mut Bencher) { b.iter(|| quote_plus("/a/テスト!/", &[b'/'])...
cher) { b.iter(|| unquote("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/")); } #[bench] fn bench_unquote_plus(b: &mut Bencher) { b.iter(|| unquote_plus("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/")); } #[bench] fn bench_parse_qs(b: &mut Bencher) { b.iter(|| parse_qs("q=%E3%83%86%E3%82%B9%E3%83%88+%E3%83%86%E3%82%B9%...
e(b: &mut Ben
identifier_name
lib.rs
/* Copyright (C) 2015 Yutaka Kamei */ #![feature(test)] extern crate urlparse; extern crate test; use urlparse::*; use test::Bencher; #[bench] fn bench_quote(b: &mut Bencher) { b.iter(|| quote("/a/テスト!/", &[b'/'])); } #[bench] fn bench_quote_plus(b: &mut Bencher) { b.iter(|| quote_plus("/a/テスト!/", &[b'/'])...
}
query: Some("filter=%28%21%28cn%3Dbar%29%29".to_string()), .. url}; urlunparse(url) });
random_line_split
lib.rs
/* Copyright (C) 2015 Yutaka Kamei */ #![feature(test)] extern crate urlparse; extern crate test; use urlparse::*; use test::Bencher; #[bench] fn bench_quote(b: &mut Bencher) { b.iter(|| quote("/a/テスト!/", &[b'/'])); } #[bench] fn bench_quote_plus(b: &mut Bencher) {
fn bench_unquote(b: &mut Bencher) { b.iter(|| unquote("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/")); } #[bench] fn bench_unquote_plus(b: &mut Bencher) { b.iter(|| unquote_plus("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/")); } #[bench] fn bench_parse_qs(b: &mut Bencher) { b.iter(|| parse_qs("q=%E3%83%86%E3%82%B9%...
b.iter(|| quote_plus("/a/テスト !/", &[b'/'])); } #[bench]
identifier_body
linux_gl_hooks.rs
#![cfg(target_os = "linux")] #[link(name = "dl")] extern "C" {} use crate::gl; use const_cstr::const_cstr; use lazy_static::lazy_static; use libc::{c_char, c_int, c_ulong, c_void}; use libc_print::libc_println; use log::*; use std::ffi::CString; use std::sync::Once; use std::time::SystemTime; ///////////////////////...
y, width, height, gl::GL_RGBA, gl::GL_UNSIGNED_BYTE, std::mem::transmute(frame_buffer.as_ptr()), ); let mut num_black = 0; for y in 0..height { for x in 0..width { let i = (y * width + x) as usize; let (r, g, b) = ( ...
{ let cc = gl::get_capture_context(get_glx_proc_address); cc.capture_frame(); let x: gl::GLint = 0; let y: gl::GLint = 0; let width: gl::GLsizei = 400; let height: gl::GLsizei = 400; let bytes_per_pixel: usize = 4; let bytes_per_frame: usize = width as usize * height as usize * bytes_pe...
identifier_body
linux_gl_hooks.rs
#![cfg(target_os = "linux")] #[link(name = "dl")] extern "C" {} use crate::gl; use const_cstr::const_cstr; use lazy_static::lazy_static; use libc::{c_char, c_int, c_ulong, c_void}; use libc_print::libc_println; use log::*; use std::ffi::CString; use std::sync::Once; use std::time::SystemTime; ///////////////////////...
() { let cc = gl::get_capture_context(get_glx_proc_address); cc.capture_frame(); let x: gl::GLint = 0; let y: gl::GLint = 0; let width: gl::GLsizei = 400; let height: gl::GLsizei = 400; let bytes_per_pixel: usize = 4; let bytes_per_frame: usize = width as usize * height as usize * bytes...
capture_gl_frame
identifier_name
linux_gl_hooks.rs
#![cfg(target_os = "linux")] #[link(name = "dl")] extern "C" {} use crate::gl; use const_cstr::const_cstr; use lazy_static::lazy_static; use libc::{c_char, c_int, c_ulong, c_void}; use libc_print::libc_println; use log::*; use std::ffi::CString; use std::sync::Once; use std::time::SystemTime; ///////////////////////...
using } static HOOK_SWAPBUFFERS_ONCE: Once = Once::new(); /// If libGL.so.1 was loaded, and only once in the lifetime /// of this process, hook libGL functions for libcapsule usage. unsafe fn hook_if_needed() { if is_using_opengl() { HOOK_SWAPBUFFERS_ONCE.call_once(|| { info!("libGL usage...
{ dlclose(handle); }
conditional_block
linux_gl_hooks.rs
#![cfg(target_os = "linux")] #[link(name = "dl")] extern "C" {} use crate::gl; use const_cstr::const_cstr; use lazy_static::lazy_static; use libc::{c_char, c_int, c_ulong, c_void}; use libc_print::libc_println; use log::*; use std::ffi::CString; use std::sync::Once; use std::time::SystemTime; ///////////////////////...
let using =!handle.is_null(); if using { dlclose(handle); } using } static HOOK_SWAPBUFFERS_ONCE: Once = Once::new(); /// If libGL.so.1 was loaded, and only once in the lifetime /// of this process, hook libGL functions for libcapsule usage. unsafe fn hook_if_needed() { if is_using_opengl(...
// modules are reference-counted. let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_NOLOAD | RTLD_LAZY);
random_line_split
pseudo_element.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/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo...
} impl PseudoElement { /// Returns the kind of cascade type that a given pseudo is going to use. /// /// In Gecko we only compute ::before and ::after eagerly. We save the rules /// for anonymous boxes separately, so we resolve them as precomputed /// pseudos. /// /// We resolve the others...
{ if !self.supports_user_action_state() { return false; } return pseudo_class.is_safe_user_action_state(); }
identifier_body
pseudo_element.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/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo...
pub fn cascade_type(&self) -> PseudoElementCascadeType { if self.is_eager() { debug_assert!(!self.is_anon_box()); return PseudoElementCascadeType::Eager } if self.is_precomputed() { return PseudoElementCascadeType::Precomputed } PseudoEle...
/// pseudos. /// /// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
random_line_split
pseudo_element.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/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo...
(&self) -> bool { (self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0 } /// Whether this pseudo-element is precomputed. #[inline] pub fn is_precomputed(&self) -> bool { self.is_anon_box() &&!self.is_tree_pseudo_element() } /// Covert non-canonical pseudo-elem...
skip_item_based_display_fixup
identifier_name
constrain-trait.rs
// run-rustfix // check-only #[derive(Debug)] struct Demo { a: String } trait GetString { fn get_a(&self) -> &String; } trait UseString: std::fmt::Debug { fn use_string(&self) { println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found } } trait UseString2 { fn use_string(&...
} fn main() {}
{ let d = Demo { a: "test".to_string() }; d.use_string(); }
identifier_body
constrain-trait.rs
// run-rustfix // check-only #[derive(Debug)] struct Demo { a: String } trait GetString { fn get_a(&self) -> &String; } trait UseString: std::fmt::Debug { fn use_string(&self) { println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found } } trait UseString2 { fn use_string(&...
impl UseString2 for Demo {} #[cfg(test)] mod tests { use crate::{Demo, UseString}; #[test] fn it_works() { let d = Demo { a: "test".to_string() }; d.use_string(); } } fn main() {}
impl UseString for Demo {}
random_line_split
constrain-trait.rs
// run-rustfix // check-only #[derive(Debug)] struct Demo { a: String } trait GetString { fn get_a(&self) -> &String; } trait UseString: std::fmt::Debug { fn use_string(&self) { println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found } } trait UseString2 { fn use_string(&...
(&self) -> &String { &self.a } } impl UseString for Demo {} impl UseString2 for Demo {} #[cfg(test)] mod tests { use crate::{Demo, UseString}; #[test] fn it_works() { let d = Demo { a: "test".to_string() }; d.use_string(); } } fn main() {}
get_a
identifier_name
block_header.rs
use Encode; use VarInt; #[derive(Debug, Encode, PartialEq)] /// 4 version int32_t Block version information (note, this is signed) /// 32 prev_block char[32] The hash value of the previous block this particular block references /// 32 merkle_root char[32] The reference to a Merkle tree collection which is a hash of al...
pub version: i32, pub prev_block: [u8; 32], pub merkle_root: [u8; 32], pub timestamp: u32, pub bits: u32, pub nonce: u32, /// txn_count is a var_int on the wire pub txn_count: VarInt, }
ockHeader {
identifier_name
block_header.rs
use Encode; use VarInt; #[derive(Debug, Encode, PartialEq)] /// 4 version int32_t Block version information (note, this is signed) /// 32 prev_block char[32] The hash value of the previous block this particular block references /// 32 merkle_root char[32] The reference to a Merkle tree collection which is a hash of al...
}
pub txn_count: VarInt,
random_line_split
mod.rs
use super::{Event, Ins, Prop, Mod, FDVar, Propagator, LeXY, GeXY, LeXYC, GeXYC, LeXC, GeXC}; use std::rc::{Rc, Weak}; /// X = Y pub struct EqXY; impl EqXY { pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>) { // TODO merge or at least intersect domains LeXY::new(model.clone(), x.clone(), y.c...
fn x(&self) -> Rc<FDVar> { self.vars.get(0).clone() } fn y(&self) -> Rc<FDVar> { self.vars.get(1).clone() } } impl Propagator for NeqXYCxy { fn id(&self) -> uint { self.id } fn model(&self) -> Weak<Mod> { self.model.clone() } fn events(&self) -> V...
{ let id = model.propagators.borrow().len(); let this = NeqXYCxy { model: model.downgrade(), id: id, vars: vec![x, y], c: c}; let p = Rc::new((box this) as Box<Propagator>); model.add_prop(p); }
identifier_body