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
group.rs
use std::slice; use std::mem::{ transmute, size_of }; use libc::*; use ::core::{ Tox, Friend, Group, Peer }; use super::{ ffi }; pub type AvGroupCallback = Fn(Group, Peer, &[i16], u32, u8, u32); pub trait AvGroupCreate { fn create_group_av(&self, cb: Box<AvGroupCallback>) -> Result<Group, ()>; fn join_av(&se...
( core: *mut c_void, group_number: c_int, peer_number: c_int, pcm: *const int16_t, samples: c_uint, channels: uint8_t, sample_rate: c_uint, cb: *mut c_void ) { unsafe { let group = Group::from(transmute(core), group_number); let peer = Peer::from(&group, peer_number);...
on_group_av
identifier_name
htmlparamelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLParamElementBinding; use dom::bindings::root::DomRoot; use dom::document...
#[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLParamElement> { Node::reflect_node(Box::new(HTMLParamElement::new_inherited(local_name, prefix, document)), document, ...
{ HTMLParamElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } }
identifier_body
htmlparamelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLParamElementBinding; use dom::bindings::root::DomRoot; use dom::document...
{ htmlelement: HTMLElement } impl HTMLParamElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLParamElement { HTMLParamElement { htmlelement: HTMLElement::new_inherited(local_name, p...
HTMLParamElement
identifier_name
htmlparamelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLParamElementBinding; use dom::bindings::root::DomRoot; use dom::document...
}
}
random_line_split
lookahead.rs
//use std::collections::LinkedList; use token::Token; use std::mem::replace; // test case: x=0;y=g=1;alert(eval("while(x)break\n/y/g.exec('y')")) // see: https://groups.google.com/d/msg/mozilla.dev.tech.js-engine.internals/2JLH5jRcr7E/Mxc7ZKc5r6sJ pub struct Buffer { //tokens: LinkedList<Token> token: O...
(&mut self, token: Token) { //assert!(self.tokens.len() == 0); //self.tokens.push_back(token); debug_assert!(self.token.is_none()); self.token = Some(token) } pub fn read_token(&mut self) -> Token { //assert!(self.tokens.len() > 0); //self.tokens.pop_front().unwr...
push_token
identifier_name
lookahead.rs
//use std::collections::LinkedList; use token::Token; use std::mem::replace; // test case: x=0;y=g=1;alert(eval("while(x)break\n/y/g.exec('y')"))
pub struct Buffer { //tokens: LinkedList<Token> token: Option<Token> } impl Buffer { pub fn new() -> Buffer { Buffer { token: None //tokens: LinkedList::new() } } pub fn is_empty(&mut self) -> bool { //self.tokens.len() == 0 self.token.is_no...
// see: https://groups.google.com/d/msg/mozilla.dev.tech.js-engine.internals/2JLH5jRcr7E/Mxc7ZKc5r6sJ
random_line_split
lookahead.rs
//use std::collections::LinkedList; use token::Token; use std::mem::replace; // test case: x=0;y=g=1;alert(eval("while(x)break\n/y/g.exec('y')")) // see: https://groups.google.com/d/msg/mozilla.dev.tech.js-engine.internals/2JLH5jRcr7E/Mxc7ZKc5r6sJ pub struct Buffer { //tokens: LinkedList<Token> token: O...
pub fn peek_token(&mut self) -> &Token { //assert!(self.tokens.len() > 0); //self.tokens.front().unwrap() debug_assert!(self.token.is_some()); self.token.as_ref().unwrap() } pub fn unread_token(&mut self, token: Token) { //assert!(self.tokens.len() < 3); //...
{ //assert!(self.tokens.len() > 0); //self.tokens.pop_front().unwrap() debug_assert!(self.token.is_some()); replace(&mut self.token, None).unwrap() }
identifier_body
expect-fn-supply-fn-multiple.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { with_closure_expecting_different_anon(|x: Different<'_, '_>| { }) } fn supplying_underscore_expecting_named() { with_closure_expecting_different(|x: Different<'_, '_>| { }) } fn main() { }
supplying_underscore_expecting_anon
identifier_name
expect-fn-supply-fn-multiple.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn supplying_nothing_expecting_named() { with_closure_expecting_different(|x: Different| { }) } fn supplying_underscore_expecting_anon() { with_closure_expecting_different_anon(|x: Different<'_, '_>| { }) } fn supplying_underscore_expecting_named() { with_closure_expecting_different(|x: Differen...
{ with_closure_expecting_different_anon(|x: Different| { }) }
identifier_body
expect-fn-supply-fn-multiple.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ } fn with_closure_expecting_different_anon<F>(_: F) where F: FnOnce(Different<'_, '_>) { } fn supplying_nothing_expecting_anon() { with_closure_expecting_different_anon(|x: Different| { }) } fn supplying_nothing_expecting_named() { with_closure_expecting_different(|x: Different| { }) } fn supp...
where F: for<'a, 'b> FnOnce(Different<'a, 'b>)
random_line_split
owned-ptr-static-bound.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, T>(&'a A<T>); trait X {} impl<'a, T> X for B<'a, T> {} fn f<'a, T, U>(v: ~A<T>) -> ~X: { ~B(v) as ~X: //~ ERROR value may contain references; add `'static` bound to `T` } fn g<'a, T, U>(v: ~A<U>) -> ~X: { ~B(v) as ~X: //~ ERROR value may contain references; add `'static` bound to `U` } fn h<'a, T:'stat...
B
identifier_name
owned-ptr-static-bound.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 ...
{}
identifier_body
owned-ptr-static-bound.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 h<'a, T:'static>(v: ~A<T>) -> ~X: { ~B(v) as ~X: // ok } fn main() {}
} fn g<'a, T, U>(v: ~A<U>) -> ~X: { ~B(v) as ~X: //~ ERROR value may contain references; add `'static` bound to `U`
random_line_split
constants.rs
extern crate classfile; use std::f32; use std::f64; use std::fs::File; use classfile::*; use classfile::reader::ClassReader; macro_rules! assert_float_eq { ($epsilon:expr, $a:expr, $b:expr) => {{ assert!(($a - $b).abs() < $epsilon); }} } #[test] fn should_constants_class() { // Given let mut...
{ println!("looking up field {}", field_name); let field = class.find_field(field_name).unwrap(); let const_value_index = field.attrs.constant_value().unwrap(); &class.constants[const_value_index] }
identifier_body
constants.rs
extern crate classfile; use std::f32; use std::f64; use std::fs::File; use classfile::*; use classfile::reader::ClassReader; macro_rules! assert_float_eq { ($epsilon:expr, $a:expr, $b:expr) => {{ assert!(($a - $b).abs() < $epsilon); }} } #[test] fn should_constants_class() { // Given let mut...
<'a>(field_name: &str, class: &'a ClassFile) -> &'a Constant { println!("looking up field {}", field_name); let field = class.find_field(field_name).unwrap(); let const_value_index = field.attrs.constant_value().unwrap(); &class.constants[const_value_index] }
get_const_value
identifier_name
constants.rs
extern crate classfile; use std::f32; use std::f64; use std::fs::File; use classfile::*; use classfile::reader::ClassReader; macro_rules! assert_float_eq { ($epsilon:expr, $a:expr, $b:expr) => {{ assert!(($a - $b).abs() < $epsilon); }} } #[test] fn should_constants_class() { // Given let mut...
assert!( !constant_value.is_some(), "Object fields should not have a ConstantValue attribute"); } fn get_const_value<'a>(field_name: &str, class: &'a ClassFile) -> &'a Constant { println!("looking up field {}", field_name); let field = class.find_field(field_name).unwrap(); let const_val...
let constant_value = object_field.attrs.constant_value();
random_line_split
mod_power_of_2_sub.rs
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base_test_util::generators::{unsigned_pair_gen_var_17, unsigned_triple_gen_var_11}; fn mod_power_of_2_sub_helper<T: PrimitiveUnsigned>() { let test = |x: T, y: T, pow, out| { assert_eq!(x.mod_power_of_2_sub(y, pow), out); ...
test(T::ZERO, T::ONE, T::WIDTH, T::MAX); test(T::ONE, T::MAX, T::WIDTH, T::TWO); } #[test] fn test_mod_power_of_2_sub() { apply_fn_to_unsigneds!(mod_power_of_2_sub_helper); } fn mod_power_of_2_sub_properties_helper<T: PrimitiveUnsigned>() { unsigned_triple_gen_var_11::<T>().test_properties(|(x, y, pow...
T::exact_from(156), );
random_line_split
mod_power_of_2_sub.rs
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base_test_util::generators::{unsigned_pair_gen_var_17, unsigned_triple_gen_var_11}; fn
<T: PrimitiveUnsigned>() { let test = |x: T, y: T, pow, out| { assert_eq!(x.mod_power_of_2_sub(y, pow), out); let mut x = x; x.mod_power_of_2_sub_assign(y, pow); assert_eq!(x, out); }; test(T::ZERO, T::ZERO, 0, T::ZERO); test(T::ZERO, T::ONE, 1, T::ONE); test(T::ONE,...
mod_power_of_2_sub_helper
identifier_name
mod_power_of_2_sub.rs
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base_test_util::generators::{unsigned_pair_gen_var_17, unsigned_triple_gen_var_11}; fn mod_power_of_2_sub_helper<T: PrimitiveUnsigned>() { let test = |x: T, y: T, pow, out| { assert_eq!(x.mod_power_of_2_sub(y, pow), out); ...
{ apply_fn_to_unsigneds!(mod_power_of_2_sub_properties_helper); }
identifier_body
test_utils.rs
#![cfg(test)] use lazy_static::lazy_static; use std::collections::HashMap; use std::ffi::OsString; use std::fmt::Debug; use std::sync::{Mutex, MutexGuard}; pub const SECRET: &str = &"TtnuieannGt2rGuie2t8Tt7urarg5nauedRndrur"; pub fn
<D>(obj: &D) -> bool where D: Debug, { let debug = format!("{:?}", obj); !debug.contains(SECRET) && debug.contains("**********") } // cargo runs tests in parallel, which leads to race conditions when changing environment // variables. Therefore we use a global mutex for all tests which rely on environment v...
is_secret_hidden_behind_asterisks
identifier_name
test_utils.rs
#![cfg(test)] use lazy_static::lazy_static; use std::collections::HashMap; use std::ffi::OsString; use std::fmt::Debug; use std::sync::{Mutex, MutexGuard}; pub const SECRET: &str = &"TtnuieannGt2rGuie2t8Tt7urarg5nauedRndrur"; pub fn is_secret_hidden_behind_asterisks<D>(obj: &D) -> bool where D: Debug,
// cargo runs tests in parallel, which leads to race conditions when changing environment // variables. Therefore we use a global mutex for all tests which rely on environment variables. // // As failed (panic) tests will poison the global mutex, we use a helper which recovers from // poisoned mutex. // // The first ...
{ let debug = format!("{:?}", obj); !debug.contains(SECRET) && debug.contains("**********") }
identifier_body
test_utils.rs
#![cfg(test)] use lazy_static::lazy_static; use std::collections::HashMap; use std::ffi::OsString; use std::fmt::Debug; use std::sync::{Mutex, MutexGuard}; pub const SECRET: &str = &"TtnuieannGt2rGuie2t8Tt7urarg5nauedRndrur"; pub fn is_secret_hidden_behind_asterisks<D>(obj: &D) -> bool where D: Debug, { let ...
// As failed (panic) tests will poison the global mutex, we use a helper which recovers from // poisoned mutex. // // The first time the helper is called it stores the original environment. If the lock is poisoned, // the environment is reset to the original state. pub fn lock_env() -> MutexGuard<'static, ()> { laz...
} // cargo runs tests in parallel, which leads to race conditions when changing environment // variables. Therefore we use a global mutex for all tests which rely on environment variables. //
random_line_split
test_list.rs
/* * Test for EinaList. */ extern crate efl; use efl::eina; fn main()
None => { println!("No next! Returning same"); strlst } Some(next) => { println!("Next: {}", eina::list_data_get(next)); next } }; let last = match eina::list_last(strlst) { ...
{ eina::init(); let mut strlst: *mut eina::_EinaList<&'static str> = eina::list_append(None, &("Rust")); println!("Last Value? {}", eina::list_last_data_get(strlst)); println!("Next Value? {}", eina::list_next(strlst)); println!("Previous Value? {}", eina::list_prev(strlst)); // Prep...
identifier_body
test_list.rs
/* * Test for EinaList. */ extern crate efl; use efl::eina; fn
() { eina::init(); let mut strlst: *mut eina::_EinaList<&'static str> = eina::list_append(None, &("Rust")); println!("Last Value? {}", eina::list_last_data_get(strlst)); println!("Next Value? {}", eina::list_next(strlst)); println!("Previous Value? {}", eina::list_prev(strlst)); // P...
main
identifier_name
test_list.rs
/* * Test for EinaList. */ extern crate efl; use efl::eina; fn main() { eina::init(); let mut strlst: *mut eina::_EinaList<&'static str> = eina::list_append(None, &("Rust")); println!("Last Value? {}", eina::list_last_data_get(strlst)); println!("Next Value? {}", eina::list_next(strlst))...
Some(last) => { println!("Last Value: {}", eina::list_data_get(last)); last } }; // Change first value let v: &&'static str = &("Rust Enlightenment"); eina::list_data_set(strlst, v); // Change last value let n: &&'static str = &("EnLi...
{ panic!("No last?!") }
conditional_block
test_list.rs
/* * Test for EinaList. */ extern crate efl; use efl::eina; fn main() { eina::init(); let mut strlst: *mut eina::_EinaList<&'static str> = eina::list_append(None, &("Rust")); println!("Last Value? {}", eina::list_last_data_get(strlst)); println!("Next Value? {}", eina::list_next(strlst))...
eina::shutdown(); }
strlst = eina::list_append(Some(strlst), &("e rust")); println!("List new count: {}", eina::list_count(strlst)); println!("New added value {}", eina::list_last_data_get(strlst)); eina::list_free(strlst);
random_line_split
hub_api.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/. //! Implementation of the Philips Hue API //! //! This module is used in various places, for example in the Hub //! o...
pub fn set_light_brightness(&self, light_id: &str, bri: u32) { let url = format!("lights/{}/state", light_id); let cmd = json!({ bri: bri }); let _ = self.put(&url, &cmd); } }
{ let (hue, sat, val) = hsv; let url = format!("lights/{}/state", light_id); let cmd = json!({ hue: hue, sat: sat, bri: val }); let _ = self.put(&url, &cmd); }
identifier_body
hub_api.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/.
//! This module is used in various places, for example in the Hub //! objects and in the Light objects. use serde_json; use std; use std::collections::BTreeMap; use std::error::Error; use super::http; use super::structs; #[derive(Debug, Clone)] pub struct HubApi { pub id: String, pub ip: String, pub token...
//! Implementation of the Philips Hue API //!
random_line_split
hub_api.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/. //! Implementation of the Philips Hue API //! //! This module is used in various places, for example in the Hub //! o...
(&self) -> bool { let url = format!("http://{}/", self.ip); let content = http::get(&url); match content { Ok(value) => value.contains("hue personal wireless lighting"), Err(_) => false, } } pub fn get_settings(&self) -> String { // [{"error":{"ty...
is_available
identifier_name
memory_field.rs
pub use Instruction; #[derive(Copy, Clone)] pub enum MemoryField { InstructionCell(Instruction), MemoryCell(u16), /// This is just to yield a better memory alignment to 8 bytes Padding(u32), } impl MemoryField {
MemoryField::InstructionCell(_) => true, _ => false } } pub fn is_memory(&self) -> bool { match *self { MemoryField::MemoryCell(_) => true, _ => false } } pub fn get_instructi...
pub fn is_instruction(&self) -> bool { match *self {
random_line_split
memory_field.rs
pub use Instruction; #[derive(Copy, Clone)] pub enum MemoryField { InstructionCell(Instruction), MemoryCell(u16), /// This is just to yield a better memory alignment to 8 bytes Padding(u32), } impl MemoryField { pub fn is_instruction(&self) -> bool { match *self { MemoryField::...
(&self) -> u16 { match *self { MemoryField::MemoryCell(x) => x, _ => 0 } } }
get_memory
identifier_name
memory_field.rs
pub use Instruction; #[derive(Copy, Clone)] pub enum MemoryField { InstructionCell(Instruction), MemoryCell(u16), /// This is just to yield a better memory alignment to 8 bytes Padding(u32), } impl MemoryField { pub fn is_instruction(&self) -> bool { match *self { MemoryField::...
pub fn get_instruction(&self) -> Option<Instruction> { match *self { MemoryField::InstructionCell(inst) => Some(inst), _ => None } } pub fn set_cell_value(&mut self, value: u16) { match *self { MemoryField::Memor...
{ match *self { MemoryField::MemoryCell(_) => true, _ => false } }
identifier_body
known_bug_excentric_convex.rs
/*! * # Expected behaviour: * Same as the box_vee3d demo. * * It seems to behave as expected if the excentricity is not too big (tested with 10 and 100). * * # Symptoms: * Some object just fall through the ground, missing any collison. Then, after a while they seem * to notice that they are deep into the plane,...
/* * Set up the testbed. */ let mut testbed = Testbed::new(world); testbed.look_at(Pnt3::new(-30.0, 30.0, -30.0), Pnt3::new(0.0, 0.0, 0.0)); testbed.run(); }
}
random_line_split
known_bug_excentric_convex.rs
/*! * # Expected behaviour: * Same as the box_vee3d demo. * * It seems to behave as expected if the excentricity is not too big (tested with 10 and 100). * * # Symptoms: * Some object just fall through the ground, missing any collison. Then, after a while they seem * to notice that they are deep into the plane,...
{ /* * World */ let mut world = World::new(); world.set_gravity(Vec3::new(0.0, -9.81, 0.0)); /* * Plane */ let geom = Plane::new(Vec3::new(0.0, 1.0, 0.0)); world.add_body(RigidBody::new_static(geom, 0.3, 0.6)); /* * Create the convex geometries. */ let n...
in()
identifier_name
known_bug_excentric_convex.rs
/*! * # Expected behaviour: * Same as the box_vee3d demo. * * It seems to behave as expected if the excentricity is not too big (tested with 10 and 100). * * # Symptoms: * Some object just fall through the ground, missing any collison. Then, after a while they seem * to notice that they are deep into the plane,...
let centerz = shift * (num as f32) / 2.0; for i in 0usize.. num { for j in 0usize.. num { for k in 0usize.. num { let excentricity = 5000.0; let x = i as f32 * shift - centerx - excentricity; let y = j as f32 * shift + centery - excentricity; ...
/* * World */ let mut world = World::new(); world.set_gravity(Vec3::new(0.0, -9.81, 0.0)); /* * Plane */ let geom = Plane::new(Vec3::new(0.0, 1.0, 0.0)); world.add_body(RigidBody::new_static(geom, 0.3, 0.6)); /* * Create the convex geometries. */ let num ...
identifier_body
model_solid_linear_elastic.rs
#![allow(dead_code, unused_mut, unused_variables)] use super::{ModelSolid, ModelSolidState}; use crate::StrError; use russell_lab::{add_vectors, copy_matrix, copy_vector, Vector}; use russell_tensor::{t4_ddot_t2, LinElasticity, Tensor2, Tensor4}; pub struct ModelSolidLinearElastic { two_dim: bool, lin_elastic...
let dd_elastic = self.lin_elasticity.get_modulus(); copy_matrix(&mut dd_new.mat, &dd_elastic.mat) } }
state_new: &ModelSolidState, first_iteration: bool, ) -> Result<(), StrError> {
random_line_split
model_solid_linear_elastic.rs
#![allow(dead_code, unused_mut, unused_variables)] use super::{ModelSolid, ModelSolidState}; use crate::StrError; use russell_lab::{add_vectors, copy_matrix, copy_vector, Vector}; use russell_tensor::{t4_ddot_t2, LinElasticity, Tensor2, Tensor4}; pub struct ModelSolidLinearElastic { two_dim: bool, lin_elastic...
/// Updates state for given delta_strain fn update_state( &self, state_new: &mut ModelSolidState, state: &ModelSolidState, delta_strain: &Tensor2, ) -> Result<(), StrError> { // update strain let eps_new = &mut state_new.strain.vec; let eps = &state....
{ let mut stress = Tensor2::new(true, self.two_dim); copy_vector(&mut stress.vec, &stress_ini.vec)?; Ok(ModelSolidState { stress, strain: Tensor2::new(true, self.two_dim), ivs: Vector::new(0), }) }
identifier_body
model_solid_linear_elastic.rs
#![allow(dead_code, unused_mut, unused_variables)] use super::{ModelSolid, ModelSolidState}; use crate::StrError; use russell_lab::{add_vectors, copy_matrix, copy_vector, Vector}; use russell_tensor::{t4_ddot_t2, LinElasticity, Tensor2, Tensor4}; pub struct ModelSolidLinearElastic { two_dim: bool, lin_elastic...
(young: f64, poisson: f64, two_dim: bool, plane_stress: bool) -> Self { ModelSolidLinearElastic { two_dim, lin_elasticity: LinElasticity::new(young, poisson, two_dim, plane_stress), } } } impl ModelSolid for ModelSolidLinearElastic { /// Calculates internal values and in...
new
identifier_name
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ mod de; mod error; mod ser; #[cfg(test)] mod tests; use self::de::Deserializer; use self::ser::Serializer; use serde::{Deserialize, Seriali...
<T>(value: &T) -> Result<Vec<u8>> where T: Serialize, { let mut out = Vec::new(); serialize_into(&mut out, value)?; Ok(out) } pub fn serialize_into<W, T:?Sized>(writer: W, value: &T) -> Result<()> where W: io::Write, T: Serialize, { let mut ser = Serializer::new(writer); Serialize::seri...
serialize
identifier_name
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ mod de; mod error; mod ser; #[cfg(test)] mod tests; use self::de::Deserializer; use self::ser::Serializer; use serde::{Deserialize, Seriali...
pub fn serialize_into<W, T:?Sized>(writer: W, value: &T) -> Result<()> where W: io::Write, T: Serialize, { let mut ser = Serializer::new(writer); Serialize::serialize(value, &mut ser) } pub fn deserialize<'de, T>(bytes: &'de [u8]) -> Result<T> where T: Deserialize<'de>, { let mut de = Deseria...
{ let mut out = Vec::new(); serialize_into(&mut out, value)?; Ok(out) }
identifier_body
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ mod de; mod error; mod ser; #[cfg(test)] mod tests; use self::de::Deserializer; use self::ser::Serializer; use serde::{Deserialize, Seriali...
{ let mut out = Vec::new(); serialize_into(&mut out, value)?; Ok(out) } pub fn serialize_into<W, T:?Sized>(writer: W, value: &T) -> Result<()> where W: io::Write, T: Serialize, { let mut ser = Serializer::new(writer); Serialize::serialize(value, &mut ser) } pub fn deserialize<'de, T>(bytes...
random_line_split
sound_cpal.rs
//! Real Audio SDL backend use crate::app::{ settings::Settings, sound::{SoundDevice, ZXSample, CHANNEL_COUNT}, }; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use std::sync::mpsc; pub struct SoundCpal { tx: mpsc::Sender<ZXSample>, sample_rate: usize, // Keep stream alive until Drop ...
} fn create_stream<T>( device: &cpal::Device, config: &cpal::StreamConfig, samples_rx: mpsc::Receiver<ZXSample>, ) -> anyhow::Result<cpal::Stream> where T: cpal::Sample, { let channels = config.channels as usize; let stream = device.build_output_stream( config, move |out: &mut...
{ self.sample_rate }
identifier_body
sound_cpal.rs
//! Real Audio SDL backend use crate::app::{ settings::Settings, sound::{SoundDevice, ZXSample, CHANNEL_COUNT}, }; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use std::sync::mpsc; pub struct SoundCpal { tx: mpsc::Sender<ZXSample>, sample_rate: usize, // Keep stream alive until Drop ...
c.channels() == CHANNEL_COUNT as u16 }) .ok_or_else(|| { anyhow::anyhow!("Sound device does not support required configuration") })?; let config = if let Some(sample_rate) = settings.sound_sample_rate { config.with_sample_rate(cpa...
{ if sample_rate < c.min_sample_rate().0 as usize || sample_rate > c.max_sample_rate().0 as usize { return false; } }
conditional_block
sound_cpal.rs
//! Real Audio SDL backend use crate::app::{ settings::Settings, sound::{SoundDevice, ZXSample, CHANNEL_COUNT}, }; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use std::sync::mpsc; pub struct SoundCpal { tx: mpsc::Sender<ZXSample>, sample_rate: usize, // Keep stream alive until Drop ...
(&self) -> usize { self.sample_rate } } fn create_stream<T>( device: &cpal::Device, config: &cpal::StreamConfig, samples_rx: mpsc::Receiver<ZXSample>, ) -> anyhow::Result<cpal::Stream> where T: cpal::Sample, { let channels = config.channels as usize; let stream = device.build_outpu...
sample_rate
identifier_name
sound_cpal.rs
//! Real Audio SDL backend use crate::app::{ settings::Settings, sound::{SoundDevice, ZXSample, CHANNEL_COUNT}, }; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use std::sync::mpsc; pub struct SoundCpal { tx: mpsc::Sender<ZXSample>, sample_rate: usize, // Keep stream alive until Drop ...
.default_output_device() .ok_or_else(|| anyhow::anyhow!("Failed to acquire cpal sound host"))?; let config = device .supported_output_configs()? .find(|c| { if let Some(sample_rate) = settings.sound_sample_rate { if sample_rate < c...
impl SoundCpal { /// Constructs sound backend from settings pub fn new(settings: &Settings) -> anyhow::Result<SoundCpal> { let host = cpal::default_host(); let device = host
random_line_split
eager_drop.rs
extern crate futures; use std::sync::mpsc::channel; use futures::Poll; use futures::future::*; use futures::sync::oneshot; mod support; use support::*; #[test] fn map() { // Whatever runs after a `map` should have dropped the closure by that // point. let (tx, rx) = channel::<()>(); let (tx2, rx2) =...
impl<F: Future, T: Send +'static> Future for FutureData<F, T> { type Item = F::Item; type Error = F::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { self.future.poll() } } #[test] fn and_then_drops_eagerly() { let (c, p) = oneshot::channel::<()>(); let (tx, rx) = channel:...
random_line_split
eager_drop.rs
extern crate futures; use std::sync::mpsc::channel; use futures::Poll; use futures::future::*; use futures::sync::oneshot; mod support; use support::*; #[test] fn map() { // Whatever runs after a `map` should have dropped the closure by that // point. let (tx, rx) = channel::<()>(); let (tx2, rx2) =...
() { let (c, p) = oneshot::channel::<()>(); let (tx, rx) = channel::<()>(); let (tx2, rx2) = channel(); FutureData { _data: tx, future: p }.and_then(move |_| { assert!(rx.recv().is_err()); tx2.send(()).unwrap(); ok(1) }).forget(); assert!(rx2.try_recv().is_err()); c.c...
and_then_drops_eagerly
identifier_name
eager_drop.rs
extern crate futures; use std::sync::mpsc::channel; use futures::Poll; use futures::future::*; use futures::sync::oneshot; mod support; use support::*; #[test] fn map()
#[test] fn map_err() { // Whatever runs after a `map_err` should have dropped the closure by that // point. let (tx, rx) = channel::<()>(); let (tx2, rx2) = channel(); ok::<i32, i32>(1).map_err(move |a| { drop(tx); a }).map(move |_| { assert!(rx.recv().is_err()); tx2.send(()).unwra...
{ // Whatever runs after a `map` should have dropped the closure by that // point. let (tx, rx) = channel::<()>(); let (tx2, rx2) = channel(); err::<i32, i32>(1).map(move |a| { drop(tx); a }).map_err(move |_| { assert!(rx.recv().is_err()); tx2.send(()).unwrap() }).forget(); r...
identifier_body
provider_client.rs
use super::*; use pact_matching::models::*; use pact_matching::models::matchingrules::MatchingRules; use std::str::FromStr; use std::collections::hash_map::HashMap; use std::io::Read; use hyper::client::Client; use hyper::client::response::Response as HyperResponse; use hyper::error::Error as HyperError; use hyper::met...
fn setup_headers(headers: &Option<HashMap<String, String>>) -> Headers { let mut hyper_headers = Headers::new(); if headers.is_some() { let headers = headers.clone().unwrap(); for (k, v) in headers.clone() { hyper_headers.set_raw(k.clone(), vec![v.bytes().collect()]); } ...
{ let mut full_path = s!(base.trim_right_matches("/")); full_path.push('/'); full_path.push_str(path.trim_left_matches("/")); full_path }
identifier_body
provider_client.rs
use super::*; use pact_matching::models::*; use pact_matching::models::matchingrules::MatchingRules; use std::str::FromStr; use std::collections::hash_map::HashMap; use std::io::Read; use hyper::client::Client; use hyper::client::response::Response as HyperResponse; use hyper::error::Error as HyperError; use hyper::met...
None } } pub fn extract_body(response: &mut HyperResponse) -> OptionalBody { let mut buffer = Vec::new(); match response.read_to_end(&mut buffer) { Ok(size) => if size > 0 { OptionalBody::Present(buffer) } else { OptionalBody::Empty },...
if headers.len() > 0 { Some(headers.iter().map(|h| (s!(h.name()), h.value_string()) ).collect()) } else {
random_line_split
provider_client.rs
use super::*; use pact_matching::models::*; use pact_matching::models::matchingrules::MatchingRules; use std::str::FromStr; use std::collections::hash_map::HashMap; use std::io::Read; use hyper::client::Client; use hyper::client::response::Response as HyperResponse; use hyper::error::Error as HyperError; use hyper::met...
(headers: &Option<HashMap<String, String>>) -> Headers { let mut hyper_headers = Headers::new(); if headers.is_some() { let headers = headers.clone().unwrap(); for (k, v) in headers.clone() { hyper_headers.set_raw(k.clone(), vec![v.bytes().collect()]); } if!headers.k...
setup_headers
identifier_name
provider_client.rs
use super::*; use pact_matching::models::*; use pact_matching::models::matchingrules::MatchingRules; use std::str::FromStr; use std::collections::hash_map::HashMap; use std::io::Read; use hyper::client::Client; use hyper::client::response::Response as HyperResponse; use hyper::error::Error as HyperError; use hyper::met...
else { None } } pub fn extract_body(response: &mut HyperResponse) -> OptionalBody { let mut buffer = Vec::new(); match response.read_to_end(&mut buffer) { Ok(size) => if size > 0 { OptionalBody::Present(buffer) } else { OptionalBody::Empty ...
{ Some(headers.iter().map(|h| (s!(h.name()), h.value_string()) ).collect()) }
conditional_block
expr.rs
// Copyright 2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed // except according to those terms. use std::fmt::{Show, Formatter, Result}; use std::from_str::FromStr; use std::num::One; use...
if digit.is_zero() { break; } let digit = match digit.to_uint() { Some(v) => v, None => return Err("float_print: failure to print digit".to_string()) }; let char_digit = match char...
{ let mut s = v.to_integer().to_string(); let mut v = v.fract(); if !v.is_zero() { s.push_char('.'); let ten: BigInt = match FromPrimitive::from_int(10) { Some(v) => v, None => return Err("float_print: unable to parse 10. Highly unlikely."....
identifier_body
expr.rs
// Copyright 2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed // except according to those terms. use std::fmt::{Show, Formatter, Result}; use std::from_str::FromStr; use std::num::One; use...
(self) -> SchemerResult<BigRational> { match self { Atom(Integer(v)) => Ok(Ratio::new(v, One::one())), Atom(Float(v)) => Ok(v), _ => Err("calling into_float() on non-numeric value".to_string()) } } pub fn into_integer(self) -> SchemerResult<BigInt> { m...
into_float
identifier_name
expr.rs
// Copyright 2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed // except according to those terms. use std::fmt::{Show, Formatter, Result}; use std::from_str::FromStr; use std::num::One; use...
, false => { match FromStr::from_str(input.as_slice()) { Some(val) => Ok(Atom(Integer(val))), None => Err(format!("Cannot parse number-like input of: {}", input)) ...
{ let parsed_val: Option<f64> = FromStr::from_str(input.as_slice()); match parsed_val { Some(val) => { let new_float = match Number::float(val) { Ok...
conditional_block
expr.rs
// Copyright 2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed // except according to those terms. use std::fmt::{Show, Formatter, Result}; use std::from_str::FromStr; use std::num::One; use...
} let digit = match digit.to_uint() { Some(v) => v, None => return Err("float_print: failure to print digit".to_string()) }; let char_digit = match char::from_digit(digit, 10) { Some(v) => v, ...
let digit = v.to_integer(); // should only be 1 digit // bail out when we hit a zero in the decimal portion if digit.is_zero() { break;
random_line_split
bls.rs
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this f...
(sig: &mut [u8], m: &str, s: &[u8]) -> isize { let d = bls_hashit(m); let mut sc = BIG::frombytes(&s); pair::g1mul(&d, &mut sc).tobytes(sig, true); return BLS_OK; } /* Verify signature given message m, the signature sig, and the public key w */ pub fn verify(sig: &[u8], m: &str, w: &[u8]) -> isize { ...
sign
identifier_name
bls.rs
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this f...
return BLS_FAIL; }
{ return BLS_OK; }
conditional_block
bls.rs
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this f...
pub fn verify(sig: &[u8], m: &str, w: &[u8]) -> isize { let hm = bls_hashit(m); let mut d = ECP::frombytes(&sig); let g = ECP2::generator(); let pk = ECP2::frombytes(&w); d.neg(); // Use new multi-pairing mechanism let mut r = pair::initmp(); pair::another(&mut r, &g, &d); pair::an...
return BLS_OK; } /* Verify signature given message m, the signature sig, and the public key w */
random_line_split
bls.rs
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this f...
/* generate key pair, private key s, public key w */ pub fn key_pair_generate(mut rng: &mut RAND, s: &mut [u8], w: &mut [u8]) -> isize { let q = BIG::new_ints(&rom::CURVE_ORDER); let g = ECP2::generator(); let mut sc = BIG::randomnum(&q, &mut rng); sc.tobytes(s); pair::g2mul(&g, &mut sc).tobytes(w...
{ let mut sh = SHA3::new(SHAKE256); let mut hm: [u8; BFS] = [0; BFS]; let t = m.as_bytes(); for i in 0..m.len() { sh.process(t[i]); } sh.shake(&mut hm, BFS); let P = ECP::mapit(&hm); return P; }
identifier_body
autoderef-method-on-trait.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x = box() (box 3_usize as Box<double>); assert_eq!(x.double(), 6_usize); }
main
identifier_name
autoderef-method-on-trait.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = box() (box 3_usize as Box<double>); assert_eq!(x.double(), 6_usize); }
identifier_body
lint-type-overflow.rs
// Copyright 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-MIT or ...
#[allow(unused_variable)] fn main() { let x1: u8 = 255; // should be OK let x1: u8 = 256; //~ error: literal out of range for its type let x1 = 255_u8; // should be OK let x1 = 256_u8; //~ error: literal out of range for its type let x2: i8 = -128; // should be OK let x1: i8 = 128; //~ error...
{ println!("x {}", x); }
identifier_body
lint-type-overflow.rs
// Copyright 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-MIT or ...
() { let x1: u8 = 255; // should be OK let x1: u8 = 256; //~ error: literal out of range for its type let x1 = 255_u8; // should be OK let x1 = 256_u8; //~ error: literal out of range for its type let x2: i8 = -128; // should be OK let x1: i8 = 128; //~ error: literal out of range for its type...
main
identifier_name
lint-type-overflow.rs
// Copyright 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-MIT or ...
let x1 = 256_u8; //~ error: literal out of range for its type let x2: i8 = -128; // should be OK let x1: i8 = 128; //~ error: literal out of range for its type let x2: i8 = --128; //~ error: literal out of range for its type let x3: i8 = -129; //~ error: literal out of range for its type let x...
fn main() { let x1: u8 = 255; // should be OK let x1: u8 = 256; //~ error: literal out of range for its type let x1 = 255_u8; // should be OK
random_line_split
mod.rs
pub mod chunk; use self::chunk::{Chunk, field::NybbleField}; use crate::aux::{ index_iter::IndexIterSigned, coord::Coord, ModuloSignedExt, DivFloorSignedExt, OptionalizeExt, }; use std::ops::{Add, Sub, Mul, Div, Rem}; type Board = hashbrown::HashMap<Coord<isize>, Chunk>; #[derive(Debug)] pub enu...
(source: Coord<isize>) -> Self { AbsoluteCoord { chunk: source.map(|x| x.div_floor(chunk::DIMENSION as isize)), square: source.map(|x| x.modulo (chunk::DIMENSION as isize)).into(), } } } #[derive(Default)] pub struct Game { pub chunks: Board, chunks_won: u6...
from
identifier_name
mod.rs
pub mod chunk; use self::chunk::{Chunk, field::NybbleField}; use crate::aux::{ index_iter::IndexIterSigned, coord::Coord, ModuloSignedExt, DivFloorSignedExt, OptionalizeExt, }; use std::ops::{Add, Sub, Mul, Div, Rem}; type Board = hashbrown::HashMap<Coord<isize>, Chunk>; #[derive(Debug)] pub enu...
} #[cfg(test)] mod tests { use super::*; #[test] fn chunk_cascade() { let touch_points: [Coord<isize>;5] = [ Coord( 0, 0), Coord( 0, 16), Coord( 8, 24), Coord(16, 8), Coord( 8, 8), ]; let mut game = Game::d...
random_line_split
mod.rs
pub mod chunk; use self::chunk::{Chunk, field::NybbleField}; use crate::aux::{ index_iter::IndexIterSigned, coord::Coord, ModuloSignedExt, DivFloorSignedExt, OptionalizeExt, }; use std::ops::{Add, Sub, Mul, Div, Rem}; type Board = hashbrown::HashMap<Coord<isize>, Chunk>; #[derive(Debug)] pub enu...
pub fn chunks_won(&self) -> u64 { self.chunks_won } pub fn chunks_lost(&self) -> u64 { self.chunks_lost } pub fn get_chunk(&self, chunk: Coord<isize>) -> Option<&Chunk> { self.chunks.get(&chunk) } fn allocate_with_surround(&mut self, chunk: Coord<isize>, square: Coord<usize>) { use hashbro...
{ Game::default() }
identifier_body
mod.rs
pub mod chunk; use self::chunk::{Chunk, field::NybbleField}; use crate::aux::{ index_iter::IndexIterSigned, coord::Coord, ModuloSignedExt, DivFloorSignedExt, OptionalizeExt, }; use std::ops::{Add, Sub, Mul, Div, Rem}; type Board = hashbrown::HashMap<Coord<isize>, Chunk>; #[derive(Debug)] pub enu...
} to_click.optionalize() } pub fn toggle_flag(&mut self, world_coord: Coord<isize>) { let AbsoluteCoord { chunk, square } = world_coord.into(); self.allocate_with_surround(chunk, square); let chunk = self.chunks.get_mut(&chunk).unwrap(); i...
{ let fringe = IndexIterSigned::self_and_adjacent(Coord::<isize>::default()) .filter(|&offset| offset != Coord::default()) .map(|offset| offset + world_coord); to_click.extend(fringe); }
conditional_block
message.rs
use std::mem; const HEADER_LEN: usize = 2; #[derive(PartialEq, Debug)] pub enum MqttType { //Reserved = 0, Connect = 1, // ConnAck = 2, Publish = 3, // PubAck = 4, // PubRec = 5, // PubRel = 6, // PubComp = 7, Subscribe = 8, SubAck = 9, // Unsubscribe = 0xa, // UnsubAck...
let ping_bytes = &[0xc0u8, 0][0..]; assert_eq!(remaining_length(&ping_bytes), 0); } #[test] fn msg_lens() { assert_eq!(remaining_length(&[]), 0); assert_eq!(remaining_length(&[0x15, 5]), 5); assert_eq!(remaining_length(&[0x27, 7]), 7); assert_eq!(remaining_length(&[0x12, 0xc1, 0x02]), 321); ...
#[test] fn ping_len() {
random_line_split
message.rs
use std::mem; const HEADER_LEN: usize = 2; #[derive(PartialEq, Debug)] pub enum MqttType { //Reserved = 0, Connect = 1, // ConnAck = 2, Publish = 3, // PubAck = 4, // PubRec = 5, // PubRel = 6, // PubComp = 7, Subscribe = 8, SubAck = 9, // Unsubscribe = 0xa, // UnsubAck...
} value } #[test] fn connect_len() { assert_eq!(remaining_length(&connect_bytes()), 42); } #[test] fn ping_len() { let ping_bytes = &[0xc0u8, 0][0..]; assert_eq!(remaining_length(&ping_bytes), 0); } #[test] fn msg_lens() { assert_eq!(remaining_length(&[]), 0); assert_eq!(remaining_lengt...
{ digit = bytes[1..][0] as usize; }
conditional_block
message.rs
use std::mem; const HEADER_LEN: usize = 2; #[derive(PartialEq, Debug)] pub enum MqttType { //Reserved = 0, Connect = 1, // ConnAck = 2, Publish = 3, // PubAck = 4, // PubRec = 5, // PubRel = 6, // PubComp = 7, Subscribe = 8, SubAck = 9, // Unsubscribe = 0xa, // UnsubAck...
() { let bytes = &[224, 0][0..]; assert_eq!(message_type(bytes), MqttType::Disconnect); } pub fn remaining_length(bytes: &[u8]) -> usize { if bytes.len() < 2 { return 0; } let bytes = &bytes[1..]; //skip half of the fixed header //algorithm straight from the MQTT spec let mut mul...
disconnect_type
identifier_name
message.rs
use std::mem; const HEADER_LEN: usize = 2; #[derive(PartialEq, Debug)] pub enum MqttType { //Reserved = 0, Connect = 1, // ConnAck = 2, Publish = 3, // PubAck = 4, // PubRec = 5, // PubRel = 6, // PubComp = 7, Subscribe = 8, SubAck = 9, // Unsubscribe = 0xa, // UnsubAck...
#[test] fn subscribe_msg_id_happy() { assert_eq!(subscribe_msg_id(&[0x8cu8, 3, 0, 33]), 33); assert_eq!(subscribe_msg_id(&[0x8cu8, 3, 0, 21]), 21); } pub fn publish_topic(bytes: &[u8]) -> String { //only works when there's no msg id let topic_len = ((bytes[2] as u16) << 8) + bytes[3] as u16; let ...
{ bytes[3] as u16 }
identifier_body
example.rs
const MODULUS: i32 = 26; /// An error type for indicating problems with the input #[derive(Debug, Eq, PartialEq)] pub enum AffineCipherError { NotCoprime(i32), } /// Encodes the plaintext using the affine cipher with key (`a`, `b`). Note that, rather than /// returning a return code, the more common convention in...
} /// Calculates the modular multiplicative inverse using the extended Euclidean algorithm. /// See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm for details. fn modular_multiplicative_inverse(a: i32) -> Option<i32> { // `rs` corresponds to the `r_i` sequence and `ts` corresponds to the `t_i` sequence...
random_line_split
example.rs
const MODULUS: i32 = 26; /// An error type for indicating problems with the input #[derive(Debug, Eq, PartialEq)] pub enum AffineCipherError { NotCoprime(i32), } /// Encodes the plaintext using the affine cipher with key (`a`, `b`). Note that, rather than /// returning a return code, the more common convention in...
} /// Calculates the modular multiplicative inverse using the extended Euclidean algorithm. /// See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm for details. fn modular_multiplicative_inverse(a: i32) -> Option<i32> { // `rs` corresponds to the `r_i` sequence and `ts` corresponds to the `t_i` sequenc...
{ let index = (ch as i32) - ('a' as i32); let decoded = (inv * (index - b)).rem_euclid(MODULUS) + 'a' as i32; decoded as u8 as char }
conditional_block
example.rs
const MODULUS: i32 = 26; /// An error type for indicating problems with the input #[derive(Debug, Eq, PartialEq)] pub enum AffineCipherError { NotCoprime(i32), } /// Encodes the plaintext using the affine cipher with key (`a`, `b`). Note that, rather than /// returning a return code, the more common convention in...
/// Calculates the modular multiplicative inverse using the extended Euclidean algorithm. /// See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm for details. fn modular_multiplicative_inverse(a: i32) -> Option<i32> { // `rs` corresponds to the `r_i` sequence and `ts` corresponds to the `t_i` sequence....
{ if ch.is_digit(10) { ch } else { let index = (ch as i32) - ('a' as i32); let decoded = (inv * (index - b)).rem_euclid(MODULUS) + 'a' as i32; decoded as u8 as char } }
identifier_body
example.rs
const MODULUS: i32 = 26; /// An error type for indicating problems with the input #[derive(Debug, Eq, PartialEq)] pub enum AffineCipherError { NotCoprime(i32), } /// Encodes the plaintext using the affine cipher with key (`a`, `b`). Note that, rather than /// returning a return code, the more common convention in...
(a: i32) -> Option<i32> { // `rs` corresponds to the `r_i` sequence and `ts` corresponds to the `t_i` sequence. We omit // `s_i` since we don't need it to calculate the MMI. let mut rs = (MODULUS, a.rem_euclid(MODULUS)); let mut ts = (0, 1); while rs.1!= 0 { let q = rs.0.div_euclid(rs.1); ...
modular_multiplicative_inverse
identifier_name
reboot.rs
//! Reboot/shutdown or enable/disable Ctrl-Alt-Delete. use {Error, Result}; use errno::Errno; use libc; use void::Void; use std::mem::drop; libc_enum! { /// How exactly should the system be rebooted. /// /// See [`set_cad_enabled()`](fn.set_cad_enabled.html) for /// enabling/disabling Ctrl-Alt-Delete....
(enable: bool) -> Result<()> { let cmd = if enable { libc::RB_ENABLE_CAD } else { libc::RB_DISABLE_CAD }; let res = unsafe { libc::reboot(cmd) }; Errno::result(res).map(drop) }
set_cad_enabled
identifier_name
reboot.rs
//! Reboot/shutdown or enable/disable Ctrl-Alt-Delete. use {Error, Result}; use errno::Errno; use libc; use void::Void; use std::mem::drop; libc_enum! { /// How exactly should the system be rebooted. /// /// See [`set_cad_enabled()`](fn.set_cad_enabled.html) for /// enabling/disabling Ctrl-Alt-Delete....
; let res = unsafe { libc::reboot(cmd) }; Errno::result(res).map(drop) }
{ libc::RB_DISABLE_CAD }
conditional_block
reboot.rs
use {Error, Result}; use errno::Errno; use libc; use void::Void; use std::mem::drop; libc_enum! { /// How exactly should the system be rebooted. /// /// See [`set_cad_enabled()`](fn.set_cad_enabled.html) for /// enabling/disabling Ctrl-Alt-Delete. #[repr(i32)] pub enum RebootMode { RB_...
//! Reboot/shutdown or enable/disable Ctrl-Alt-Delete.
random_line_split
reboot.rs
//! Reboot/shutdown or enable/disable Ctrl-Alt-Delete. use {Error, Result}; use errno::Errno; use libc; use void::Void; use std::mem::drop; libc_enum! { /// How exactly should the system be rebooted. /// /// See [`set_cad_enabled()`](fn.set_cad_enabled.html) for /// enabling/disabling Ctrl-Alt-Delete....
{ let cmd = if enable { libc::RB_ENABLE_CAD } else { libc::RB_DISABLE_CAD }; let res = unsafe { libc::reboot(cmd) }; Errno::result(res).map(drop) }
identifier_body
class-impl-very-parameterized-trait.rs
// Copyright 2012-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...
(&mut self, _k: &int) -> Option<T> { fail!() } fn swap(&mut self, _k: int, _v: T) -> Option<T> { fail!() } } impl<T> cat<T> { pub fn get<'a>(&'a self, k: &int) -> &'a T { match self.find(k) { Some(v) => { v } None => { fail!("epic fail"); } } } pub fn new(in_x: ...
pop
identifier_name
class-impl-very-parameterized-trait.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } } impl<T> Container for cat<T> { fn len(&self) -> uin...
{ self.meow(); }
identifier_body
class-impl-very-parameterized-trait.rs
// Copyright 2012-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...
} fn pop(&mut self, _k: &int) -> Option<T> { fail!() } fn swap(&mut self, _k: int, _v: T) -> Option<T> { fail!() } } impl<T> cat<T> { pub fn get<'a>(&'a self, k: &int) -> &'a T { match self.find(k) { Some(v) => { v } None => { fail!("epic fail"); } } } ...
{ false }
conditional_block
class-impl-very-parameterized-trait.rs
// Copyright 2012-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) as uint) == ((*other) as uint) } fn ne(&self, other: &cat_type) -> bool {!(*self).eq(other) } } // Very silly -- this just returns the value of the name field // for any int value that's less than the meows field // ok: T should be in scope when resolving the trait ref for map struct cat<T> {...
#[deriving(Show)] enum cat_type { tuxedo, tabby, tortoiseshell } impl cmp::Eq for cat_type { fn eq(&self, other: &cat_type) -> bool {
random_line_split
mount.rs
use std; use std::process::{Command, Stdio}; use config::Mount; #[derive(Debug)] pub enum MountError { SpawnFailed(std::io::Error), ExternalCommandFailed(String), } impl From<std::io::Error> for MountError { fn from(err: std::io::Error) -> MountError { MountError::SpawnFailed(err) } } pub fn ...
} #[cfg(test)] mod tests {}
{ let err_text = String::from_utf8(result.stderr).unwrap_or_else(|_| String::from("unable to decode mount stderr")); Err(MountError::ExternalCommandFailed(err_text)) }
conditional_block
mount.rs
use std; use std::process::{Command, Stdio}; use config::Mount; #[derive(Debug)] pub enum
{ SpawnFailed(std::io::Error), ExternalCommandFailed(String), } impl From<std::io::Error> for MountError { fn from(err: std::io::Error) -> MountError { MountError::SpawnFailed(err) } } pub fn mount(config: &Mount, block_device: &str) -> Result<(), MountError> { let mut cmd = Command::new(...
MountError
identifier_name
mount.rs
use std; use std::process::{Command, Stdio}; use config::Mount; #[derive(Debug)] pub enum MountError { SpawnFailed(std::io::Error), ExternalCommandFailed(String), } impl From<std::io::Error> for MountError { fn from(err: std::io::Error) -> MountError { MountError::SpawnFailed(err) } } pub fn ...
Ok(()) } else { let err_text = String::from_utf8(result.stderr).unwrap_or_else(|_| String::from("unable to decode mount stderr")); Err(MountError::ExternalCommandFailed(err_text)) } } #[cfg(test)] mod tests {}
trace!("external mount command succeeded");
random_line_split
init-res-into-things.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let i = box(GC) Cell::new(0i); { let _a = box(GC) Box { x: r(i) }; } assert_eq!(i.get(), 1); } pub fn main() { test_box(); test_rec(); test_tag(); test_tup(); test_unique(); test_box_rec(); }
test_box_rec
identifier_name
init-res-into-things.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn test_rec() { let i = box(GC) Cell::new(0i); { let _a = Box {x: r(i)}; } assert_eq!(i.get(), 1); } fn test_tag() { enum t { t0(r), } let i = box(GC) Cell::new(0i); { let _a = t0(r(i)); } assert_eq!(i.get(), 1); } fn test_tup() { let i = box(GC) ...
{ let i = box(GC) Cell::new(0i); { let _a = box(GC) r(i); } assert_eq!(i.get(), 1); }
identifier_body
init-res-into-things.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 ...
} assert_eq!(i.get(), 1); } pub fn main() { test_box(); test_rec(); test_tag(); test_tup(); test_unique(); test_box_rec(); }
};
random_line_split
errors.rs
// Copyright 2012-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...
{ ThisLine, FollowPrevious(uint), AdjustBackward(uint) } /// Looks for either "//~| KIND MESSAGE" or "//~^^... KIND MESSAGE" /// The former is a "follow" that inherits its target from the preceding line; /// the latter is an "adjusts" that goes that many lines up. /// /// Goal is to enable tests both like: //~^^^ ERR...
WhichLine
identifier_name
errors.rs
// Copyright 2012-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...
fn parse_expected(last_nonfollow_error: Option<uint>, line_num: uint, line: &str) -> Option<(WhichLine, ExpectedError)> { let start = match line.find_str("//~") { Some(i) => i, None => return None }; let (follow, adjusts) = if line.char_at(start + 3) == '|' { (true, ...
random_line_split
errors.rs
// Copyright 2012-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...
else { let which = if adjusts > 0 { AdjustBackward(adjusts) } else { ThisLine }; let line = line_num - adjusts; (which, line) }; debug!("line={} which={:?} kind={:?} msg={:?}", line_num, which, kind, msg); Some((which, ExpectedError { line: line, ...
{ assert!(adjusts == 0, "use either //~| or //~^, not both."); let line = last_nonfollow_error.unwrap_or_else(|| { panic!("encountered //~| without preceding //~^ line.") }); (FollowPrevious(line), line) }
conditional_block
mod.rs
// Copyright (c) 2014 Robert Clipsham <robert@octarineparrot.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. This file may not be copied, modified, or...
} pub fn send_to(socket: CSocket, buffer: &[u8], dst: *const libc::sockaddr, slen: libc::socklen_t) -> io::Result<usize> { let send_len = retry(&mut || unsafe { libc::sendto(socket, buffer.as_ptr() as *const libc::c_void, buffer.len() as BufLen, 0, dst, slen) }); if send...
{ unsafe { close(self.fd); } }
identifier_body
mod.rs
// Copyright (c) 2014 Robert Clipsham <robert@octarineparrot.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. This file may not be copied, modified, or...
impl Drop for FileDesc { fn drop(&mut self) { unsafe { close(self.fd); } } } pub fn send_to(socket: CSocket, buffer: &[u8], dst: *const libc::sockaddr, slen: libc::socklen_t) -> io::Result<usize> { let send_len = retry(&mut || unsafe { libc::sendto(socket, buffer.a...
// Any file descriptor on unix, only sockets on Windows. pub struct FileDesc { pub fd: CSocket, }
random_line_split
mod.rs
// Copyright (c) 2014 Robert Clipsham <robert@octarineparrot.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. This file may not be copied, modified, or...
else { Ok(len as usize) } }
{ Err(io::Error::last_os_error()) }
conditional_block
mod.rs
// Copyright (c) 2014 Robert Clipsham <robert@octarineparrot.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. This file may not be copied, modified, or...
(socket: CSocket, buffer: &[u8], dst: *const libc::sockaddr, slen: libc::socklen_t) -> io::Result<usize> { let send_len = retry(&mut || unsafe { libc::sendto(socket, buffer.as_ptr() as *const libc::c_void, buffer.len() as BufLen, 0, dst, slen) }); if send_len < 0 { ...
send_to
identifier_name
task-spawn-barefn.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 ...
use std::thread; fn main() { // the purpose of this test is to make sure that thread::spawn() // works when provided with a bare function: let r = thread::spawn(startfn).join(); if r.is_err() { panic!() } } fn startfn() { assert!("Ensure that the child thread runs by panicking".is_empt...
// error-pattern:Ensure that the child thread runs by panicking // ignore-emscripten Needs threads.
random_line_split
task-spawn-barefn.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 ...
() { // the purpose of this test is to make sure that thread::spawn() // works when provided with a bare function: let r = thread::spawn(startfn).join(); if r.is_err() { panic!() } } fn startfn() { assert!("Ensure that the child thread runs by panicking".is_empty()); }
main
identifier_name