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(&self, friend: &Friend, data: &[u8], cb: Box<AvGroupCallback>) -> Result<Group, ()>; } impl AvGroupCreate for Tox { fn create_group_av(&self, cb: Box<AvGroupCallback>) -> Result<Group, ()> { match unsafe { ffi::toxav_add_av_groupchat( transmute(self.core), on_group_av, transmute(&cb) ) } { -1 => Err(()), num => Ok(Group::from(self.core, num)) } } fn join_av(&self, friend: &Friend, data: &[u8], cb: Box<AvGroupCallback>) -> Result<Group, ()> { match unsafe { ffi::toxav_join_av_groupchat( transmute(self.core), friend.number as int32_t, data.as_ptr(), data.len() as uint16_t, on_group_av, transmute(&cb) ) } { -1 => Err(()), num => Ok(Group::from(self.core, num)) } } } extern "C" fn
( 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); let callback: &Box<AvGroupCallback> = transmute(cb); callback( group, peer, slice::from_raw_parts(pcm, samples as usize * channels as usize * size_of::<int16_t>()), samples, channels, sample_rate ); } }
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::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLParamElement { htmlelement: HTMLElement } impl HTMLParamElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLParamElement
#[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, HTMLParamElementBinding::Wrap) } }
{ 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::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct
{ htmlelement: HTMLElement } impl HTMLParamElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLParamElement { HTMLParamElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, 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, HTMLParamElementBinding::Wrap) } }
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::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLParamElement { htmlelement: HTMLElement } impl HTMLParamElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLParamElement { HTMLParamElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, 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, HTMLParamElementBinding::Wrap)
}
}
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: 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_none() } pub fn
(&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().unwrap() debug_assert!(self.token.is_some()); replace(&mut self.token, None).unwrap() } 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); //self.tokens.push_front(token); debug_assert!(self.token.is_none()); self.token = Some(token); } }
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_none() } pub fn push_token(&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().unwrap() debug_assert!(self.token.is_some()); replace(&mut self.token, None).unwrap() } 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); //self.tokens.push_front(token); debug_assert!(self.token.is_none()); self.token = Some(token); } }
// 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: 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_none() } pub fn push_token(&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
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); //self.tokens.push_front(token); debug_assert!(self.token.is_none()); self.token = Some(token); } }
{ //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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-pass #![allow(warnings)] type Different<'a, 'b> = &'a mut (&'a (), &'b ()); type Same<'a> = Different<'a, 'a>; fn with_closure_expecting_different<F>(_: F) where F: for<'a, 'b> FnOnce(Different<'a, 'b>) { } 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
() { 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-pass #![allow(warnings)] type Different<'a, 'b> = &'a mut (&'a (), &'b ()); type Same<'a> = Different<'a, 'a>; fn with_closure_expecting_different<F>(_: F) where F: for<'a, 'b> FnOnce(Different<'a, 'b>) { } fn with_closure_expecting_different_anon<F>(_: F) where F: FnOnce(Different<'_, '_>) { } fn supplying_nothing_expecting_anon()
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: Different<'_, '_>| { }) } fn main() { }
{ 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-pass #![allow(warnings)] type Different<'a, 'b> = &'a mut (&'a (), &'b ()); type Same<'a> = Different<'a, 'a>; fn with_closure_expecting_different<F>(_: F)
{ } 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 supplying_underscore_expecting_anon() { with_closure_expecting_different_anon(|x: Different<'_, '_>| { }) } fn supplying_underscore_expecting_named() { with_closure_expecting_different(|x: Different<'_, '_>| { }) } fn main() { }
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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait A<T> {} struct
<'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:'static>(v: ~A<T>) -> ~X: { ~B(v) as ~X: // ok } fn main() {}
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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait A<T> {} struct B<'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:'static>(v: ~A<T>) -> ~X: { ~B(v) as ~X: // ok } fn main()
{}
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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait A<T> {} struct B<'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 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 file = File::open("../test-classes/Constants.class").unwrap(); // When let class = ClassReader::new(&mut file).read_class().unwrap(); // Then // Ints assert_eq!( 0xcafebabeu32 as i32, get_const_value("INT_VALUE", &class).as_integer()); assert_eq!( 2147483647, get_const_value("INT_MAX", &class).as_integer()); assert_eq!( -2147483648, get_const_value("INT_MIN", &class).as_integer()); // Longs assert_eq!( 0xdeadc0ffeebabei64, get_const_value("LONG_VALUE", &class).as_long()); assert_eq!( 9223372036854775807i64, get_const_value("LONG_MAX", &class).as_long()); assert_eq!( -9223372036854775808i64, get_const_value("LONG_MIN", &class).as_long()); // Floats assert_float_eq!( f32::EPSILON, 3.4028235E38f64 as f32, get_const_value("FLOAT_MAX", &class).as_float()); assert_float_eq!( f32::EPSILON, 1.17549435E-38f64 as f32, get_const_value("FLOAT_MIN_NORMAL", &class).as_float()); assert_float_eq!( f32::EPSILON, 1.4E-45f32, get_const_value("FLOAT_MIN", &class).as_float()); let float = get_const_value("FLOAT_NEGATIVE_INF", &class).as_float(); assert!(float.is_sign_negative()); assert!(float.is_infinite()); let float = get_const_value("FLOAT_POSITIVE_INF", &class).as_float(); assert!(!float.is_sign_negative()); assert!(float.is_infinite()); let float = get_const_value("FLOAT_NAN", &class).as_float(); assert!(float.is_nan()); // Doubles assert_float_eq!( f64::EPSILON, 1.7976931348623157E308f64, get_const_value("DOUBLE_MAX", &class).as_double()); assert_float_eq!( f64::EPSILON, 2.2250738585072014E-308f64, get_const_value("DOUBLE_MIN_NORMAL", &class).as_double()); assert_float_eq!( f64::EPSILON, 4.9E-324f64, get_const_value("DOUBLE_MIN", &class).as_double()); let double = get_const_value("DOUBLE_NEGATIVE_INF", &class).as_double(); assert!(double.is_sign_negative()); assert!(double.is_infinite()); let double = get_const_value("DOUBLE_POSITIVE_INF", &class).as_double(); assert!(!double.is_sign_negative()); assert!(double.is_infinite()); let double = get_const_value("DOUBLE_NAN", &class).as_double(); assert!(double.is_nan()); // String let utf8_index = get_const_value("STRING_VALUE", &class).as_string(); assert_eq!( "This is a string constant", class.constants[utf8_index].as_utf8()); // Class let object_field = class.find_field("CLASS_VALUE").unwrap(); let constant_value = object_field.attrs.constant_value(); 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_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 file = File::open("../test-classes/Constants.class").unwrap(); // When let class = ClassReader::new(&mut file).read_class().unwrap(); // Then // Ints assert_eq!( 0xcafebabeu32 as i32, get_const_value("INT_VALUE", &class).as_integer()); assert_eq!( 2147483647, get_const_value("INT_MAX", &class).as_integer()); assert_eq!( -2147483648, get_const_value("INT_MIN", &class).as_integer()); // Longs assert_eq!( 0xdeadc0ffeebabei64, get_const_value("LONG_VALUE", &class).as_long()); assert_eq!( 9223372036854775807i64, get_const_value("LONG_MAX", &class).as_long()); assert_eq!( -9223372036854775808i64, get_const_value("LONG_MIN", &class).as_long()); // Floats assert_float_eq!( f32::EPSILON, 3.4028235E38f64 as f32, get_const_value("FLOAT_MAX", &class).as_float()); assert_float_eq!( f32::EPSILON, 1.17549435E-38f64 as f32, get_const_value("FLOAT_MIN_NORMAL", &class).as_float()); assert_float_eq!( f32::EPSILON, 1.4E-45f32, get_const_value("FLOAT_MIN", &class).as_float()); let float = get_const_value("FLOAT_NEGATIVE_INF", &class).as_float(); assert!(float.is_sign_negative()); assert!(float.is_infinite()); let float = get_const_value("FLOAT_POSITIVE_INF", &class).as_float(); assert!(!float.is_sign_negative()); assert!(float.is_infinite()); let float = get_const_value("FLOAT_NAN", &class).as_float(); assert!(float.is_nan()); // Doubles assert_float_eq!( f64::EPSILON, 1.7976931348623157E308f64, get_const_value("DOUBLE_MAX", &class).as_double()); assert_float_eq!( f64::EPSILON, 2.2250738585072014E-308f64, get_const_value("DOUBLE_MIN_NORMAL", &class).as_double()); assert_float_eq!( f64::EPSILON, 4.9E-324f64, get_const_value("DOUBLE_MIN", &class).as_double()); let double = get_const_value("DOUBLE_NEGATIVE_INF", &class).as_double(); assert!(double.is_sign_negative()); assert!(double.is_infinite()); let double = get_const_value("DOUBLE_POSITIVE_INF", &class).as_double(); assert!(!double.is_sign_negative()); assert!(double.is_infinite()); let double = get_const_value("DOUBLE_NAN", &class).as_double(); assert!(double.is_nan()); // String let utf8_index = get_const_value("STRING_VALUE", &class).as_string(); assert_eq!( "This is a string constant", class.constants[utf8_index].as_utf8()); // Class let object_field = class.find_field("CLASS_VALUE").unwrap(); let constant_value = object_field.attrs.constant_value(); assert!( !constant_value.is_some(), "Object fields should not have a ConstantValue attribute"); } fn
<'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 file = File::open("../test-classes/Constants.class").unwrap(); // When let class = ClassReader::new(&mut file).read_class().unwrap(); // Then // Ints assert_eq!( 0xcafebabeu32 as i32, get_const_value("INT_VALUE", &class).as_integer()); assert_eq!( 2147483647, get_const_value("INT_MAX", &class).as_integer()); assert_eq!( -2147483648, get_const_value("INT_MIN", &class).as_integer()); // Longs assert_eq!( 0xdeadc0ffeebabei64, get_const_value("LONG_VALUE", &class).as_long()); assert_eq!( 9223372036854775807i64, get_const_value("LONG_MAX", &class).as_long()); assert_eq!( -9223372036854775808i64, get_const_value("LONG_MIN", &class).as_long()); // Floats assert_float_eq!( f32::EPSILON, 3.4028235E38f64 as f32, get_const_value("FLOAT_MAX", &class).as_float()); assert_float_eq!( f32::EPSILON, 1.17549435E-38f64 as f32, get_const_value("FLOAT_MIN_NORMAL", &class).as_float()); assert_float_eq!( f32::EPSILON, 1.4E-45f32, get_const_value("FLOAT_MIN", &class).as_float()); let float = get_const_value("FLOAT_NEGATIVE_INF", &class).as_float(); assert!(float.is_sign_negative()); assert!(float.is_infinite()); let float = get_const_value("FLOAT_POSITIVE_INF", &class).as_float(); assert!(!float.is_sign_negative()); assert!(float.is_infinite()); let float = get_const_value("FLOAT_NAN", &class).as_float(); assert!(float.is_nan()); // Doubles assert_float_eq!( f64::EPSILON, 1.7976931348623157E308f64, get_const_value("DOUBLE_MAX", &class).as_double()); assert_float_eq!( f64::EPSILON, 2.2250738585072014E-308f64, get_const_value("DOUBLE_MIN_NORMAL", &class).as_double()); assert_float_eq!( f64::EPSILON, 4.9E-324f64, get_const_value("DOUBLE_MIN", &class).as_double()); let double = get_const_value("DOUBLE_NEGATIVE_INF", &class).as_double(); assert!(double.is_sign_negative()); assert!(double.is_infinite()); let double = get_const_value("DOUBLE_POSITIVE_INF", &class).as_double(); assert!(!double.is_sign_negative()); assert!(double.is_infinite()); let double = get_const_value("DOUBLE_NAN", &class).as_double(); assert!(double.is_nan()); // String let utf8_index = get_const_value("STRING_VALUE", &class).as_string(); assert_eq!( "This is a string constant", class.constants[utf8_index].as_utf8()); // Class let object_field = class.find_field("CLASS_VALUE").unwrap();
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_value_index = field.attrs.constant_value().unwrap(); &class.constants[const_value_index] }
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); 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, T::ONE, 1, T::ZERO); test(T::exact_from(5), T::TWO, 5, T::exact_from(3)); test(T::exact_from(10), T::exact_from(14), 4, T::exact_from(12)); test( T::exact_from(100), T::exact_from(200), 8,
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)| { assert!(x.mod_power_of_2_is_reduced(pow)); assert!(y.mod_power_of_2_is_reduced(pow)); let diff = x.mod_power_of_2_sub(y, pow); assert!(diff.mod_power_of_2_is_reduced(pow)); let mut x_alt = x; x_alt.mod_power_of_2_sub_assign(y, pow); assert_eq!(x_alt, diff); assert_eq!(diff.mod_power_of_2_add(y, pow), x); assert_eq!(diff.mod_power_of_2_sub(x, pow), y.mod_power_of_2_neg(pow)); assert_eq!(y.mod_power_of_2_sub(x, pow), diff.mod_power_of_2_neg(pow)); assert_eq!(x.mod_power_of_2_add(y.mod_power_of_2_neg(pow), pow), diff); }); unsigned_pair_gen_var_17::<T>().test_properties(|(x, pow)| { assert_eq!(x.mod_power_of_2_sub(T::ZERO, pow), x); assert_eq!( T::ZERO.mod_power_of_2_sub(x, pow), x.mod_power_of_2_neg(pow) ); assert_eq!(x.mod_power_of_2_sub(x, pow), T::ZERO); }); } #[test] fn mod_power_of_2_sub_properties() { apply_fn_to_unsigneds!(mod_power_of_2_sub_properties_helper); }
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, T::ONE, 1, T::ZERO); test(T::exact_from(5), T::TWO, 5, T::exact_from(3)); test(T::exact_from(10), T::exact_from(14), 4, T::exact_from(12)); test( T::exact_from(100), T::exact_from(200), 8, T::exact_from(156), ); 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)| { assert!(x.mod_power_of_2_is_reduced(pow)); assert!(y.mod_power_of_2_is_reduced(pow)); let diff = x.mod_power_of_2_sub(y, pow); assert!(diff.mod_power_of_2_is_reduced(pow)); let mut x_alt = x; x_alt.mod_power_of_2_sub_assign(y, pow); assert_eq!(x_alt, diff); assert_eq!(diff.mod_power_of_2_add(y, pow), x); assert_eq!(diff.mod_power_of_2_sub(x, pow), y.mod_power_of_2_neg(pow)); assert_eq!(y.mod_power_of_2_sub(x, pow), diff.mod_power_of_2_neg(pow)); assert_eq!(x.mod_power_of_2_add(y.mod_power_of_2_neg(pow), pow), diff); }); unsigned_pair_gen_var_17::<T>().test_properties(|(x, pow)| { assert_eq!(x.mod_power_of_2_sub(T::ZERO, pow), x); assert_eq!( T::ZERO.mod_power_of_2_sub(x, pow), x.mod_power_of_2_neg(pow) ); assert_eq!(x.mod_power_of_2_sub(x, pow), T::ZERO); }); } #[test] fn mod_power_of_2_sub_properties() { apply_fn_to_unsigneds!(mod_power_of_2_sub_properties_helper); }
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); 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, T::ONE, 1, T::ZERO); test(T::exact_from(5), T::TWO, 5, T::exact_from(3)); test(T::exact_from(10), T::exact_from(14), 4, T::exact_from(12)); test( T::exact_from(100), T::exact_from(200), 8, T::exact_from(156), ); 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)| { assert!(x.mod_power_of_2_is_reduced(pow)); assert!(y.mod_power_of_2_is_reduced(pow)); let diff = x.mod_power_of_2_sub(y, pow); assert!(diff.mod_power_of_2_is_reduced(pow)); let mut x_alt = x; x_alt.mod_power_of_2_sub_assign(y, pow); assert_eq!(x_alt, diff); assert_eq!(diff.mod_power_of_2_add(y, pow), x); assert_eq!(diff.mod_power_of_2_sub(x, pow), y.mod_power_of_2_neg(pow)); assert_eq!(y.mod_power_of_2_sub(x, pow), diff.mod_power_of_2_neg(pow)); assert_eq!(x.mod_power_of_2_add(y.mod_power_of_2_neg(pow), pow), diff); }); unsigned_pair_gen_var_17::<T>().test_properties(|(x, pow)| { assert_eq!(x.mod_power_of_2_sub(T::ZERO, pow), x); assert_eq!( T::ZERO.mod_power_of_2_sub(x, pow), x.mod_power_of_2_neg(pow) ); assert_eq!(x.mod_power_of_2_sub(x, pow), T::ZERO); }); } #[test] fn mod_power_of_2_sub_properties()
{ 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 variables. // // 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, ()> { lazy_static! { static ref ENV_MUTEX: Mutex<()> = Mutex::new(()); static ref ORIGINAL_ENVIRONMENT: HashMap<OsString, OsString> = std::env::vars_os().collect(); } let guard = ENV_MUTEX.lock(); lazy_static::initialize(&ORIGINAL_ENVIRONMENT); match guard { Ok(guard) => guard, Err(poisoned) => { for (name, _) in std::env::vars_os() { if!ORIGINAL_ENVIRONMENT.contains_key(&name) { std::env::remove_var(name); } } for (name, value) in ORIGINAL_ENVIRONMENT.iter() { std::env::set_var(name, value); } poisoned.into_inner() } } }
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 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, ()> { lazy_static! { static ref ENV_MUTEX: Mutex<()> = Mutex::new(()); static ref ORIGINAL_ENVIRONMENT: HashMap<OsString, OsString> = std::env::vars_os().collect(); } let guard = ENV_MUTEX.lock(); lazy_static::initialize(&ORIGINAL_ENVIRONMENT); match guard { Ok(guard) => guard, Err(poisoned) => { for (name, _) in std::env::vars_os() { if!ORIGINAL_ENVIRONMENT.contains_key(&name) { std::env::remove_var(name); } } for (name, value) in ORIGINAL_ENVIRONMENT.iter() { std::env::set_var(name, value); } poisoned.into_inner() } } }
{ 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 debug = format!("{:?}", obj); !debug.contains(SECRET) && debug.contains("**********")
// 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, ()> { lazy_static! { static ref ENV_MUTEX: Mutex<()> = Mutex::new(()); static ref ORIGINAL_ENVIRONMENT: HashMap<OsString, OsString> = std::env::vars_os().collect(); } let guard = ENV_MUTEX.lock(); lazy_static::initialize(&ORIGINAL_ENVIRONMENT); match guard { Ok(guard) => guard, Err(poisoned) => { for (name, _) in std::env::vars_os() { if!ORIGINAL_ENVIRONMENT.contains_key(&name) { std::env::remove_var(name); } } for (name, value) in ORIGINAL_ENVIRONMENT.iter() { std::env::set_var(name, value); } poisoned.into_inner() } } }
} // 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) { None => { panic!("No last?!") } 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 = &("EnLiGhTeNmEnT"); eina::list_data_set(last, n); println!("First New Value: {}", eina::list_data_get(strlst)); println!("Next still: {}", eina::list_data_get(next)); println!("Last New Value: {}", eina::list_last_data_get(strlst)); // Change next value let t = &("Enlightenment through Rust!"); println!("Old next: {}, changing!", eina::list_data_set(next, t)); println!("Next value changed to: {}", eina::list_data_get(next)); println!("List count: {}", eina::list_count(strlst)); // Add new node 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); eina::shutdown(); }
{ 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)); // Prepend a new node strlst = eina::list_prepend(Some(strlst), &("rust-efl")); println!("First Value: {}", eina::list_data_get(strlst)); strlst = eina::list_append(Some(strlst), &("EFL")); strlst = eina::list_append(Some(strlst), &("Rust EFL!")); let next = match eina::list_next(strlst) {
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)); // Prepend a new node strlst = eina::list_prepend(Some(strlst), &("rust-efl")); println!("First Value: {}", eina::list_data_get(strlst)); strlst = eina::list_append(Some(strlst), &("EFL")); strlst = eina::list_append(Some(strlst), &("Rust EFL!")); let next = match eina::list_next(strlst) { None => { println!("No next! Returning same"); strlst } Some(next) => { println!("Next: {}", eina::list_data_get(next)); next } }; let last = match eina::list_last(strlst) { None => { panic!("No last?!") } 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 = &("EnLiGhTeNmEnT"); eina::list_data_set(last, n); println!("First New Value: {}", eina::list_data_get(strlst)); println!("Next still: {}", eina::list_data_get(next)); println!("Last New Value: {}", eina::list_last_data_get(strlst)); // Change next value let t = &("Enlightenment through Rust!"); println!("Old next: {}, changing!", eina::list_data_set(next, t)); println!("Next value changed to: {}", eina::list_data_get(next)); println!("List count: {}", eina::list_count(strlst)); // Add new node 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); eina::shutdown(); }
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)); println!("Previous Value? {}", eina::list_prev(strlst)); // Prepend a new node strlst = eina::list_prepend(Some(strlst), &("rust-efl")); println!("First Value: {}", eina::list_data_get(strlst)); strlst = eina::list_append(Some(strlst), &("EFL")); strlst = eina::list_append(Some(strlst), &("Rust EFL!")); let next = match eina::list_next(strlst) { None => { println!("No next! Returning same"); strlst } Some(next) => { println!("Next: {}", eina::list_data_get(next)); next } }; let last = match eina::list_last(strlst) { None =>
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 = &("EnLiGhTeNmEnT"); eina::list_data_set(last, n); println!("First New Value: {}", eina::list_data_get(strlst)); println!("Next still: {}", eina::list_data_get(next)); println!("Last New Value: {}", eina::list_last_data_get(strlst)); // Change next value let t = &("Enlightenment through Rust!"); println!("Old next: {}, changing!", eina::list_data_set(next, t)); println!("Next value changed to: {}", eina::list_data_get(next)); println!("List count: {}", eina::list_count(strlst)); // Add new node 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); eina::shutdown(); }
{ 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)); println!("Previous Value? {}", eina::list_prev(strlst)); // Prepend a new node strlst = eina::list_prepend(Some(strlst), &("rust-efl")); println!("First Value: {}", eina::list_data_get(strlst)); strlst = eina::list_append(Some(strlst), &("EFL")); strlst = eina::list_append(Some(strlst), &("Rust EFL!")); let next = match eina::list_next(strlst) { None => { println!("No next! Returning same"); strlst } Some(next) => { println!("Next: {}", eina::list_data_get(next)); next } }; let last = match eina::list_last(strlst) { None => { panic!("No last?!") } 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 = &("EnLiGhTeNmEnT"); eina::list_data_set(last, n); println!("First New Value: {}", eina::list_data_get(strlst)); println!("Next still: {}", eina::list_data_get(next)); println!("Last New Value: {}", eina::list_last_data_get(strlst)); // Change next value let t = &("Enlightenment through Rust!"); println!("Old next: {}, changing!", eina::list_data_set(next, t)); println!("Next value changed to: {}", eina::list_data_get(next)); println!("List count: {}", eina::list_count(strlst)); // Add new node
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 //! 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: String, } impl std::fmt::Display for HubApi { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Hue Bridge id:{} at {:?}", self.id, self.ip) } } impl HubApi { pub fn new(id: &str, ip: &str, token: &str) -> HubApi { HubApi { id: id.to_owned(), ip: ip.to_owned(), token: token.to_owned(), } } pub fn update_token(&mut self, token: &str) { self.token = token.to_owned(); } pub fn get(&self, cmd: &str) -> Result<String, Box<Error>> { let url = format!("http://{}/api/{}/{}", self.ip, self.token, cmd); debug!("GET request to Philips Hue bridge {}: {}", self.id, url); let content = http::get(&url); trace!("Philips Hue API response: {:?}", content); content } #[allow(dead_code)] pub fn post(&self, cmd: &str, data: &str) -> Result<String, Box<Error>> { let url = format!("http://{}/api/{}/{}", self.ip, self.token, cmd); debug!("POST request to Philips Hue bridge {}: {} data: {}", self.id, url, data); let content = http::post(&url, data); trace!("Philips Hue API response: {:?}", content); content } pub fn post_unauth(&self, cmd: &str, data: &str) -> Result<String, Box<Error>> { let url = format!("http://{}/{}", self.ip, cmd); debug!("POST request to Philips Hue bridge {}: {} data: {}", self.id, url, data); let content = http::post(&url, data); trace!("Philips Hue API response: {:?}", content); content } pub fn put(&self, cmd: &str, data: &str) -> Result<String, Box<Error>> { let url = format!("http://{}/api/{}/{}", self.ip, self.token, cmd); debug!("PUT request to Philips Hue bridge {}: {} data: {}", self.id, url, data); let content = http::put(&url, data); trace!("Philips Hue API response: {:?}", content); content } pub fn is_available(&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":{"type":1,"address":"/","description":"unauthorized user"}}] self.get("").unwrap_or("".to_owned()) // TODO no unwrap } pub fn is_paired(&self) -> bool { let settings = self.get_settings(); !settings.contains("unauthorized user") } pub fn try_pairing(&self) -> Result<Option<String>, ()> { #[derive(Deserialize, Debug)] struct PairingResponse { success: Option<SuccessResponse>, error: Option<ErrorResponse>, } #[derive(Deserialize, Debug)] struct SuccessResponse { username: String, } #[derive(Deserialize, Debug)] struct ErrorResponse { #[serde(rename="type")] error_type: u32, address: String, description: String, } let url = "api"; let req = json!({ devicetype: "foxbox_hub"}); let response = self.post_unauth(&url, &req).unwrap_or("[]".to_owned()); let mut response: Vec<PairingResponse> = structs::parse_json(&response) .unwrap_or(Vec::new()); if response.len()!= 1 { error!("Pairing request to Philips Hue bridge {} yielded unexpected response", self.id); return Err(()); } let response = match response.pop() { Some(response) => response, None => return Err(()), }; if let Some(success) = response.success { Ok(Some(success.username)) } else { if let Some(error) = response.error { if error.description.contains("link button not pressed") { debug!("Push pairing button on Philips Hue bridge {}", self.id); Ok(None) } else { error!("Error while pairing with Philips Hue bridge {}: {}", self.id, error.description); Err(()) } } else { error!("Pairing request to Philips Hue bridge {} \ yielded unexpected response", self.id); Err(()) } } } pub fn get_lights(&self) -> Vec<String> { let mut lights: Vec<String> = Vec::new(); let url = "lights"; let res = self.get(url).unwrap(); // TODO: remove unwrap let json: BTreeMap<String, structs::SettingsLightEntry> = structs::parse_json(&res) .unwrap(); // TODO: no unwrap for key in json.keys() { lights.push(key.to_owned()); } lights } pub fn get_light_status(&self, id: &str) -> structs::SettingsLightEntry { let url = format!("lights/{}", id); let res = self.get(&url).unwrap(); // TODO: remove unwrap structs::parse_json(&res).unwrap() // TODO no unwrap } pub fn set_light_power(&self, light_id: &str, on: bool) { let url = format!("lights/{}/state", light_id); let cmd = json!({ on: on }); let _ = self.put(&url, &cmd); } pub fn set_light_color(&self, light_id: &str, hsv: (u32, u32, u32))
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: String, } impl std::fmt::Display for HubApi { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Hue Bridge id:{} at {:?}", self.id, self.ip) } } impl HubApi { pub fn new(id: &str, ip: &str, token: &str) -> HubApi { HubApi { id: id.to_owned(), ip: ip.to_owned(), token: token.to_owned(), } } pub fn update_token(&mut self, token: &str) { self.token = token.to_owned(); } pub fn get(&self, cmd: &str) -> Result<String, Box<Error>> { let url = format!("http://{}/api/{}/{}", self.ip, self.token, cmd); debug!("GET request to Philips Hue bridge {}: {}", self.id, url); let content = http::get(&url); trace!("Philips Hue API response: {:?}", content); content } #[allow(dead_code)] pub fn post(&self, cmd: &str, data: &str) -> Result<String, Box<Error>> { let url = format!("http://{}/api/{}/{}", self.ip, self.token, cmd); debug!("POST request to Philips Hue bridge {}: {} data: {}", self.id, url, data); let content = http::post(&url, data); trace!("Philips Hue API response: {:?}", content); content } pub fn post_unauth(&self, cmd: &str, data: &str) -> Result<String, Box<Error>> { let url = format!("http://{}/{}", self.ip, cmd); debug!("POST request to Philips Hue bridge {}: {} data: {}", self.id, url, data); let content = http::post(&url, data); trace!("Philips Hue API response: {:?}", content); content } pub fn put(&self, cmd: &str, data: &str) -> Result<String, Box<Error>> { let url = format!("http://{}/api/{}/{}", self.ip, self.token, cmd); debug!("PUT request to Philips Hue bridge {}: {} data: {}", self.id, url, data); let content = http::put(&url, data); trace!("Philips Hue API response: {:?}", content); content } pub fn is_available(&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":{"type":1,"address":"/","description":"unauthorized user"}}] self.get("").unwrap_or("".to_owned()) // TODO no unwrap } pub fn is_paired(&self) -> bool { let settings = self.get_settings(); !settings.contains("unauthorized user") } pub fn try_pairing(&self) -> Result<Option<String>, ()> { #[derive(Deserialize, Debug)] struct PairingResponse { success: Option<SuccessResponse>, error: Option<ErrorResponse>, } #[derive(Deserialize, Debug)] struct SuccessResponse { username: String, } #[derive(Deserialize, Debug)] struct ErrorResponse { #[serde(rename="type")] error_type: u32, address: String, description: String, } let url = "api"; let req = json!({ devicetype: "foxbox_hub"}); let response = self.post_unauth(&url, &req).unwrap_or("[]".to_owned()); let mut response: Vec<PairingResponse> = structs::parse_json(&response) .unwrap_or(Vec::new()); if response.len()!= 1 { error!("Pairing request to Philips Hue bridge {} yielded unexpected response", self.id); return Err(()); } let response = match response.pop() { Some(response) => response, None => return Err(()), }; if let Some(success) = response.success { Ok(Some(success.username)) } else { if let Some(error) = response.error { if error.description.contains("link button not pressed") { debug!("Push pairing button on Philips Hue bridge {}", self.id); Ok(None) } else { error!("Error while pairing with Philips Hue bridge {}: {}", self.id, error.description); Err(()) } } else { error!("Pairing request to Philips Hue bridge {} \ yielded unexpected response", self.id); Err(()) } } } pub fn get_lights(&self) -> Vec<String> { let mut lights: Vec<String> = Vec::new(); let url = "lights"; let res = self.get(url).unwrap(); // TODO: remove unwrap let json: BTreeMap<String, structs::SettingsLightEntry> = structs::parse_json(&res) .unwrap(); // TODO: no unwrap for key in json.keys() { lights.push(key.to_owned()); } lights } pub fn get_light_status(&self, id: &str) -> structs::SettingsLightEntry { let url = format!("lights/{}", id); let res = self.get(&url).unwrap(); // TODO: remove unwrap structs::parse_json(&res).unwrap() // TODO no unwrap } pub fn set_light_power(&self, light_id: &str, on: bool) { let url = format!("lights/{}/state", light_id); let cmd = json!({ on: on }); let _ = self.put(&url, &cmd); } pub fn set_light_color(&self, light_id: &str, hsv: (u32, u32, u32)) { 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); } 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); } }
//! 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 //! 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: String, } impl std::fmt::Display for HubApi { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Hue Bridge id:{} at {:?}", self.id, self.ip) } } impl HubApi { pub fn new(id: &str, ip: &str, token: &str) -> HubApi { HubApi { id: id.to_owned(), ip: ip.to_owned(), token: token.to_owned(), } } pub fn update_token(&mut self, token: &str) { self.token = token.to_owned(); } pub fn get(&self, cmd: &str) -> Result<String, Box<Error>> { let url = format!("http://{}/api/{}/{}", self.ip, self.token, cmd); debug!("GET request to Philips Hue bridge {}: {}", self.id, url); let content = http::get(&url); trace!("Philips Hue API response: {:?}", content); content } #[allow(dead_code)] pub fn post(&self, cmd: &str, data: &str) -> Result<String, Box<Error>> { let url = format!("http://{}/api/{}/{}", self.ip, self.token, cmd); debug!("POST request to Philips Hue bridge {}: {} data: {}", self.id, url, data); let content = http::post(&url, data); trace!("Philips Hue API response: {:?}", content); content } pub fn post_unauth(&self, cmd: &str, data: &str) -> Result<String, Box<Error>> { let url = format!("http://{}/{}", self.ip, cmd); debug!("POST request to Philips Hue bridge {}: {} data: {}", self.id, url, data); let content = http::post(&url, data); trace!("Philips Hue API response: {:?}", content); content } pub fn put(&self, cmd: &str, data: &str) -> Result<String, Box<Error>> { let url = format!("http://{}/api/{}/{}", self.ip, self.token, cmd); debug!("PUT request to Philips Hue bridge {}: {} data: {}", self.id, url, data); let content = http::put(&url, data); trace!("Philips Hue API response: {:?}", content); content } pub fn
(&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":{"type":1,"address":"/","description":"unauthorized user"}}] self.get("").unwrap_or("".to_owned()) // TODO no unwrap } pub fn is_paired(&self) -> bool { let settings = self.get_settings(); !settings.contains("unauthorized user") } pub fn try_pairing(&self) -> Result<Option<String>, ()> { #[derive(Deserialize, Debug)] struct PairingResponse { success: Option<SuccessResponse>, error: Option<ErrorResponse>, } #[derive(Deserialize, Debug)] struct SuccessResponse { username: String, } #[derive(Deserialize, Debug)] struct ErrorResponse { #[serde(rename="type")] error_type: u32, address: String, description: String, } let url = "api"; let req = json!({ devicetype: "foxbox_hub"}); let response = self.post_unauth(&url, &req).unwrap_or("[]".to_owned()); let mut response: Vec<PairingResponse> = structs::parse_json(&response) .unwrap_or(Vec::new()); if response.len()!= 1 { error!("Pairing request to Philips Hue bridge {} yielded unexpected response", self.id); return Err(()); } let response = match response.pop() { Some(response) => response, None => return Err(()), }; if let Some(success) = response.success { Ok(Some(success.username)) } else { if let Some(error) = response.error { if error.description.contains("link button not pressed") { debug!("Push pairing button on Philips Hue bridge {}", self.id); Ok(None) } else { error!("Error while pairing with Philips Hue bridge {}: {}", self.id, error.description); Err(()) } } else { error!("Pairing request to Philips Hue bridge {} \ yielded unexpected response", self.id); Err(()) } } } pub fn get_lights(&self) -> Vec<String> { let mut lights: Vec<String> = Vec::new(); let url = "lights"; let res = self.get(url).unwrap(); // TODO: remove unwrap let json: BTreeMap<String, structs::SettingsLightEntry> = structs::parse_json(&res) .unwrap(); // TODO: no unwrap for key in json.keys() { lights.push(key.to_owned()); } lights } pub fn get_light_status(&self, id: &str) -> structs::SettingsLightEntry { let url = format!("lights/{}", id); let res = self.get(&url).unwrap(); // TODO: remove unwrap structs::parse_json(&res).unwrap() // TODO no unwrap } pub fn set_light_power(&self, light_id: &str, on: bool) { let url = format!("lights/{}/state", light_id); let cmd = json!({ on: on }); let _ = self.put(&url, &cmd); } pub fn set_light_color(&self, light_id: &str, hsv: (u32, u32, u32)) { 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); } 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); } }
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_instruction(&self) -> Option<Instruction> { match *self { MemoryField::InstructionCell(inst) => Some(inst), _ => None } } pub fn set_cell_value(&mut self, value: u16) { match *self { MemoryField::MemoryCell(ref mut x) => *x = value, _ => () } } pub fn get_memory(&self) -> u16 { match *self { MemoryField::MemoryCell(x) => x, _ => 0 } } }
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::InstructionCell(_) => true, _ => false } } pub fn is_memory(&self) -> bool { match *self { MemoryField::MemoryCell(_) => true, _ => false } } 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::MemoryCell(ref mut x) => *x = value, _ => () } } pub fn
(&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::InstructionCell(_) => true, _ => false } } pub fn is_memory(&self) -> bool
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::MemoryCell(ref mut x) => *x = value, _ => () } } pub fn get_memory(&self) -> u16 { match *self { MemoryField::MemoryCell(x) => x, _ => 0 } } }
{ 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, and "jump" due to penetration resolution. * Thus, some collision are missed. * Identically, some boxes just dont collide to each other some times. * * # Cause: * Not sure, but this seems to be an accuracy limitation of the contact manifold generators * (OneShotContactManifoldGenerator and IncrementalContactManifoldGenerator). The repetitive * transformations of the saved contact might invalidate them. * * However, this might be a real bug for some other non-accuracy-related reasons. For example, when * a box is deep on the plane without contact why does the one-shot contact manifold generator * fails? Something wrong with the perturbation? * * This might be (but it is very unlikely) a problem with the DBVT that might become invalid. * Though this seems very unlikely as the AABBs seem to be fine and the plane has an infinite aabb * anyway. Thurthermore, the ray-cast (which uses the dbvt…) works fine, even for "jumpy" objects. * * * # Solution: * * * # Limitations of the solution: * */ extern crate nalgebra as na; extern crate ncollide; extern crate nphysics; extern crate nphysics_testbed3d; use na::{Pnt3, Vec3, Translation}; use ncollide::shape::{Plane, Convex}; use ncollide::procedural; use nphysics::world::World; use nphysics::object::RigidBody; use nphysics_testbed3d::Testbed; fn main() { /* * 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 = 8; let shift = 2.0; let centerx = shift * (num as f32) / 2.0; let centery = shift / 2.0; 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; let z = k as f32 * shift - centerz - excentricity; let mut shape = procedural::cuboid(&Vec3::new(2.0 - 0.08, 2.0 - 0.08, 2.0 - 0.08)); for c in shape.coords.iter_mut() { *c = *c + Vec3::new(excentricity, excentricity, excentricity); } let geom = Convex::new(shape.coords); let mut rb = RigidBody::new_dynamic(geom, 1.0, 0.3, 0.5); rb.set_deactivation_threshold(None); rb.append_translation(&Vec3::new(x, y, z)); world.add_body(rb); } }
/* * 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, and "jump" due to penetration resolution. * Thus, some collision are missed. * Identically, some boxes just dont collide to each other some times. * * # Cause: * Not sure, but this seems to be an accuracy limitation of the contact manifold generators * (OneShotContactManifoldGenerator and IncrementalContactManifoldGenerator). The repetitive * transformations of the saved contact might invalidate them. * * However, this might be a real bug for some other non-accuracy-related reasons. For example, when * a box is deep on the plane without contact why does the one-shot contact manifold generator * fails? Something wrong with the perturbation? * * This might be (but it is very unlikely) a problem with the DBVT that might become invalid. * Though this seems very unlikely as the AABBs seem to be fine and the plane has an infinite aabb * anyway. Thurthermore, the ray-cast (which uses the dbvt…) works fine, even for "jumpy" objects. * * * # Solution: * * * # Limitations of the solution: * */ extern crate nalgebra as na; extern crate ncollide; extern crate nphysics; extern crate nphysics_testbed3d; use na::{Pnt3, Vec3, Translation}; use ncollide::shape::{Plane, Convex}; use ncollide::procedural; use nphysics::world::World; use nphysics::object::RigidBody; use nphysics_testbed3d::Testbed; fn ma
{ /* * 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 = 8; let shift = 2.0; let centerx = shift * (num as f32) / 2.0; let centery = shift / 2.0; 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; let z = k as f32 * shift - centerz - excentricity; let mut shape = procedural::cuboid(&Vec3::new(2.0 - 0.08, 2.0 - 0.08, 2.0 - 0.08)); for c in shape.coords.iter_mut() { *c = *c + Vec3::new(excentricity, excentricity, excentricity); } let geom = Convex::new(shape.coords); let mut rb = RigidBody::new_dynamic(geom, 1.0, 0.3, 0.5); rb.set_deactivation_threshold(None); rb.append_translation(&Vec3::new(x, y, z)); world.add_body(rb); } } } /* * 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(); }
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, and "jump" due to penetration resolution. * Thus, some collision are missed. * Identically, some boxes just dont collide to each other some times. * * # Cause: * Not sure, but this seems to be an accuracy limitation of the contact manifold generators * (OneShotContactManifoldGenerator and IncrementalContactManifoldGenerator). The repetitive * transformations of the saved contact might invalidate them. * * However, this might be a real bug for some other non-accuracy-related reasons. For example, when * a box is deep on the plane without contact why does the one-shot contact manifold generator * fails? Something wrong with the perturbation? * * This might be (but it is very unlikely) a problem with the DBVT that might become invalid. * Though this seems very unlikely as the AABBs seem to be fine and the plane has an infinite aabb * anyway. Thurthermore, the ray-cast (which uses the dbvt…) works fine, even for "jumpy" objects. * * * # Solution: * * * # Limitations of the solution: * */ extern crate nalgebra as na; extern crate ncollide; extern crate nphysics; extern crate nphysics_testbed3d; use na::{Pnt3, Vec3, Translation}; use ncollide::shape::{Plane, Convex}; use ncollide::procedural; use nphysics::world::World; use nphysics::object::RigidBody; use nphysics_testbed3d::Testbed; fn main() {
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; let z = k as f32 * shift - centerz - excentricity; let mut shape = procedural::cuboid(&Vec3::new(2.0 - 0.08, 2.0 - 0.08, 2.0 - 0.08)); for c in shape.coords.iter_mut() { *c = *c + Vec3::new(excentricity, excentricity, excentricity); } let geom = Convex::new(shape.coords); let mut rb = RigidBody::new_dynamic(geom, 1.0, 0.3, 0.5); rb.set_deactivation_threshold(None); rb.append_translation(&Vec3::new(x, y, z)); world.add_body(rb); } } } /* * 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(); }
/* * 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 = 8; let shift = 2.0; let centerx = shift * (num as f32) / 2.0; let centery = shift / 2.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_elasticity: LinElasticity, } impl ModelSolidLinearElastic { pub fn new(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 initializes state fn initialize_state(&self, stress_ini: &Tensor2) -> Result<ModelSolidState, StrError> { 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), }) } /// 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.strain.vec; let deps = &delta_strain.vec; add_vectors(eps_new, 1.0, eps, 1.0, deps)?; // update stress let dd = self.lin_elasticity.get_modulus(); t4_ddot_t2(&mut state_new.stress, 1.0, &dd, &state_new.strain) } /// Calculates the consistent tangent modulus at new state fn consistent_modulus( &self, dd_new: &mut Tensor4,
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_elasticity: LinElasticity, } impl ModelSolidLinearElastic { pub fn new(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 initializes state fn initialize_state(&self, stress_ini: &Tensor2) -> Result<ModelSolidState, StrError>
/// 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.strain.vec; let deps = &delta_strain.vec; add_vectors(eps_new, 1.0, eps, 1.0, deps)?; // update stress let dd = self.lin_elasticity.get_modulus(); t4_ddot_t2(&mut state_new.stress, 1.0, &dd, &state_new.strain) } /// Calculates the consistent tangent modulus at new state fn consistent_modulus( &self, dd_new: &mut Tensor4, state_new: &ModelSolidState, first_iteration: bool, ) -> Result<(), StrError> { let dd_elastic = self.lin_elasticity.get_modulus(); copy_matrix(&mut dd_new.mat, &dd_elastic.mat) } }
{ 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_elasticity: LinElasticity, } impl ModelSolidLinearElastic { pub fn
(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 initializes state fn initialize_state(&self, stress_ini: &Tensor2) -> Result<ModelSolidState, StrError> { 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), }) } /// 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.strain.vec; let deps = &delta_strain.vec; add_vectors(eps_new, 1.0, eps, 1.0, deps)?; // update stress let dd = self.lin_elasticity.get_modulus(); t4_ddot_t2(&mut state_new.stress, 1.0, &dd, &state_new.strain) } /// Calculates the consistent tangent modulus at new state fn consistent_modulus( &self, dd_new: &mut Tensor4, state_new: &ModelSolidState, first_iteration: bool, ) -> Result<(), StrError> { let dd_elastic = self.lin_elasticity.get_modulus(); copy_matrix(&mut dd_new.mat, &dd_elastic.mat) } }
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, Serialize}; use std::io; pub use self::error::{Error, Result}; pub fn
<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::serialize(value, &mut ser) } pub fn deserialize<'de, T>(bytes: &'de [u8]) -> Result<T> where T: Deserialize<'de>, { let mut de = Deserializer::new(bytes); Deserialize::deserialize(&mut de) }
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, Serialize}; use std::io; pub use self::error::{Error, Result}; pub fn serialize<T>(value: &T) -> Result<Vec<u8>> where T: Serialize,
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 = Deserializer::new(bytes); Deserialize::deserialize(&mut de) }
{ 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, Serialize}; use std::io; pub use self::error::{Error, Result}; pub fn serialize<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::serialize(value, &mut ser) } pub fn deserialize<'de, T>(bytes: &'de [u8]) -> Result<T> where T: Deserialize<'de>, { let mut de = Deserializer::new(bytes); Deserialize::deserialize(&mut de) }
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 _stream: cpal::Stream, } impl SoundCpal { /// Constructs sound backend from settings pub fn new(settings: &Settings) -> anyhow::Result<SoundCpal> { let host = cpal::default_host(); let device = host .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.min_sample_rate().0 as usize || sample_rate > c.max_sample_rate().0 as usize { return false; } } 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(cpal::SampleRate(sample_rate as u32)) } else { config.with_max_sample_rate() }; let sample_rate = config.sample_rate().0 as usize; let (tx, rx) = mpsc::channel(); let stream = match config.sample_format() { cpal::SampleFormat::I16 => create_stream::<i16>(&device, &config.into(), rx)?, cpal::SampleFormat::U16 => create_stream::<u16>(&device, &config.into(), rx)?, cpal::SampleFormat::F32 => create_stream::<f32>(&device, &config.into(), rx)?, }; Ok(SoundCpal { tx, sample_rate, _stream: stream, }) } } impl SoundDevice for SoundCpal { fn send_sample(&mut self, sample: ZXSample) { self.tx.send(sample).unwrap(); } fn sample_rate(&self) -> usize
} 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 [T], _: &cpal::OutputCallbackInfo| { for frame in out.chunks_mut(channels) { match samples_rx.try_recv().ok() { Some(zx_sample) => { let left: T = cpal::Sample::from(&zx_sample.left); let right: T = cpal::Sample::from(&zx_sample.right); frame[0] = left; frame[1] = right; } None => { frame[0] = cpal::Sample::from(&0f32); frame[1] = cpal::Sample::from(&0f32); } } } }, |_| {}, )?; stream.play()?; Ok(stream) }
{ 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 _stream: cpal::Stream, } impl SoundCpal { /// Constructs sound backend from settings pub fn new(settings: &Settings) -> anyhow::Result<SoundCpal> { let host = cpal::default_host(); let device = host .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
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(cpal::SampleRate(sample_rate as u32)) } else { config.with_max_sample_rate() }; let sample_rate = config.sample_rate().0 as usize; let (tx, rx) = mpsc::channel(); let stream = match config.sample_format() { cpal::SampleFormat::I16 => create_stream::<i16>(&device, &config.into(), rx)?, cpal::SampleFormat::U16 => create_stream::<u16>(&device, &config.into(), rx)?, cpal::SampleFormat::F32 => create_stream::<f32>(&device, &config.into(), rx)?, }; Ok(SoundCpal { tx, sample_rate, _stream: stream, }) } } impl SoundDevice for SoundCpal { fn send_sample(&mut self, sample: ZXSample) { self.tx.send(sample).unwrap(); } fn sample_rate(&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_output_stream( config, move |out: &mut [T], _: &cpal::OutputCallbackInfo| { for frame in out.chunks_mut(channels) { match samples_rx.try_recv().ok() { Some(zx_sample) => { let left: T = cpal::Sample::from(&zx_sample.left); let right: T = cpal::Sample::from(&zx_sample.right); frame[0] = left; frame[1] = right; } None => { frame[0] = cpal::Sample::from(&0f32); frame[1] = cpal::Sample::from(&0f32); } } } }, |_| {}, )?; stream.play()?; Ok(stream) }
{ 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 _stream: cpal::Stream, } impl SoundCpal { /// Constructs sound backend from settings pub fn new(settings: &Settings) -> anyhow::Result<SoundCpal> { let host = cpal::default_host(); let device = host .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.min_sample_rate().0 as usize || sample_rate > c.max_sample_rate().0 as usize { return false; } } 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(cpal::SampleRate(sample_rate as u32)) } else { config.with_max_sample_rate() }; let sample_rate = config.sample_rate().0 as usize; let (tx, rx) = mpsc::channel(); let stream = match config.sample_format() { cpal::SampleFormat::I16 => create_stream::<i16>(&device, &config.into(), rx)?, cpal::SampleFormat::U16 => create_stream::<u16>(&device, &config.into(), rx)?, cpal::SampleFormat::F32 => create_stream::<f32>(&device, &config.into(), rx)?, }; Ok(SoundCpal { tx, sample_rate, _stream: stream, }) } } impl SoundDevice for SoundCpal { fn send_sample(&mut self, sample: ZXSample) { self.tx.send(sample).unwrap(); } fn
(&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_output_stream( config, move |out: &mut [T], _: &cpal::OutputCallbackInfo| { for frame in out.chunks_mut(channels) { match samples_rx.try_recv().ok() { Some(zx_sample) => { let left: T = cpal::Sample::from(&zx_sample.left); let right: T = cpal::Sample::from(&zx_sample.right); frame[0] = left; frame[1] = right; } None => { frame[0] = cpal::Sample::from(&0f32); frame[1] = cpal::Sample::from(&0f32); } } } }, |_| {}, )?; stream.play()?; Ok(stream) }
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 _stream: cpal::Stream, }
.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.min_sample_rate().0 as usize || sample_rate > c.max_sample_rate().0 as usize { return false; } } 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(cpal::SampleRate(sample_rate as u32)) } else { config.with_max_sample_rate() }; let sample_rate = config.sample_rate().0 as usize; let (tx, rx) = mpsc::channel(); let stream = match config.sample_format() { cpal::SampleFormat::I16 => create_stream::<i16>(&device, &config.into(), rx)?, cpal::SampleFormat::U16 => create_stream::<u16>(&device, &config.into(), rx)?, cpal::SampleFormat::F32 => create_stream::<f32>(&device, &config.into(), rx)?, }; Ok(SoundCpal { tx, sample_rate, _stream: stream, }) } } impl SoundDevice for SoundCpal { fn send_sample(&mut self, sample: ZXSample) { self.tx.send(sample).unwrap(); } fn sample_rate(&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_output_stream( config, move |out: &mut [T], _: &cpal::OutputCallbackInfo| { for frame in out.chunks_mut(channels) { match samples_rx.try_recv().ok() { Some(zx_sample) => { let left: T = cpal::Sample::from(&zx_sample.left); let right: T = cpal::Sample::from(&zx_sample.right); frame[0] = left; frame[1] = right; } None => { frame[0] = cpal::Sample::from(&0f32); frame[1] = cpal::Sample::from(&0f32); } } } }, |_| {}, )?; stream.play()?; Ok(stream) }
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) = channel(); err::<i32, i32>(1).map(move |a| { drop(tx); a }).map_err(move |_| { assert!(rx.recv().is_err()); tx2.send(()).unwrap() }).forget(); rx2.recv().unwrap(); } #[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(()).unwrap() }).forget(); rx2.recv().unwrap(); } struct FutureData<F, T> { _data: T, future: F, }
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::<()>(); 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.complete(()); rx2.recv().unwrap(); } // #[test] // fn or_else_drops_eagerly() { // let (p1, c1) = oneshot::<(), ()>(); // let (p2, c2) = oneshot::<(), ()>(); // let (tx, rx) = channel::<()>(); // let (tx2, rx2) = channel(); // p1.map(move |a| { drop(tx); a }).or_else(move |_| { // assert!(rx.recv().is_err()); // p2 // }).map(move |_| tx2.send(()).unwrap()).forget(); // assert!(rx2.try_recv().is_err()); // c1.fail(()); // assert!(rx2.try_recv().is_err()); // c2.finish(()); // rx2.recv().unwrap(); // }
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) = channel(); err::<i32, i32>(1).map(move |a| { drop(tx); a }).map_err(move |_| { assert!(rx.recv().is_err()); tx2.send(()).unwrap() }).forget(); rx2.recv().unwrap(); } #[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(()).unwrap() }).forget(); rx2.recv().unwrap(); } struct FutureData<F, T> { _data: T, future: F, } 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
() { 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.complete(()); rx2.recv().unwrap(); } // #[test] // fn or_else_drops_eagerly() { // let (p1, c1) = oneshot::<(), ()>(); // let (p2, c2) = oneshot::<(), ()>(); // let (tx, rx) = channel::<()>(); // let (tx2, rx2) = channel(); // p1.map(move |a| { drop(tx); a }).or_else(move |_| { // assert!(rx.recv().is_err()); // p2 // }).map(move |_| tx2.send(()).unwrap()).forget(); // assert!(rx2.try_recv().is_err()); // c1.fail(()); // assert!(rx2.try_recv().is_err()); // c2.finish(()); // rx2.recv().unwrap(); // }
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(()).unwrap() }).forget(); rx2.recv().unwrap(); } struct FutureData<F, T> { _data: T, future: F, } 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::<()>(); 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.complete(()); rx2.recv().unwrap(); } // #[test] // fn or_else_drops_eagerly() { // let (p1, c1) = oneshot::<(), ()>(); // let (p2, c2) = oneshot::<(), ()>(); // let (tx, rx) = channel::<()>(); // let (tx2, rx2) = channel(); // p1.map(move |a| { drop(tx); a }).or_else(move |_| { // assert!(rx.recv().is_err()); // p2 // }).map(move |_| tx2.send(()).unwrap()).forget(); // assert!(rx2.try_recv().is_err()); // c1.fail(()); // assert!(rx2.try_recv().is_err()); // c2.finish(()); // rx2.recv().unwrap(); // }
{ // 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(); rx2.recv().unwrap(); }
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::method::Method; use hyper::header::{Headers, ContentType}; use hyper::mime::{Mime, TopLevel, SubLevel}; pub fn join_paths(base: &String, path: String) -> String
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()]); } if!headers.keys().any(|k| k.to_lowercase() == "content-type") { hyper_headers.set(ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![]))); } } hyper_headers } fn make_request(base_url: &String, request: &Request, client: &Client) -> Result<HyperResponse, HyperError> { match Method::from_str(&request.method) { Ok(method) => { let mut url = join_paths(base_url, request.path.clone()); if request.query.is_some() { url.push('?'); url.push_str(&build_query_string(request.query.clone().unwrap())); } debug!("Making request to '{}'", url); let hyper_request = client.request(method, &url) .headers(setup_headers(&request.headers.clone())); match request.body { OptionalBody::Present(ref s) => hyper_request.body(s.as_slice()), OptionalBody::Null => { if request.content_type() == "application/json" { hyper_request.body("null") } else { hyper_request } }, _ => hyper_request }.send() }, Err(err) => Err(err) } } fn extract_headers(headers: &Headers) -> Option<HashMap<String, String>> { if headers.len() > 0 { Some(headers.iter().map(|h| (s!(h.name()), h.value_string()) ).collect()) } 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 }, Err(err) => { warn!("Failed to read request body: {}", err); OptionalBody::Missing } } } fn hyper_response_to_pact_response(response: &mut HyperResponse) -> Response { Response { status: response.status.to_u16(), headers: extract_headers(&response.headers), body: extract_body(response), matching_rules: MatchingRules::default() } } pub fn make_provider_request(provider: &ProviderInfo, request: &Request) -> Result<Response, HyperError> { debug!("Sending {:?} to provider", request); let client = Client::new(); match make_request(&format!("{}://{}:{}{}", provider.protocol, provider.host, provider.port, provider.path), request, &client) { Ok(ref mut response) => { debug!("Received response: {:?}", response); Ok(hyper_response_to_pact_response(response)) }, Err(err) => { debug!("Request failed: {}", err); Err(err) } } } pub fn make_state_change_request(provider: &ProviderInfo, request: &Request) -> Result<(), String> { debug!("Sending {:?} to state change handler", request); let client = Client::new(); match make_request(&provider.state_change_url.clone().unwrap(), request, &client) { Ok(ref mut response) => { debug!("Received response: {:?}", response); if response.status.is_success() { Ok(()) } else { debug!("Request failed: {}", response.status); Err(format!("State change request failed: {}", response.status)) } }, Err(err) => { debug!("Request failed: {}", err); Err(format!("State change request failed: {}", err)) } } } #[cfg(test)] mod tests { use expectest::prelude::*; use super::join_paths; #[test] fn join_paths_test() { expect!(join_paths(&s!(""), s!(""))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!("/"), s!(""))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!(""), s!("/"))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!("/"), s!("/"))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!("/a/b"), s!("/c/d"))).to(be_equal_to(s!("/a/b/c/d"))); } }
{ 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::method::Method; use hyper::header::{Headers, ContentType}; use hyper::mime::{Mime, TopLevel, SubLevel}; pub fn join_paths(base: &String, path: String) -> String { let mut full_path = s!(base.trim_right_matches("/")); full_path.push('/'); full_path.push_str(path.trim_left_matches("/")); full_path } 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()]); } if!headers.keys().any(|k| k.to_lowercase() == "content-type") { hyper_headers.set(ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![]))); } } hyper_headers } fn make_request(base_url: &String, request: &Request, client: &Client) -> Result<HyperResponse, HyperError> { match Method::from_str(&request.method) { Ok(method) => { let mut url = join_paths(base_url, request.path.clone()); if request.query.is_some() { url.push('?'); url.push_str(&build_query_string(request.query.clone().unwrap())); } debug!("Making request to '{}'", url); let hyper_request = client.request(method, &url) .headers(setup_headers(&request.headers.clone())); match request.body { OptionalBody::Present(ref s) => hyper_request.body(s.as_slice()), OptionalBody::Null => { if request.content_type() == "application/json" { hyper_request.body("null") } else { hyper_request } }, _ => hyper_request }.send() }, Err(err) => Err(err) } } fn extract_headers(headers: &Headers) -> Option<HashMap<String, String>> {
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 }, Err(err) => { warn!("Failed to read request body: {}", err); OptionalBody::Missing } } } fn hyper_response_to_pact_response(response: &mut HyperResponse) -> Response { Response { status: response.status.to_u16(), headers: extract_headers(&response.headers), body: extract_body(response), matching_rules: MatchingRules::default() } } pub fn make_provider_request(provider: &ProviderInfo, request: &Request) -> Result<Response, HyperError> { debug!("Sending {:?} to provider", request); let client = Client::new(); match make_request(&format!("{}://{}:{}{}", provider.protocol, provider.host, provider.port, provider.path), request, &client) { Ok(ref mut response) => { debug!("Received response: {:?}", response); Ok(hyper_response_to_pact_response(response)) }, Err(err) => { debug!("Request failed: {}", err); Err(err) } } } pub fn make_state_change_request(provider: &ProviderInfo, request: &Request) -> Result<(), String> { debug!("Sending {:?} to state change handler", request); let client = Client::new(); match make_request(&provider.state_change_url.clone().unwrap(), request, &client) { Ok(ref mut response) => { debug!("Received response: {:?}", response); if response.status.is_success() { Ok(()) } else { debug!("Request failed: {}", response.status); Err(format!("State change request failed: {}", response.status)) } }, Err(err) => { debug!("Request failed: {}", err); Err(format!("State change request failed: {}", err)) } } } #[cfg(test)] mod tests { use expectest::prelude::*; use super::join_paths; #[test] fn join_paths_test() { expect!(join_paths(&s!(""), s!(""))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!("/"), s!(""))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!(""), s!("/"))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!("/"), s!("/"))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!("/a/b"), s!("/c/d"))).to(be_equal_to(s!("/a/b/c/d"))); } }
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::method::Method; use hyper::header::{Headers, ContentType}; use hyper::mime::{Mime, TopLevel, SubLevel}; pub fn join_paths(base: &String, path: String) -> String { let mut full_path = s!(base.trim_right_matches("/")); full_path.push('/'); full_path.push_str(path.trim_left_matches("/")); full_path } fn
(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.keys().any(|k| k.to_lowercase() == "content-type") { hyper_headers.set(ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![]))); } } hyper_headers } fn make_request(base_url: &String, request: &Request, client: &Client) -> Result<HyperResponse, HyperError> { match Method::from_str(&request.method) { Ok(method) => { let mut url = join_paths(base_url, request.path.clone()); if request.query.is_some() { url.push('?'); url.push_str(&build_query_string(request.query.clone().unwrap())); } debug!("Making request to '{}'", url); let hyper_request = client.request(method, &url) .headers(setup_headers(&request.headers.clone())); match request.body { OptionalBody::Present(ref s) => hyper_request.body(s.as_slice()), OptionalBody::Null => { if request.content_type() == "application/json" { hyper_request.body("null") } else { hyper_request } }, _ => hyper_request }.send() }, Err(err) => Err(err) } } fn extract_headers(headers: &Headers) -> Option<HashMap<String, String>> { if headers.len() > 0 { Some(headers.iter().map(|h| (s!(h.name()), h.value_string()) ).collect()) } 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 }, Err(err) => { warn!("Failed to read request body: {}", err); OptionalBody::Missing } } } fn hyper_response_to_pact_response(response: &mut HyperResponse) -> Response { Response { status: response.status.to_u16(), headers: extract_headers(&response.headers), body: extract_body(response), matching_rules: MatchingRules::default() } } pub fn make_provider_request(provider: &ProviderInfo, request: &Request) -> Result<Response, HyperError> { debug!("Sending {:?} to provider", request); let client = Client::new(); match make_request(&format!("{}://{}:{}{}", provider.protocol, provider.host, provider.port, provider.path), request, &client) { Ok(ref mut response) => { debug!("Received response: {:?}", response); Ok(hyper_response_to_pact_response(response)) }, Err(err) => { debug!("Request failed: {}", err); Err(err) } } } pub fn make_state_change_request(provider: &ProviderInfo, request: &Request) -> Result<(), String> { debug!("Sending {:?} to state change handler", request); let client = Client::new(); match make_request(&provider.state_change_url.clone().unwrap(), request, &client) { Ok(ref mut response) => { debug!("Received response: {:?}", response); if response.status.is_success() { Ok(()) } else { debug!("Request failed: {}", response.status); Err(format!("State change request failed: {}", response.status)) } }, Err(err) => { debug!("Request failed: {}", err); Err(format!("State change request failed: {}", err)) } } } #[cfg(test)] mod tests { use expectest::prelude::*; use super::join_paths; #[test] fn join_paths_test() { expect!(join_paths(&s!(""), s!(""))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!("/"), s!(""))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!(""), s!("/"))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!("/"), s!("/"))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!("/a/b"), s!("/c/d"))).to(be_equal_to(s!("/a/b/c/d"))); } }
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::method::Method; use hyper::header::{Headers, ContentType}; use hyper::mime::{Mime, TopLevel, SubLevel}; pub fn join_paths(base: &String, path: String) -> String { let mut full_path = s!(base.trim_right_matches("/")); full_path.push('/'); full_path.push_str(path.trim_left_matches("/")); full_path } 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()]); } if!headers.keys().any(|k| k.to_lowercase() == "content-type") { hyper_headers.set(ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![]))); } } hyper_headers } fn make_request(base_url: &String, request: &Request, client: &Client) -> Result<HyperResponse, HyperError> { match Method::from_str(&request.method) { Ok(method) => { let mut url = join_paths(base_url, request.path.clone()); if request.query.is_some() { url.push('?'); url.push_str(&build_query_string(request.query.clone().unwrap())); } debug!("Making request to '{}'", url); let hyper_request = client.request(method, &url) .headers(setup_headers(&request.headers.clone())); match request.body { OptionalBody::Present(ref s) => hyper_request.body(s.as_slice()), OptionalBody::Null => { if request.content_type() == "application/json" { hyper_request.body("null") } else { hyper_request } }, _ => hyper_request }.send() }, Err(err) => Err(err) } } fn extract_headers(headers: &Headers) -> Option<HashMap<String, String>> { if headers.len() > 0
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 }, Err(err) => { warn!("Failed to read request body: {}", err); OptionalBody::Missing } } } fn hyper_response_to_pact_response(response: &mut HyperResponse) -> Response { Response { status: response.status.to_u16(), headers: extract_headers(&response.headers), body: extract_body(response), matching_rules: MatchingRules::default() } } pub fn make_provider_request(provider: &ProviderInfo, request: &Request) -> Result<Response, HyperError> { debug!("Sending {:?} to provider", request); let client = Client::new(); match make_request(&format!("{}://{}:{}{}", provider.protocol, provider.host, provider.port, provider.path), request, &client) { Ok(ref mut response) => { debug!("Received response: {:?}", response); Ok(hyper_response_to_pact_response(response)) }, Err(err) => { debug!("Request failed: {}", err); Err(err) } } } pub fn make_state_change_request(provider: &ProviderInfo, request: &Request) -> Result<(), String> { debug!("Sending {:?} to state change handler", request); let client = Client::new(); match make_request(&provider.state_change_url.clone().unwrap(), request, &client) { Ok(ref mut response) => { debug!("Received response: {:?}", response); if response.status.is_success() { Ok(()) } else { debug!("Request failed: {}", response.status); Err(format!("State change request failed: {}", response.status)) } }, Err(err) => { debug!("Request failed: {}", err); Err(format!("State change request failed: {}", err)) } } } #[cfg(test)] mod tests { use expectest::prelude::*; use super::join_paths; #[test] fn join_paths_test() { expect!(join_paths(&s!(""), s!(""))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!("/"), s!(""))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!(""), s!("/"))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!("/"), s!("/"))).to(be_equal_to(s!("/"))); expect!(join_paths(&s!("/a/b"), s!("/c/d"))).to(be_equal_to(s!("/a/b/c/d"))); } }
{ 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 num::rational::{Ratio, BigRational}; use num::bigint::BigInt; use env::Env; use eval::eval; use result::SchemerResult; pub type ExprResult = SchemerResult<Expr>; pub type UnboxAndEvalResult = SchemerResult<(Vec<Expr>, Env)>; pub type UnConsResult = SchemerResult<(Expr, Expr)>; pub type PrintResult = SchemerResult<String>; #[deriving(PartialEq, Show, Clone)] pub enum Expr { Atom(AtomVal), List(Vec<Box<Expr>>) } #[deriving(PartialEq, Show, Clone)] pub enum AtomVal { Symbol(String), Integer(BigInt), Float(BigRational), Lambda(LambdaVal), Boolean(bool) } #[deriving(Clone)] pub enum LambdaVal { UserDefined(String, Vec<String>, Box<Expr>, Env), BuiltIn(String, fn(args: Vec<Expr>, env: Env) -> SchemerResult<(Option<Expr>, Env)>) } impl LambdaVal { pub fn print(&self) -> PrintResult { match self { &UserDefined(ref name, ref vars, _, _) => { let var_expr = List(vars.iter().map(|v| box Atom(Symbol(v.to_string()))).collect()); let printed_val = match var_expr.print() { Ok(v) => v, Err(e) => return Err(e) }; Ok(format!("lambda:{}{}", name.to_string(), printed_val)) }, &BuiltIn(ref name, _) => Ok(format!("builtin-fn:{}", name.to_string())) } } } impl PartialEq for LambdaVal { // Our custom eq allows numbers which are near each other to be equal! :D fn eq(&self, other: &LambdaVal) -> bool { match self { &UserDefined(ref name, ref args, ref body, _) => match other { &UserDefined(ref other_name, ref other_args, ref other_body, _) => name == other_name && { if args.len()!= other_args.len() { return false; } let mut args_match = true; for ctr in range(0, args.len()) { args_match = args[ctr] == other_args[ctr]; } args_match } && body == other_body, &BuiltIn(_, _) => false }, &BuiltIn(ref name, ref body_fn) => match other { &BuiltIn(ref other_name, ref other_body_fn) => *body_fn as *mut u8 == *other_body_fn as *mut u8 && name == other_name, &UserDefined(_, _, _, _) => false } } } } impl Show for LambdaVal { fn fmt(&self, f: &mut Formatter) -> Result { // The `f.buf` value is of the type `&mut io::Writer`, which is what the // write! macro is expecting. Note that this formatting ignores the // various flags provided to format strings. write!(f, "{}", self.print()) } } impl Expr { pub fn new_atom(input: String) -> ExprResult { let first_char = input.as_slice().char_at(0); match first_char { '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => { match input.as_slice().contains(".") { true => { let parsed_val: Option<f64> = FromStr::from_str(input.as_slice()); match parsed_val { Some(val) => { let new_float = match Number::float(val) { Ok(v) => v, Err(e) => return Err(e) }; Ok(Atom(new_float)) }, None => Err(format!("Cannot parse number-like input of: '{}'", input)) } }, false => { match FromStr::from_str(input.as_slice()) { Some(val) => Ok(Atom(Integer(val))), None => Err(format!("Cannot parse number-like input of: {}", input)) } } } }, '#' => { // #-prefix parsing match &input { v if *v == "#f".to_string() => Ok(Atom(Boolean(false))), v if *v == "#false".to_string() => Ok(Atom(Boolean(false))), v if *v == "#t".to_string() => Ok(Atom(Boolean(true))), v if *v == "#true".to_string() => Ok(Atom(Boolean(true))), _ => Err(format!("un-implemented case of sharp/pound-prefixing")) } } _ => Ok(Atom(Symbol(input))) } } pub fn cons(car: Expr, cdr: Expr) -> ExprResult { let mut new_items = vec!(box car); match cdr { v @ Atom(_) => new_items.push(box v), List(cdr_items) => for i in cdr_items.move_iter() { new_items.push(i); } } Ok(List(new_items)) } pub fn print(&self) -> PrintResult { match self { &List(ref items) => { // this has to change let mut items_iter = items.iter(); let mut has_more = true; let mut printed_val = "(".to_string(); while has_more { match items_iter.next() { None => has_more = false, Some(ref i) => match i.print() { Ok(i) => { printed_val = printed_val.append(i.append(" ").as_slice()) }, Err(e) => return Err(e) } } } Ok(printed_val.as_slice().trim().to_string().append(")")) }, &Atom(ref v) => (*v).print() } } pub fn un_cons(self) -> UnConsResult { match self { Atom(_) => return Err("expr.un_cons(): Cannot un_cons an Atom value" .to_string()), List(mut items) => { if items.len() == 0 { return Err("expr.un_cons(): cannot build car/cdr of empty list" .to_string()); } let car = match items.remove(0) { Some(v) => v, None => return Err("expr.un_cons(): items collection empty; \ shouldn't happen".to_string()) }; Ok((*car, List(items))) } } } // type-evaluating built-ins pub fn is_atom(&self) -> bool { match *self { Atom(_) => true, _ => false } } pub fn is_null(&self) -> bool { match *self { List(ref items) => items.len() == 0, _ => false } } // fns for consuming/breaking down Exprs into composed elements // or underlying values pub fn unbox_and_eval(self, env: Env) -> UnboxAndEvalResult { match self { List(items) => { let args: Vec<Expr> = items.move_iter().map(|x| *x).collect(); let mut env = env; let mut evald_args = Vec::new(); for i in args.move_iter() { let (evald_arg, out_env) = try!(eval(i, env)); let evald_arg = match evald_arg { Some(v) => v, _ => return Err("eval'd arg should ret expr".to_string()) }; env = out_env; evald_args.push(evald_arg); } Ok((evald_args, env)) }, _ => Err(format!("calling unbox on non-List expr")) } } pub fn into_float(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> { match self { Atom(Float(v)) => Ok(v.numer().clone()), Atom(Integer(v)) => Ok(v), _ => Err("calling into_integer() on non-numeric value".to_string()) } } } impl AtomVal { pub fn print(&self) -> PrintResult { match self { &Symbol(ref v) => Ok(v.to_string()), &Integer(ref v) => Ok(v.to_string()), &Float(ref v) => match Number::float_print(v) { Ok(v) => Ok(v), Err(e) => return Err(e) }, &Lambda(ref v) => v.print(), &Boolean(ref v) => Ok("#".to_string().append(format!("{}", v).as_slice())) } } } pub mod Number { use std::char; use std::num::Zero; use num::bigint::BigInt; use num::rational::{Ratio, BigRational}; use collections::TreeSet; use result::SchemerResult; use super::{AtomVal, Integer, Float}; use super::PrintResult; #[allow(dead_code)] pub fn integer(val: i64) -> SchemerResult<AtomVal> { let bi: BigInt = match FromPrimitive::from_i64(val) { Some(v) => v, None => return Err("Number::integer: should be able to convert i64->BigInt".to_string()) }; Ok(Integer(bi)) } pub fn uint(val: uint) -> SchemerResult<AtomVal> { let bi: BigInt = match FromPrimitive::from_uint(val) { Some(v) => v, None => return Err("Number::uint: should be able to convert uint->BigInt".to_string()) }; Ok(Integer(bi)) } pub fn float(val: f64) -> SchemerResult<AtomVal> { let br = match Ratio::from_float(val) { Some(v) => v, None => return Err("Number::float: should be able to convert f64->BigInt".to_string()) }; Ok(Float(br)) } // adapted from https://gist.github.com/kballard/4771f0d338fbb1896446 pub fn float_print(v: &BigRational) -> PrintResult
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::from_digit(digit, 10) { Some(v) => v, None => return Err( "float_print: couldn't parse char_digit. Also unlikely.".to_string()) }; s.push_char(char_digit); v = v.fract(); } } Ok(s.into_string()) } }
{ 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.".to_string()) }; let ten = Ratio::from_integer(ten); let mut seen = TreeSet::new(); while !v.is_zero() { v = v * ten; if seen.contains(&v) { s.push_str("…"); break; } seen.insert(v.clone()); let digit = v.to_integer(); // should only be 1 digit // bail out when we hit a zero in the decimal portion
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 num::rational::{Ratio, BigRational}; use num::bigint::BigInt; use env::Env; use eval::eval; use result::SchemerResult; pub type ExprResult = SchemerResult<Expr>; pub type UnboxAndEvalResult = SchemerResult<(Vec<Expr>, Env)>; pub type UnConsResult = SchemerResult<(Expr, Expr)>; pub type PrintResult = SchemerResult<String>; #[deriving(PartialEq, Show, Clone)] pub enum Expr { Atom(AtomVal), List(Vec<Box<Expr>>) } #[deriving(PartialEq, Show, Clone)] pub enum AtomVal { Symbol(String), Integer(BigInt), Float(BigRational), Lambda(LambdaVal), Boolean(bool) } #[deriving(Clone)] pub enum LambdaVal { UserDefined(String, Vec<String>, Box<Expr>, Env), BuiltIn(String, fn(args: Vec<Expr>, env: Env) -> SchemerResult<(Option<Expr>, Env)>) } impl LambdaVal { pub fn print(&self) -> PrintResult { match self { &UserDefined(ref name, ref vars, _, _) => { let var_expr = List(vars.iter().map(|v| box Atom(Symbol(v.to_string()))).collect()); let printed_val = match var_expr.print() { Ok(v) => v, Err(e) => return Err(e) }; Ok(format!("lambda:{}{}", name.to_string(), printed_val)) }, &BuiltIn(ref name, _) => Ok(format!("builtin-fn:{}", name.to_string())) } } } impl PartialEq for LambdaVal { // Our custom eq allows numbers which are near each other to be equal! :D fn eq(&self, other: &LambdaVal) -> bool { match self { &UserDefined(ref name, ref args, ref body, _) => match other { &UserDefined(ref other_name, ref other_args, ref other_body, _) => name == other_name && { if args.len()!= other_args.len() { return false; } let mut args_match = true; for ctr in range(0, args.len()) { args_match = args[ctr] == other_args[ctr]; } args_match } && body == other_body, &BuiltIn(_, _) => false }, &BuiltIn(ref name, ref body_fn) => match other { &BuiltIn(ref other_name, ref other_body_fn) => *body_fn as *mut u8 == *other_body_fn as *mut u8 && name == other_name, &UserDefined(_, _, _, _) => false } } } } impl Show for LambdaVal { fn fmt(&self, f: &mut Formatter) -> Result { // The `f.buf` value is of the type `&mut io::Writer`, which is what the // write! macro is expecting. Note that this formatting ignores the // various flags provided to format strings. write!(f, "{}", self.print()) } } impl Expr { pub fn new_atom(input: String) -> ExprResult { let first_char = input.as_slice().char_at(0); match first_char { '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => { match input.as_slice().contains(".") { true => { let parsed_val: Option<f64> = FromStr::from_str(input.as_slice()); match parsed_val { Some(val) => { let new_float = match Number::float(val) { Ok(v) => v, Err(e) => return Err(e) }; Ok(Atom(new_float)) }, None => Err(format!("Cannot parse number-like input of: '{}'", input)) } }, false => { match FromStr::from_str(input.as_slice()) { Some(val) => Ok(Atom(Integer(val))), None => Err(format!("Cannot parse number-like input of: {}", input)) } } } }, '#' => { // #-prefix parsing match &input { v if *v == "#f".to_string() => Ok(Atom(Boolean(false))), v if *v == "#false".to_string() => Ok(Atom(Boolean(false))), v if *v == "#t".to_string() => Ok(Atom(Boolean(true))), v if *v == "#true".to_string() => Ok(Atom(Boolean(true))), _ => Err(format!("un-implemented case of sharp/pound-prefixing")) } } _ => Ok(Atom(Symbol(input))) } } pub fn cons(car: Expr, cdr: Expr) -> ExprResult { let mut new_items = vec!(box car); match cdr { v @ Atom(_) => new_items.push(box v), List(cdr_items) => for i in cdr_items.move_iter() { new_items.push(i); } } Ok(List(new_items)) } pub fn print(&self) -> PrintResult { match self { &List(ref items) => { // this has to change let mut items_iter = items.iter(); let mut has_more = true; let mut printed_val = "(".to_string(); while has_more { match items_iter.next() { None => has_more = false, Some(ref i) => match i.print() { Ok(i) => { printed_val = printed_val.append(i.append(" ").as_slice()) }, Err(e) => return Err(e) } } } Ok(printed_val.as_slice().trim().to_string().append(")")) }, &Atom(ref v) => (*v).print() } } pub fn un_cons(self) -> UnConsResult { match self { Atom(_) => return Err("expr.un_cons(): Cannot un_cons an Atom value" .to_string()), List(mut items) => { if items.len() == 0 { return Err("expr.un_cons(): cannot build car/cdr of empty list" .to_string()); } let car = match items.remove(0) { Some(v) => v, None => return Err("expr.un_cons(): items collection empty; \ shouldn't happen".to_string()) }; Ok((*car, List(items))) } } } // type-evaluating built-ins pub fn is_atom(&self) -> bool { match *self { Atom(_) => true, _ => false } } pub fn is_null(&self) -> bool { match *self { List(ref items) => items.len() == 0, _ => false } } // fns for consuming/breaking down Exprs into composed elements // or underlying values pub fn unbox_and_eval(self, env: Env) -> UnboxAndEvalResult { match self { List(items) => { let args: Vec<Expr> = items.move_iter().map(|x| *x).collect(); let mut env = env; let mut evald_args = Vec::new(); for i in args.move_iter() { let (evald_arg, out_env) = try!(eval(i, env)); let evald_arg = match evald_arg { Some(v) => v, _ => return Err("eval'd arg should ret expr".to_string()) }; env = out_env; evald_args.push(evald_arg); } Ok((evald_args, env)) }, _ => Err(format!("calling unbox on non-List expr")) } } pub fn
(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> { match self { Atom(Float(v)) => Ok(v.numer().clone()), Atom(Integer(v)) => Ok(v), _ => Err("calling into_integer() on non-numeric value".to_string()) } } } impl AtomVal { pub fn print(&self) -> PrintResult { match self { &Symbol(ref v) => Ok(v.to_string()), &Integer(ref v) => Ok(v.to_string()), &Float(ref v) => match Number::float_print(v) { Ok(v) => Ok(v), Err(e) => return Err(e) }, &Lambda(ref v) => v.print(), &Boolean(ref v) => Ok("#".to_string().append(format!("{}", v).as_slice())) } } } pub mod Number { use std::char; use std::num::Zero; use num::bigint::BigInt; use num::rational::{Ratio, BigRational}; use collections::TreeSet; use result::SchemerResult; use super::{AtomVal, Integer, Float}; use super::PrintResult; #[allow(dead_code)] pub fn integer(val: i64) -> SchemerResult<AtomVal> { let bi: BigInt = match FromPrimitive::from_i64(val) { Some(v) => v, None => return Err("Number::integer: should be able to convert i64->BigInt".to_string()) }; Ok(Integer(bi)) } pub fn uint(val: uint) -> SchemerResult<AtomVal> { let bi: BigInt = match FromPrimitive::from_uint(val) { Some(v) => v, None => return Err("Number::uint: should be able to convert uint->BigInt".to_string()) }; Ok(Integer(bi)) } pub fn float(val: f64) -> SchemerResult<AtomVal> { let br = match Ratio::from_float(val) { Some(v) => v, None => return Err("Number::float: should be able to convert f64->BigInt".to_string()) }; Ok(Float(br)) } // adapted from https://gist.github.com/kballard/4771f0d338fbb1896446 pub fn float_print(v: &BigRational) -> PrintResult { 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.".to_string()) }; let ten = Ratio::from_integer(ten); let mut seen = TreeSet::new(); while!v.is_zero() { v = v * ten; if seen.contains(&v) { s.push_str("…"); break; } seen.insert(v.clone()); 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; } 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, None => return Err( "float_print: couldn't parse char_digit. Also unlikely.".to_string()) }; s.push_char(char_digit); v = v.fract(); } } Ok(s.into_string()) } }
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 num::rational::{Ratio, BigRational}; use num::bigint::BigInt; use env::Env; use eval::eval; use result::SchemerResult; pub type ExprResult = SchemerResult<Expr>; pub type UnboxAndEvalResult = SchemerResult<(Vec<Expr>, Env)>; pub type UnConsResult = SchemerResult<(Expr, Expr)>; pub type PrintResult = SchemerResult<String>; #[deriving(PartialEq, Show, Clone)] pub enum Expr { Atom(AtomVal), List(Vec<Box<Expr>>) } #[deriving(PartialEq, Show, Clone)] pub enum AtomVal { Symbol(String), Integer(BigInt), Float(BigRational), Lambda(LambdaVal), Boolean(bool) } #[deriving(Clone)] pub enum LambdaVal { UserDefined(String, Vec<String>, Box<Expr>, Env), BuiltIn(String, fn(args: Vec<Expr>, env: Env) -> SchemerResult<(Option<Expr>, Env)>) } impl LambdaVal { pub fn print(&self) -> PrintResult { match self { &UserDefined(ref name, ref vars, _, _) => { let var_expr = List(vars.iter().map(|v| box Atom(Symbol(v.to_string()))).collect()); let printed_val = match var_expr.print() { Ok(v) => v, Err(e) => return Err(e) }; Ok(format!("lambda:{}{}", name.to_string(), printed_val)) }, &BuiltIn(ref name, _) => Ok(format!("builtin-fn:{}", name.to_string())) } } } impl PartialEq for LambdaVal { // Our custom eq allows numbers which are near each other to be equal! :D fn eq(&self, other: &LambdaVal) -> bool { match self { &UserDefined(ref name, ref args, ref body, _) => match other { &UserDefined(ref other_name, ref other_args, ref other_body, _) => name == other_name && { if args.len()!= other_args.len() { return false; } let mut args_match = true; for ctr in range(0, args.len()) { args_match = args[ctr] == other_args[ctr]; } args_match } && body == other_body, &BuiltIn(_, _) => false }, &BuiltIn(ref name, ref body_fn) => match other { &BuiltIn(ref other_name, ref other_body_fn) => *body_fn as *mut u8 == *other_body_fn as *mut u8 && name == other_name, &UserDefined(_, _, _, _) => false } } } } impl Show for LambdaVal { fn fmt(&self, f: &mut Formatter) -> Result { // The `f.buf` value is of the type `&mut io::Writer`, which is what the // write! macro is expecting. Note that this formatting ignores the // various flags provided to format strings. write!(f, "{}", self.print()) } } impl Expr { pub fn new_atom(input: String) -> ExprResult { let first_char = input.as_slice().char_at(0); match first_char { '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => { match input.as_slice().contains(".") { true =>
, false => { match FromStr::from_str(input.as_slice()) { Some(val) => Ok(Atom(Integer(val))), None => Err(format!("Cannot parse number-like input of: {}", input)) } } } }, '#' => { // #-prefix parsing match &input { v if *v == "#f".to_string() => Ok(Atom(Boolean(false))), v if *v == "#false".to_string() => Ok(Atom(Boolean(false))), v if *v == "#t".to_string() => Ok(Atom(Boolean(true))), v if *v == "#true".to_string() => Ok(Atom(Boolean(true))), _ => Err(format!("un-implemented case of sharp/pound-prefixing")) } } _ => Ok(Atom(Symbol(input))) } } pub fn cons(car: Expr, cdr: Expr) -> ExprResult { let mut new_items = vec!(box car); match cdr { v @ Atom(_) => new_items.push(box v), List(cdr_items) => for i in cdr_items.move_iter() { new_items.push(i); } } Ok(List(new_items)) } pub fn print(&self) -> PrintResult { match self { &List(ref items) => { // this has to change let mut items_iter = items.iter(); let mut has_more = true; let mut printed_val = "(".to_string(); while has_more { match items_iter.next() { None => has_more = false, Some(ref i) => match i.print() { Ok(i) => { printed_val = printed_val.append(i.append(" ").as_slice()) }, Err(e) => return Err(e) } } } Ok(printed_val.as_slice().trim().to_string().append(")")) }, &Atom(ref v) => (*v).print() } } pub fn un_cons(self) -> UnConsResult { match self { Atom(_) => return Err("expr.un_cons(): Cannot un_cons an Atom value" .to_string()), List(mut items) => { if items.len() == 0 { return Err("expr.un_cons(): cannot build car/cdr of empty list" .to_string()); } let car = match items.remove(0) { Some(v) => v, None => return Err("expr.un_cons(): items collection empty; \ shouldn't happen".to_string()) }; Ok((*car, List(items))) } } } // type-evaluating built-ins pub fn is_atom(&self) -> bool { match *self { Atom(_) => true, _ => false } } pub fn is_null(&self) -> bool { match *self { List(ref items) => items.len() == 0, _ => false } } // fns for consuming/breaking down Exprs into composed elements // or underlying values pub fn unbox_and_eval(self, env: Env) -> UnboxAndEvalResult { match self { List(items) => { let args: Vec<Expr> = items.move_iter().map(|x| *x).collect(); let mut env = env; let mut evald_args = Vec::new(); for i in args.move_iter() { let (evald_arg, out_env) = try!(eval(i, env)); let evald_arg = match evald_arg { Some(v) => v, _ => return Err("eval'd arg should ret expr".to_string()) }; env = out_env; evald_args.push(evald_arg); } Ok((evald_args, env)) }, _ => Err(format!("calling unbox on non-List expr")) } } pub fn into_float(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> { match self { Atom(Float(v)) => Ok(v.numer().clone()), Atom(Integer(v)) => Ok(v), _ => Err("calling into_integer() on non-numeric value".to_string()) } } } impl AtomVal { pub fn print(&self) -> PrintResult { match self { &Symbol(ref v) => Ok(v.to_string()), &Integer(ref v) => Ok(v.to_string()), &Float(ref v) => match Number::float_print(v) { Ok(v) => Ok(v), Err(e) => return Err(e) }, &Lambda(ref v) => v.print(), &Boolean(ref v) => Ok("#".to_string().append(format!("{}", v).as_slice())) } } } pub mod Number { use std::char; use std::num::Zero; use num::bigint::BigInt; use num::rational::{Ratio, BigRational}; use collections::TreeSet; use result::SchemerResult; use super::{AtomVal, Integer, Float}; use super::PrintResult; #[allow(dead_code)] pub fn integer(val: i64) -> SchemerResult<AtomVal> { let bi: BigInt = match FromPrimitive::from_i64(val) { Some(v) => v, None => return Err("Number::integer: should be able to convert i64->BigInt".to_string()) }; Ok(Integer(bi)) } pub fn uint(val: uint) -> SchemerResult<AtomVal> { let bi: BigInt = match FromPrimitive::from_uint(val) { Some(v) => v, None => return Err("Number::uint: should be able to convert uint->BigInt".to_string()) }; Ok(Integer(bi)) } pub fn float(val: f64) -> SchemerResult<AtomVal> { let br = match Ratio::from_float(val) { Some(v) => v, None => return Err("Number::float: should be able to convert f64->BigInt".to_string()) }; Ok(Float(br)) } // adapted from https://gist.github.com/kballard/4771f0d338fbb1896446 pub fn float_print(v: &BigRational) -> PrintResult { 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.".to_string()) }; let ten = Ratio::from_integer(ten); let mut seen = TreeSet::new(); while!v.is_zero() { v = v * ten; if seen.contains(&v) { s.push_str("…"); break; } seen.insert(v.clone()); 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; } 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, None => return Err( "float_print: couldn't parse char_digit. Also unlikely.".to_string()) }; s.push_char(char_digit); v = v.fract(); } } Ok(s.into_string()) } }
{ let parsed_val: Option<f64> = FromStr::from_str(input.as_slice()); match parsed_val { Some(val) => { let new_float = match Number::float(val) { Ok(v) => v, Err(e) => return Err(e) }; Ok(Atom(new_float)) }, None => Err(format!("Cannot parse number-like input of: '{}'", input)) } }
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 num::rational::{Ratio, BigRational}; use num::bigint::BigInt; use env::Env; use eval::eval; use result::SchemerResult; pub type ExprResult = SchemerResult<Expr>; pub type UnboxAndEvalResult = SchemerResult<(Vec<Expr>, Env)>; pub type UnConsResult = SchemerResult<(Expr, Expr)>; pub type PrintResult = SchemerResult<String>; #[deriving(PartialEq, Show, Clone)] pub enum Expr { Atom(AtomVal), List(Vec<Box<Expr>>) } #[deriving(PartialEq, Show, Clone)] pub enum AtomVal { Symbol(String), Integer(BigInt), Float(BigRational), Lambda(LambdaVal), Boolean(bool) } #[deriving(Clone)] pub enum LambdaVal { UserDefined(String, Vec<String>, Box<Expr>, Env), BuiltIn(String, fn(args: Vec<Expr>, env: Env) -> SchemerResult<(Option<Expr>, Env)>) } impl LambdaVal { pub fn print(&self) -> PrintResult { match self { &UserDefined(ref name, ref vars, _, _) => { let var_expr = List(vars.iter().map(|v| box Atom(Symbol(v.to_string()))).collect()); let printed_val = match var_expr.print() { Ok(v) => v, Err(e) => return Err(e) }; Ok(format!("lambda:{}{}", name.to_string(), printed_val)) }, &BuiltIn(ref name, _) => Ok(format!("builtin-fn:{}", name.to_string())) } } } impl PartialEq for LambdaVal { // Our custom eq allows numbers which are near each other to be equal! :D fn eq(&self, other: &LambdaVal) -> bool { match self { &UserDefined(ref name, ref args, ref body, _) => match other { &UserDefined(ref other_name, ref other_args, ref other_body, _) => name == other_name && { if args.len()!= other_args.len() { return false; } let mut args_match = true; for ctr in range(0, args.len()) { args_match = args[ctr] == other_args[ctr]; } args_match } && body == other_body, &BuiltIn(_, _) => false }, &BuiltIn(ref name, ref body_fn) => match other { &BuiltIn(ref other_name, ref other_body_fn) => *body_fn as *mut u8 == *other_body_fn as *mut u8 && name == other_name, &UserDefined(_, _, _, _) => false } } } } impl Show for LambdaVal { fn fmt(&self, f: &mut Formatter) -> Result { // The `f.buf` value is of the type `&mut io::Writer`, which is what the // write! macro is expecting. Note that this formatting ignores the // various flags provided to format strings. write!(f, "{}", self.print()) } } impl Expr { pub fn new_atom(input: String) -> ExprResult { let first_char = input.as_slice().char_at(0); match first_char { '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => { match input.as_slice().contains(".") { true => { let parsed_val: Option<f64> = FromStr::from_str(input.as_slice()); match parsed_val { Some(val) => { let new_float = match Number::float(val) { Ok(v) => v, Err(e) => return Err(e) }; Ok(Atom(new_float)) }, None => Err(format!("Cannot parse number-like input of: '{}'", input)) } }, false => { match FromStr::from_str(input.as_slice()) { Some(val) => Ok(Atom(Integer(val))), None => Err(format!("Cannot parse number-like input of: {}", input)) } } } }, '#' => { // #-prefix parsing match &input { v if *v == "#f".to_string() => Ok(Atom(Boolean(false))), v if *v == "#false".to_string() => Ok(Atom(Boolean(false))), v if *v == "#t".to_string() => Ok(Atom(Boolean(true))), v if *v == "#true".to_string() => Ok(Atom(Boolean(true))), _ => Err(format!("un-implemented case of sharp/pound-prefixing")) } } _ => Ok(Atom(Symbol(input))) } } pub fn cons(car: Expr, cdr: Expr) -> ExprResult { let mut new_items = vec!(box car); match cdr { v @ Atom(_) => new_items.push(box v), List(cdr_items) => for i in cdr_items.move_iter() { new_items.push(i); } } Ok(List(new_items)) } pub fn print(&self) -> PrintResult { match self { &List(ref items) => { // this has to change let mut items_iter = items.iter(); let mut has_more = true; let mut printed_val = "(".to_string(); while has_more { match items_iter.next() { None => has_more = false, Some(ref i) => match i.print() { Ok(i) => { printed_val = printed_val.append(i.append(" ").as_slice()) }, Err(e) => return Err(e) } } } Ok(printed_val.as_slice().trim().to_string().append(")")) }, &Atom(ref v) => (*v).print() } } pub fn un_cons(self) -> UnConsResult { match self { Atom(_) => return Err("expr.un_cons(): Cannot un_cons an Atom value" .to_string()), List(mut items) => { if items.len() == 0 { return Err("expr.un_cons(): cannot build car/cdr of empty list" .to_string()); } let car = match items.remove(0) { Some(v) => v, None => return Err("expr.un_cons(): items collection empty; \ shouldn't happen".to_string()) }; Ok((*car, List(items))) } } } // type-evaluating built-ins pub fn is_atom(&self) -> bool { match *self { Atom(_) => true, _ => false } } pub fn is_null(&self) -> bool { match *self { List(ref items) => items.len() == 0, _ => false } } // fns for consuming/breaking down Exprs into composed elements // or underlying values pub fn unbox_and_eval(self, env: Env) -> UnboxAndEvalResult { match self { List(items) => { let args: Vec<Expr> = items.move_iter().map(|x| *x).collect(); let mut env = env; let mut evald_args = Vec::new(); for i in args.move_iter() { let (evald_arg, out_env) = try!(eval(i, env)); let evald_arg = match evald_arg { Some(v) => v, _ => return Err("eval'd arg should ret expr".to_string()) }; env = out_env; evald_args.push(evald_arg); } Ok((evald_args, env)) }, _ => Err(format!("calling unbox on non-List expr")) } } pub fn into_float(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> { match self { Atom(Float(v)) => Ok(v.numer().clone()), Atom(Integer(v)) => Ok(v), _ => Err("calling into_integer() on non-numeric value".to_string()) } } } impl AtomVal { pub fn print(&self) -> PrintResult { match self { &Symbol(ref v) => Ok(v.to_string()), &Integer(ref v) => Ok(v.to_string()), &Float(ref v) => match Number::float_print(v) { Ok(v) => Ok(v), Err(e) => return Err(e) }, &Lambda(ref v) => v.print(), &Boolean(ref v) => Ok("#".to_string().append(format!("{}", v).as_slice())) } } } pub mod Number { use std::char; use std::num::Zero; use num::bigint::BigInt; use num::rational::{Ratio, BigRational}; use collections::TreeSet; use result::SchemerResult; use super::{AtomVal, Integer, Float}; use super::PrintResult; #[allow(dead_code)] pub fn integer(val: i64) -> SchemerResult<AtomVal> { let bi: BigInt = match FromPrimitive::from_i64(val) { Some(v) => v, None => return Err("Number::integer: should be able to convert i64->BigInt".to_string()) }; Ok(Integer(bi)) } pub fn uint(val: uint) -> SchemerResult<AtomVal> { let bi: BigInt = match FromPrimitive::from_uint(val) { Some(v) => v, None => return Err("Number::uint: should be able to convert uint->BigInt".to_string()) }; Ok(Integer(bi)) } pub fn float(val: f64) -> SchemerResult<AtomVal> { let br = match Ratio::from_float(val) { Some(v) => v, None => return Err("Number::float: should be able to convert f64->BigInt".to_string()) }; Ok(Float(br)) } // adapted from https://gist.github.com/kballard/4771f0d338fbb1896446 pub fn float_print(v: &BigRational) -> PrintResult { 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.".to_string()) }; let ten = Ratio::from_integer(ten); let mut seen = TreeSet::new(); while!v.is_zero() { v = v * ten; if seen.contains(&v) { s.push_str("…"); break; } seen.insert(v.clone());
} 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, None => return Err( "float_print: couldn't parse char_digit. Also unlikely.".to_string()) }; s.push_char(char_digit); v = v.fract(); } } Ok(s.into_string()) } }
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 file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use super::ecp::ECP; use super::ecp2::ECP2; use std::str; //use super::fp12::FP12; use super::big; use super::big::BIG; use super::pair; use super::rom; use rand::RAND; use sha3::SHA3; use sha3::SHAKE256; /* BLS API Functions */ pub const BFS: usize = big::MODBYTES as usize; pub const BGS: usize = big::MODBYTES as usize; pub const BLS_OK: isize = 0; pub const BLS_FAIL: isize = -1; /* hash a message to an ECP point, using SHA3 */ #[allow(non_snake_case)] pub fn bls_hashit(m: &str) -> ECP { 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; } /* 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); return BLS_OK; } /* Sign message m using private key s to produce signature sig */ pub fn
(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 { 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::another(&mut r, &pk, &hm); let mut v = pair::miller(&r); //.. or alternatively // let mut v = pair::ate2(&g, &d, &pk, &hm); v = pair::fexp(&v); if v.isunity() { return BLS_OK; } return BLS_FAIL; }
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 file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use super::ecp::ECP; use super::ecp2::ECP2; use std::str; //use super::fp12::FP12; use super::big; use super::big::BIG; use super::pair; use super::rom; use rand::RAND; use sha3::SHA3; use sha3::SHAKE256; /* BLS API Functions */ pub const BFS: usize = big::MODBYTES as usize; pub const BGS: usize = big::MODBYTES as usize; pub const BLS_OK: isize = 0; pub const BLS_FAIL: isize = -1; /* hash a message to an ECP point, using SHA3 */ #[allow(non_snake_case)] pub fn bls_hashit(m: &str) -> ECP { 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; } /* 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); return BLS_OK; } /* Sign message m using private key s to produce signature sig */ pub fn sign(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 { 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::another(&mut r, &pk, &hm); let mut v = pair::miller(&r); //.. or alternatively // let mut v = pair::ate2(&g, &d, &pk, &hm); v = pair::fexp(&v); if v.isunity()
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 file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use super::ecp::ECP; use super::ecp2::ECP2; use std::str; //use super::fp12::FP12; use super::big; use super::big::BIG; use super::pair; use super::rom; use rand::RAND; use sha3::SHA3; use sha3::SHAKE256; /* BLS API Functions */ pub const BFS: usize = big::MODBYTES as usize; pub const BGS: usize = big::MODBYTES as usize; pub const BLS_OK: isize = 0; pub const BLS_FAIL: isize = -1; /* hash a message to an ECP point, using SHA3 */ #[allow(non_snake_case)] pub fn bls_hashit(m: &str) -> ECP { 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; } /* 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); return BLS_OK; } /* Sign message m using private key s to produce signature sig */ pub fn sign(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);
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::another(&mut r, &pk, &hm); let mut v = pair::miller(&r); //.. or alternatively // let mut v = pair::ate2(&g, &d, &pk, &hm); v = pair::fexp(&v); if v.isunity() { return BLS_OK; } return BLS_FAIL; }
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 file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use super::ecp::ECP; use super::ecp2::ECP2; use std::str; //use super::fp12::FP12; use super::big; use super::big::BIG; use super::pair; use super::rom; use rand::RAND; use sha3::SHA3; use sha3::SHAKE256; /* BLS API Functions */ pub const BFS: usize = big::MODBYTES as usize; pub const BGS: usize = big::MODBYTES as usize; pub const BLS_OK: isize = 0; pub const BLS_FAIL: isize = -1; /* hash a message to an ECP point, using SHA3 */ #[allow(non_snake_case)] pub fn bls_hashit(m: &str) -> ECP
/* 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); return BLS_OK; } /* Sign message m using private key s to produce signature sig */ pub fn sign(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 { 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::another(&mut r, &pk, &hm); let mut v = pair::miller(&r); //.. or alternatively // let mut v = pair::ate2(&g, &d, &pk, &hm); v = pair::fexp(&v); if v.isunity() { return BLS_OK; } return BLS_FAIL; }
{ 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(unknown_features)] #![feature(box_syntax)] trait double { fn double(self: Box<Self>) -> uint; } impl double for uint { fn double(self: Box<uint>) -> uint { *self * 2_usize } } pub fn
() { 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(unknown_features)] #![feature(box_syntax)] trait double { fn double(self: Box<Self>) -> uint; } impl double for uint { fn double(self: Box<uint>) -> uint { *self * 2_usize } } pub fn main()
{ 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // #![deny(type_overflow)] fn test(x: i8)
#[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: 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 x3: i8 = -(129); //~ error: literal out of range for its type let x3: i8 = -{129}; //~ error: literal out of range for its type test(1000); //~ error: literal out of range for its type let x = 128_i8; //~ error: literal out of range for its type let x = 127_i8; let x = -128_i8; let x = -(128_i8); let x = -129_i8; //~ error: literal out of range for its type let x: i32 = 2147483647; // should be OK let x = 2147483647_i32; // should be OK let x: i32 = 2147483648; //~ error: literal out of range for its type let x = 2147483648_i32; //~ error: literal out of range for its type let x: i32 = -2147483648; // should be OK let x = -2147483648_i32; // should be OK let x: i32 = -2147483649; //~ error: literal out of range for its type let x = -2147483649_i32; //~ error: literal out of range for its type let x = -3.40282348e+38_f32; //~ error: literal out of range for its type let x = 3.40282348e+38_f32; //~ error: literal out of range for its type let x = -1.7976931348623159e+308_f64; //~ error: literal out of range for its type let x = 1.7976931348623159e+308_f64; //~ error: literal out of range for its type }
{ 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // #![deny(type_overflow)] fn test(x: i8) { println!("x {}", x); } #[allow(unused_variable)] fn
() { 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 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 x3: i8 = -(129); //~ error: literal out of range for its type let x3: i8 = -{129}; //~ error: literal out of range for its type test(1000); //~ error: literal out of range for its type let x = 128_i8; //~ error: literal out of range for its type let x = 127_i8; let x = -128_i8; let x = -(128_i8); let x = -129_i8; //~ error: literal out of range for its type let x: i32 = 2147483647; // should be OK let x = 2147483647_i32; // should be OK let x: i32 = 2147483648; //~ error: literal out of range for its type let x = 2147483648_i32; //~ error: literal out of range for its type let x: i32 = -2147483648; // should be OK let x = -2147483648_i32; // should be OK let x: i32 = -2147483649; //~ error: literal out of range for its type let x = -2147483649_i32; //~ error: literal out of range for its type let x = -3.40282348e+38_f32; //~ error: literal out of range for its type let x = 3.40282348e+38_f32; //~ error: literal out of range for its type let x = -1.7976931348623159e+308_f64; //~ error: literal out of range for its type let x = 1.7976931348623159e+308_f64; //~ 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // #![deny(type_overflow)] fn test(x: i8) { println!("x {}", x); } #[allow(unused_variable)]
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 x3: i8 = -(129); //~ error: literal out of range for its type let x3: i8 = -{129}; //~ error: literal out of range for its type test(1000); //~ error: literal out of range for its type let x = 128_i8; //~ error: literal out of range for its type let x = 127_i8; let x = -128_i8; let x = -(128_i8); let x = -129_i8; //~ error: literal out of range for its type let x: i32 = 2147483647; // should be OK let x = 2147483647_i32; // should be OK let x: i32 = 2147483648; //~ error: literal out of range for its type let x = 2147483648_i32; //~ error: literal out of range for its type let x: i32 = -2147483648; // should be OK let x = -2147483648_i32; // should be OK let x: i32 = -2147483649; //~ error: literal out of range for its type let x = -2147483649_i32; //~ error: literal out of range for its type let x = -3.40282348e+38_f32; //~ error: literal out of range for its type let x = 3.40282348e+38_f32; //~ error: literal out of range for its type let x = -1.7976931348623159e+308_f64; //~ error: literal out of range for its type let x = 1.7976931348623159e+308_f64; //~ error: literal out of range for its type }
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 enum SquareView { Clicked(u8), Unclicked, Flagged, Penalty, Points, } pub struct AbsoluteCoord { pub chunk: Coord<isize>, pub square: Coord<usize>, } impl From<AbsoluteCoord> for Coord<isize> { fn from(AbsoluteCoord { chunk, square }: AbsoluteCoord) -> Self { chunk * Coord::squared(8) + Coord::<isize>::from(square) } } impl From<Coord<isize>> for AbsoluteCoord { fn
(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: u64, chunks_lost: u64, } impl Game { pub fn new() -> Self { Game::default() } 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 hashbrown::hash_map::Entry::Vacant; if let Vacant(entry) = self.chunks.entry(chunk) { entry.insert(loop { // Ensure first click is not a mine let insert = Chunk::with_mines(); if insert.mines.get(square) { continue; } break insert; }); } IndexIterSigned::self_and_adjacent(chunk) .filter(|&coord| coord!= chunk) .for_each(|coord| if let Vacant(entry) = self.chunks.entry(coord) { entry.insert(Chunk::with_mines()); } ); } pub fn touch(&mut self, world_coords: &[Coord<isize>]) -> Option<Vec<Coord<isize>>> { let mut to_click = Vec::with_capacity(64); for &world_coord in world_coords { let AbsoluteCoord { chunk, square } = world_coord.into(); self.allocate_with_surround(chunk, square); self.calc_neighbors(chunk); { let touched_chunk = self.chunks.get_mut(&chunk).unwrap(); if touched_chunk.clicked.get(square) { continue; } // Actually click touched_chunk.flags.unset(square); touched_chunk.clicked.set(square); if touched_chunk.mines.get(square) { touched_chunk.status = chunk::Status::Lost; self.chunks_lost += 1; return None; } if touched_chunk.is_won() { touched_chunk.status = chunk::Status::Won; self.chunks_won += 1; } } let num_neighbors = self .chunks .get(&chunk) .unwrap() .neighbors .get(square); if num_neighbors == 0 { let fringe = IndexIterSigned::self_and_adjacent(Coord::<isize>::default()) .filter(|&offset| offset!= Coord::default()) .map(|offset| offset + world_coord); to_click.extend(fringe); } } 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(); if!chunk.clicked.get(square) { chunk.flags.toggle(square); } if chunk.is_won() { chunk.status = chunk::Status::Won; self.chunks_won += 1; } } fn calc_neighbors(&mut self, coord: Coord<isize>) { debug_assert!( IndexIterSigned::self_and_adjacent(coord) .all(|chunk| self.chunks.contains_key(&chunk)) ); let neighbors = { let mut canvas = NybbleField::default(); let center = self.chunks.get(&coord).unwrap(); if center.status!= chunk::Status::Enmined { return; } let surround = IndexIterSigned::self_and_adjacent(coord) .map(|target| self.chunks.get(&target)) .collect::<Option<Vec<_>>>() .unwrap(); for square_index in chunk::all_squares() { if center.mines.get(square_index) { continue; } // Mine squares have no count let square_index_i = Coord::<isize>::from(square_index); let count = IndexIterSigned::self_and_adjacent(Coord::<isize>::default()) .map(|offset| { const DIMENSION_COORD: Coord<isize> = Coord::squared(chunk::DIMENSION as isize); let RENAME_ME = square_index_i .add(offset) .add(DIMENSION_COORD) .div(DIMENSION_COORD); let chunk = RENAME_ME .mul(Coord(3, 1)) .sum() as usize; let square: Coord<usize> = square_index_i .add(offset) .add( Coord::squared(2) .sub(RENAME_ME) .mul(DIMENSION_COORD) ) .rem(DIMENSION_COORD) .into(); (chunk, square) }) .filter(|&(chunk, square)| surround[chunk].mines.get(square)) .count(); debug_assert!(count < std::u8::MAX.into()); canvas.set(square_index, count as u8); } canvas }; let dest = self.chunks.get_mut(&coord).unwrap(); dest.neighbors = neighbors; dest.status = chunk::Status::Neighbored; } } #[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::default(); game.touch(&touch_points); let active_count = game .chunks .values() .filter(|&chunk| chunk.status!= chunk::Status::Enmined) .count(); assert_eq!(game.chunks.len(), 25); assert_eq!(active_count, 5); } }
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 enum SquareView { Clicked(u8), Unclicked, Flagged, Penalty, Points, } pub struct AbsoluteCoord { pub chunk: Coord<isize>, pub square: Coord<usize>, } impl From<AbsoluteCoord> for Coord<isize> { fn from(AbsoluteCoord { chunk, square }: AbsoluteCoord) -> Self { chunk * Coord::squared(8) + Coord::<isize>::from(square) } } impl From<Coord<isize>> for AbsoluteCoord { fn from(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: u64, chunks_lost: u64, } impl Game { pub fn new() -> Self { Game::default() } 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 hashbrown::hash_map::Entry::Vacant; if let Vacant(entry) = self.chunks.entry(chunk) { entry.insert(loop { // Ensure first click is not a mine let insert = Chunk::with_mines(); if insert.mines.get(square) { continue; } break insert; }); } IndexIterSigned::self_and_adjacent(chunk) .filter(|&coord| coord!= chunk) .for_each(|coord| if let Vacant(entry) = self.chunks.entry(coord) { entry.insert(Chunk::with_mines()); } ); } pub fn touch(&mut self, world_coords: &[Coord<isize>]) -> Option<Vec<Coord<isize>>> { let mut to_click = Vec::with_capacity(64); for &world_coord in world_coords { let AbsoluteCoord { chunk, square } = world_coord.into(); self.allocate_with_surround(chunk, square); self.calc_neighbors(chunk); { let touched_chunk = self.chunks.get_mut(&chunk).unwrap(); if touched_chunk.clicked.get(square) { continue; } // Actually click touched_chunk.flags.unset(square); touched_chunk.clicked.set(square); if touched_chunk.mines.get(square) { touched_chunk.status = chunk::Status::Lost; self.chunks_lost += 1; return None; } if touched_chunk.is_won() { touched_chunk.status = chunk::Status::Won; self.chunks_won += 1; } } let num_neighbors = self .chunks .get(&chunk) .unwrap() .neighbors .get(square); if num_neighbors == 0 { let fringe = IndexIterSigned::self_and_adjacent(Coord::<isize>::default()) .filter(|&offset| offset!= Coord::default()) .map(|offset| offset + world_coord); to_click.extend(fringe); } } 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(); if!chunk.clicked.get(square) { chunk.flags.toggle(square); } if chunk.is_won() { chunk.status = chunk::Status::Won; self.chunks_won += 1; } } fn calc_neighbors(&mut self, coord: Coord<isize>) { debug_assert!( IndexIterSigned::self_and_adjacent(coord) .all(|chunk| self.chunks.contains_key(&chunk)) ); let neighbors = { let mut canvas = NybbleField::default(); let center = self.chunks.get(&coord).unwrap(); if center.status!= chunk::Status::Enmined { return; } let surround = IndexIterSigned::self_and_adjacent(coord) .map(|target| self.chunks.get(&target)) .collect::<Option<Vec<_>>>() .unwrap(); for square_index in chunk::all_squares() { if center.mines.get(square_index) { continue; } // Mine squares have no count let square_index_i = Coord::<isize>::from(square_index); let count = IndexIterSigned::self_and_adjacent(Coord::<isize>::default()) .map(|offset| { const DIMENSION_COORD: Coord<isize> = Coord::squared(chunk::DIMENSION as isize); let RENAME_ME = square_index_i .add(offset) .add(DIMENSION_COORD) .div(DIMENSION_COORD); let chunk = RENAME_ME .mul(Coord(3, 1)) .sum() as usize; let square: Coord<usize> = square_index_i .add(offset) .add( Coord::squared(2) .sub(RENAME_ME) .mul(DIMENSION_COORD) ) .rem(DIMENSION_COORD) .into(); (chunk, square) }) .filter(|&(chunk, square)| surround[chunk].mines.get(square)) .count(); debug_assert!(count < std::u8::MAX.into()); canvas.set(square_index, count as u8); } canvas }; let dest = self.chunks.get_mut(&coord).unwrap(); dest.neighbors = neighbors; dest.status = chunk::Status::Neighbored; }
} #[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::default(); game.touch(&touch_points); let active_count = game .chunks .values() .filter(|&chunk| chunk.status!= chunk::Status::Enmined) .count(); assert_eq!(game.chunks.len(), 25); assert_eq!(active_count, 5); } }
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 enum SquareView { Clicked(u8), Unclicked, Flagged, Penalty, Points, } pub struct AbsoluteCoord { pub chunk: Coord<isize>, pub square: Coord<usize>, } impl From<AbsoluteCoord> for Coord<isize> { fn from(AbsoluteCoord { chunk, square }: AbsoluteCoord) -> Self { chunk * Coord::squared(8) + Coord::<isize>::from(square) } } impl From<Coord<isize>> for AbsoluteCoord { fn from(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: u64, chunks_lost: u64, } impl Game { pub fn new() -> Self
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 hashbrown::hash_map::Entry::Vacant; if let Vacant(entry) = self.chunks.entry(chunk) { entry.insert(loop { // Ensure first click is not a mine let insert = Chunk::with_mines(); if insert.mines.get(square) { continue; } break insert; }); } IndexIterSigned::self_and_adjacent(chunk) .filter(|&coord| coord!= chunk) .for_each(|coord| if let Vacant(entry) = self.chunks.entry(coord) { entry.insert(Chunk::with_mines()); } ); } pub fn touch(&mut self, world_coords: &[Coord<isize>]) -> Option<Vec<Coord<isize>>> { let mut to_click = Vec::with_capacity(64); for &world_coord in world_coords { let AbsoluteCoord { chunk, square } = world_coord.into(); self.allocate_with_surround(chunk, square); self.calc_neighbors(chunk); { let touched_chunk = self.chunks.get_mut(&chunk).unwrap(); if touched_chunk.clicked.get(square) { continue; } // Actually click touched_chunk.flags.unset(square); touched_chunk.clicked.set(square); if touched_chunk.mines.get(square) { touched_chunk.status = chunk::Status::Lost; self.chunks_lost += 1; return None; } if touched_chunk.is_won() { touched_chunk.status = chunk::Status::Won; self.chunks_won += 1; } } let num_neighbors = self .chunks .get(&chunk) .unwrap() .neighbors .get(square); if num_neighbors == 0 { let fringe = IndexIterSigned::self_and_adjacent(Coord::<isize>::default()) .filter(|&offset| offset!= Coord::default()) .map(|offset| offset + world_coord); to_click.extend(fringe); } } 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(); if!chunk.clicked.get(square) { chunk.flags.toggle(square); } if chunk.is_won() { chunk.status = chunk::Status::Won; self.chunks_won += 1; } } fn calc_neighbors(&mut self, coord: Coord<isize>) { debug_assert!( IndexIterSigned::self_and_adjacent(coord) .all(|chunk| self.chunks.contains_key(&chunk)) ); let neighbors = { let mut canvas = NybbleField::default(); let center = self.chunks.get(&coord).unwrap(); if center.status!= chunk::Status::Enmined { return; } let surround = IndexIterSigned::self_and_adjacent(coord) .map(|target| self.chunks.get(&target)) .collect::<Option<Vec<_>>>() .unwrap(); for square_index in chunk::all_squares() { if center.mines.get(square_index) { continue; } // Mine squares have no count let square_index_i = Coord::<isize>::from(square_index); let count = IndexIterSigned::self_and_adjacent(Coord::<isize>::default()) .map(|offset| { const DIMENSION_COORD: Coord<isize> = Coord::squared(chunk::DIMENSION as isize); let RENAME_ME = square_index_i .add(offset) .add(DIMENSION_COORD) .div(DIMENSION_COORD); let chunk = RENAME_ME .mul(Coord(3, 1)) .sum() as usize; let square: Coord<usize> = square_index_i .add(offset) .add( Coord::squared(2) .sub(RENAME_ME) .mul(DIMENSION_COORD) ) .rem(DIMENSION_COORD) .into(); (chunk, square) }) .filter(|&(chunk, square)| surround[chunk].mines.get(square)) .count(); debug_assert!(count < std::u8::MAX.into()); canvas.set(square_index, count as u8); } canvas }; let dest = self.chunks.get_mut(&coord).unwrap(); dest.neighbors = neighbors; dest.status = chunk::Status::Neighbored; } } #[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::default(); game.touch(&touch_points); let active_count = game .chunks .values() .filter(|&chunk| chunk.status!= chunk::Status::Enmined) .count(); assert_eq!(game.chunks.len(), 25); assert_eq!(active_count, 5); } }
{ 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 enum SquareView { Clicked(u8), Unclicked, Flagged, Penalty, Points, } pub struct AbsoluteCoord { pub chunk: Coord<isize>, pub square: Coord<usize>, } impl From<AbsoluteCoord> for Coord<isize> { fn from(AbsoluteCoord { chunk, square }: AbsoluteCoord) -> Self { chunk * Coord::squared(8) + Coord::<isize>::from(square) } } impl From<Coord<isize>> for AbsoluteCoord { fn from(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: u64, chunks_lost: u64, } impl Game { pub fn new() -> Self { Game::default() } 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 hashbrown::hash_map::Entry::Vacant; if let Vacant(entry) = self.chunks.entry(chunk) { entry.insert(loop { // Ensure first click is not a mine let insert = Chunk::with_mines(); if insert.mines.get(square) { continue; } break insert; }); } IndexIterSigned::self_and_adjacent(chunk) .filter(|&coord| coord!= chunk) .for_each(|coord| if let Vacant(entry) = self.chunks.entry(coord) { entry.insert(Chunk::with_mines()); } ); } pub fn touch(&mut self, world_coords: &[Coord<isize>]) -> Option<Vec<Coord<isize>>> { let mut to_click = Vec::with_capacity(64); for &world_coord in world_coords { let AbsoluteCoord { chunk, square } = world_coord.into(); self.allocate_with_surround(chunk, square); self.calc_neighbors(chunk); { let touched_chunk = self.chunks.get_mut(&chunk).unwrap(); if touched_chunk.clicked.get(square) { continue; } // Actually click touched_chunk.flags.unset(square); touched_chunk.clicked.set(square); if touched_chunk.mines.get(square) { touched_chunk.status = chunk::Status::Lost; self.chunks_lost += 1; return None; } if touched_chunk.is_won() { touched_chunk.status = chunk::Status::Won; self.chunks_won += 1; } } let num_neighbors = self .chunks .get(&chunk) .unwrap() .neighbors .get(square); if num_neighbors == 0
} 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(); if!chunk.clicked.get(square) { chunk.flags.toggle(square); } if chunk.is_won() { chunk.status = chunk::Status::Won; self.chunks_won += 1; } } fn calc_neighbors(&mut self, coord: Coord<isize>) { debug_assert!( IndexIterSigned::self_and_adjacent(coord) .all(|chunk| self.chunks.contains_key(&chunk)) ); let neighbors = { let mut canvas = NybbleField::default(); let center = self.chunks.get(&coord).unwrap(); if center.status!= chunk::Status::Enmined { return; } let surround = IndexIterSigned::self_and_adjacent(coord) .map(|target| self.chunks.get(&target)) .collect::<Option<Vec<_>>>() .unwrap(); for square_index in chunk::all_squares() { if center.mines.get(square_index) { continue; } // Mine squares have no count let square_index_i = Coord::<isize>::from(square_index); let count = IndexIterSigned::self_and_adjacent(Coord::<isize>::default()) .map(|offset| { const DIMENSION_COORD: Coord<isize> = Coord::squared(chunk::DIMENSION as isize); let RENAME_ME = square_index_i .add(offset) .add(DIMENSION_COORD) .div(DIMENSION_COORD); let chunk = RENAME_ME .mul(Coord(3, 1)) .sum() as usize; let square: Coord<usize> = square_index_i .add(offset) .add( Coord::squared(2) .sub(RENAME_ME) .mul(DIMENSION_COORD) ) .rem(DIMENSION_COORD) .into(); (chunk, square) }) .filter(|&(chunk, square)| surround[chunk].mines.get(square)) .count(); debug_assert!(count < std::u8::MAX.into()); canvas.set(square_index, count as u8); } canvas }; let dest = self.chunks.get_mut(&coord).unwrap(); dest.neighbors = neighbors; dest.status = chunk::Status::Neighbored; } } #[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::default(); game.touch(&touch_points); let active_count = game .chunks .values() .filter(|&chunk| chunk.status!= chunk::Status::Enmined) .count(); assert_eq!(game.chunks.len(), 25); assert_eq!(active_count, 5); } }
{ 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 = 0xb, PingReq = 0xc, // PingResp = 0xd, Disconnect = 0xe, } pub fn message_type(bytes: &[u8]) -> MqttType { unsafe { mem::transmute((bytes[0] & 0xf0) >> 4) } } fn connect_bytes() -> Vec<u8> { vec!( 0x10u8, 0x2a, // fixed header 0x00, 0x06, 'M' as u8, 'Q' as u8, 'I' as u8,'s' as u8, 'd' as u8, 'p' as u8, 0x03, // protocol version 0xcc, // connection flags 1100111x user, pw,!wr, w(01), w,!c, x 0x00, 0x0a, // keepalive of 100 0x00, 0x03, 'c' as u8, 'i' as u8, 'd' as u8, // client ID 0x00, 0x04, 'w' as u8, 'i' as u8, 'l' as u8, 'l' as u8, // will topic 0x00, 0x04, 'w' as u8,'m' as u8,'s' as u8, 'g' as u8, // will msg 0x00, 0x07, 'g' as u8, 'l' as u8, 'i' as u8, 'f' as u8, 't' as u8, 'e' as u8, 'l' as u8, // username 0x00, 0x02, 'p' as u8, 'w' as u8, // password ) } #[test] fn connect_type() { let connect_bytes = connect_bytes(); assert_eq!(message_type(&connect_bytes), MqttType::Connect); } #[test] fn ping_type() { let ping_bytes = &[0xc0u8, 0][0..]; assert_eq!(message_type(ping_bytes), MqttType::PingReq); } #[test] fn subscribe_type() { let subscribe_header = &[0x80, 0][0..]; assert_eq!(message_type(subscribe_header), MqttType::Subscribe); } #[test] fn suback_type() { let subscribe_header = &[0x90, 3, 0, 7, 1][0..]; assert_eq!(message_type(subscribe_header), MqttType::SubAck); } #[test] fn disconnect_type() { 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 multiplier: usize = 1; let mut value: usize = 0; let mut digit: usize = bytes[0] as usize; loop { // do-while would be cleaner... value += (digit & 127) * multiplier; multiplier *= 128; if (digit & 128) == 0 { break; } if bytes.len() > 1 { digit = bytes[1..][0] as usize; } } value } #[test] fn connect_len() { assert_eq!(remaining_length(&connect_bytes()), 42); }
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); assert_eq!(remaining_length(&[0x12, 0x83, 0x02]), 259); //assert_eq!(remaining_length(&[0x12, 0x85, 0x80, 0x01]), 2097157); } pub fn subscribe_msg_id(bytes: &[u8]) -> u16 { bytes[3] as u16 } #[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 topic_len = topic_len as usize; String::from_utf8(bytes[4.. 4 + topic_len].to_vec()) .expect("Could not convert publish topic to vec") } #[test] fn test_get_topic_with_msg_id() { let pub_bytes = vec![ 0x3c, 0x0d, //fixed header 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8,//topic name 0x00, 0x21, //message ID 'b' as u8, 'o' as u8, 'r' as u8, 'g' as u8, //payload ]; assert_eq!(publish_topic(&pub_bytes[..]), "first"); } pub fn publish_payload(bytes: &[u8]) -> &[u8] { let topic_len = publish_topic(bytes).len(); let mut start = HEADER_LEN + topic_len + 2; if (bytes[0] & 0x06)!= 0 { start += 2; } &bytes[start..] } #[test] fn test_get_payload_with_msg_id() { let pub_bytes = vec![ 0x3c, 0x0d, //fixed header 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8,//topic name 0x00, 0x21, //message ID 1, 2, 3, 4, //payload ]; assert_eq!(publish_payload(&pub_bytes[..]).to_vec(), vec![1, 2, 3, 4]); } #[test] fn test_get_payload_no_msg_id() { let pub_bytes = vec![ 0x30, 0x0a, //fixed header 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8,//topic name 9, 8, 7, //payload ]; assert_eq!(publish_payload(&pub_bytes[..]).to_vec(), vec![9, 8, 7]); } pub fn subscribe_topics(bytes: &[u8]) -> Vec<String> { let start = HEADER_LEN + 2; // final 2 for msg_id let mut res = vec![]; let mut slice = &bytes[start.. ]; while slice.len() > 0 { let topic_len = (((slice[0] as u16) << 8) + slice[1] as u16) as usize; let topic_slice = &slice[2.. 2 + topic_len]; res.push(String::from_utf8(topic_slice.to_vec()) .expect("Could not convert subscribe topic to vec")); //first 2 for topic len, last 1 for qos slice = &slice[2 + topic_len + 1.. ]; } res } #[test] fn test_subscribe_topics1() { let sub_bytes = vec![ 0x8b, 0x13, //fixed header 0x00, 0x21, //message ID 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8, 0x01, //qos 0x00, 0x06,'s' as u8, 'e' as u8, 'c' as u8, 'o' as u8, 'n' as u8, 'd' as u8, 0x02, //qos ]; assert_eq!(subscribe_topics(&sub_bytes[..]), vec!["first".to_string(), "second".to_string()]); } #[test] fn test_subscribe_topics2() { let sub_bytes = vec![ 0x8b, 0x12, //fixed header 0x00, 0x21, //message ID 0x00, 0x04, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 0x01, //qos 0x00, 0x06,'s' as u8, 'e' as u8, 'c' as u8, 'o' as u8, 'n' as u8, 'd' as u8, 0x02, //qos ]; assert_eq!(subscribe_topics(&sub_bytes[..]), vec!["firs".to_string(), "second".to_string()]); } pub fn total_length(bytes: &[u8]) -> usize { return remaining_length(bytes) + HEADER_LEN; }
#[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 = 0xb, PingReq = 0xc, // PingResp = 0xd, Disconnect = 0xe, } pub fn message_type(bytes: &[u8]) -> MqttType { unsafe { mem::transmute((bytes[0] & 0xf0) >> 4) } } fn connect_bytes() -> Vec<u8> { vec!( 0x10u8, 0x2a, // fixed header 0x00, 0x06, 'M' as u8, 'Q' as u8, 'I' as u8,'s' as u8, 'd' as u8, 'p' as u8, 0x03, // protocol version 0xcc, // connection flags 1100111x user, pw,!wr, w(01), w,!c, x 0x00, 0x0a, // keepalive of 100 0x00, 0x03, 'c' as u8, 'i' as u8, 'd' as u8, // client ID 0x00, 0x04, 'w' as u8, 'i' as u8, 'l' as u8, 'l' as u8, // will topic 0x00, 0x04, 'w' as u8,'m' as u8,'s' as u8, 'g' as u8, // will msg 0x00, 0x07, 'g' as u8, 'l' as u8, 'i' as u8, 'f' as u8, 't' as u8, 'e' as u8, 'l' as u8, // username 0x00, 0x02, 'p' as u8, 'w' as u8, // password ) } #[test] fn connect_type() { let connect_bytes = connect_bytes(); assert_eq!(message_type(&connect_bytes), MqttType::Connect); } #[test] fn ping_type() { let ping_bytes = &[0xc0u8, 0][0..]; assert_eq!(message_type(ping_bytes), MqttType::PingReq); } #[test] fn subscribe_type() { let subscribe_header = &[0x80, 0][0..]; assert_eq!(message_type(subscribe_header), MqttType::Subscribe); } #[test] fn suback_type() { let subscribe_header = &[0x90, 3, 0, 7, 1][0..]; assert_eq!(message_type(subscribe_header), MqttType::SubAck); } #[test] fn disconnect_type() { 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 multiplier: usize = 1; let mut value: usize = 0; let mut digit: usize = bytes[0] as usize; loop { // do-while would be cleaner... value += (digit & 127) * multiplier; multiplier *= 128; if (digit & 128) == 0 { break; } if bytes.len() > 1
} 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_length(&[0x15, 5]), 5); assert_eq!(remaining_length(&[0x27, 7]), 7); assert_eq!(remaining_length(&[0x12, 0xc1, 0x02]), 321); assert_eq!(remaining_length(&[0x12, 0x83, 0x02]), 259); //assert_eq!(remaining_length(&[0x12, 0x85, 0x80, 0x01]), 2097157); } pub fn subscribe_msg_id(bytes: &[u8]) -> u16 { bytes[3] as u16 } #[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 topic_len = topic_len as usize; String::from_utf8(bytes[4.. 4 + topic_len].to_vec()) .expect("Could not convert publish topic to vec") } #[test] fn test_get_topic_with_msg_id() { let pub_bytes = vec![ 0x3c, 0x0d, //fixed header 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8,//topic name 0x00, 0x21, //message ID 'b' as u8, 'o' as u8, 'r' as u8, 'g' as u8, //payload ]; assert_eq!(publish_topic(&pub_bytes[..]), "first"); } pub fn publish_payload(bytes: &[u8]) -> &[u8] { let topic_len = publish_topic(bytes).len(); let mut start = HEADER_LEN + topic_len + 2; if (bytes[0] & 0x06)!= 0 { start += 2; } &bytes[start..] } #[test] fn test_get_payload_with_msg_id() { let pub_bytes = vec![ 0x3c, 0x0d, //fixed header 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8,//topic name 0x00, 0x21, //message ID 1, 2, 3, 4, //payload ]; assert_eq!(publish_payload(&pub_bytes[..]).to_vec(), vec![1, 2, 3, 4]); } #[test] fn test_get_payload_no_msg_id() { let pub_bytes = vec![ 0x30, 0x0a, //fixed header 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8,//topic name 9, 8, 7, //payload ]; assert_eq!(publish_payload(&pub_bytes[..]).to_vec(), vec![9, 8, 7]); } pub fn subscribe_topics(bytes: &[u8]) -> Vec<String> { let start = HEADER_LEN + 2; // final 2 for msg_id let mut res = vec![]; let mut slice = &bytes[start.. ]; while slice.len() > 0 { let topic_len = (((slice[0] as u16) << 8) + slice[1] as u16) as usize; let topic_slice = &slice[2.. 2 + topic_len]; res.push(String::from_utf8(topic_slice.to_vec()) .expect("Could not convert subscribe topic to vec")); //first 2 for topic len, last 1 for qos slice = &slice[2 + topic_len + 1.. ]; } res } #[test] fn test_subscribe_topics1() { let sub_bytes = vec![ 0x8b, 0x13, //fixed header 0x00, 0x21, //message ID 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8, 0x01, //qos 0x00, 0x06,'s' as u8, 'e' as u8, 'c' as u8, 'o' as u8, 'n' as u8, 'd' as u8, 0x02, //qos ]; assert_eq!(subscribe_topics(&sub_bytes[..]), vec!["first".to_string(), "second".to_string()]); } #[test] fn test_subscribe_topics2() { let sub_bytes = vec![ 0x8b, 0x12, //fixed header 0x00, 0x21, //message ID 0x00, 0x04, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 0x01, //qos 0x00, 0x06,'s' as u8, 'e' as u8, 'c' as u8, 'o' as u8, 'n' as u8, 'd' as u8, 0x02, //qos ]; assert_eq!(subscribe_topics(&sub_bytes[..]), vec!["firs".to_string(), "second".to_string()]); } pub fn total_length(bytes: &[u8]) -> usize { return remaining_length(bytes) + HEADER_LEN; }
{ 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 = 0xb, PingReq = 0xc, // PingResp = 0xd, Disconnect = 0xe, } pub fn message_type(bytes: &[u8]) -> MqttType { unsafe { mem::transmute((bytes[0] & 0xf0) >> 4) } } fn connect_bytes() -> Vec<u8> { vec!( 0x10u8, 0x2a, // fixed header 0x00, 0x06, 'M' as u8, 'Q' as u8, 'I' as u8,'s' as u8, 'd' as u8, 'p' as u8, 0x03, // protocol version 0xcc, // connection flags 1100111x user, pw,!wr, w(01), w,!c, x 0x00, 0x0a, // keepalive of 100 0x00, 0x03, 'c' as u8, 'i' as u8, 'd' as u8, // client ID 0x00, 0x04, 'w' as u8, 'i' as u8, 'l' as u8, 'l' as u8, // will topic 0x00, 0x04, 'w' as u8,'m' as u8,'s' as u8, 'g' as u8, // will msg 0x00, 0x07, 'g' as u8, 'l' as u8, 'i' as u8, 'f' as u8, 't' as u8, 'e' as u8, 'l' as u8, // username 0x00, 0x02, 'p' as u8, 'w' as u8, // password ) } #[test] fn connect_type() { let connect_bytes = connect_bytes(); assert_eq!(message_type(&connect_bytes), MqttType::Connect); } #[test] fn ping_type() { let ping_bytes = &[0xc0u8, 0][0..]; assert_eq!(message_type(ping_bytes), MqttType::PingReq); } #[test] fn subscribe_type() { let subscribe_header = &[0x80, 0][0..]; assert_eq!(message_type(subscribe_header), MqttType::Subscribe); } #[test] fn suback_type() { let subscribe_header = &[0x90, 3, 0, 7, 1][0..]; assert_eq!(message_type(subscribe_header), MqttType::SubAck); } #[test] fn
() { 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 multiplier: usize = 1; let mut value: usize = 0; let mut digit: usize = bytes[0] as usize; loop { // do-while would be cleaner... value += (digit & 127) * multiplier; multiplier *= 128; if (digit & 128) == 0 { break; } if bytes.len() > 1 { digit = bytes[1..][0] as usize; } } 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_length(&[0x15, 5]), 5); assert_eq!(remaining_length(&[0x27, 7]), 7); assert_eq!(remaining_length(&[0x12, 0xc1, 0x02]), 321); assert_eq!(remaining_length(&[0x12, 0x83, 0x02]), 259); //assert_eq!(remaining_length(&[0x12, 0x85, 0x80, 0x01]), 2097157); } pub fn subscribe_msg_id(bytes: &[u8]) -> u16 { bytes[3] as u16 } #[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 topic_len = topic_len as usize; String::from_utf8(bytes[4.. 4 + topic_len].to_vec()) .expect("Could not convert publish topic to vec") } #[test] fn test_get_topic_with_msg_id() { let pub_bytes = vec![ 0x3c, 0x0d, //fixed header 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8,//topic name 0x00, 0x21, //message ID 'b' as u8, 'o' as u8, 'r' as u8, 'g' as u8, //payload ]; assert_eq!(publish_topic(&pub_bytes[..]), "first"); } pub fn publish_payload(bytes: &[u8]) -> &[u8] { let topic_len = publish_topic(bytes).len(); let mut start = HEADER_LEN + topic_len + 2; if (bytes[0] & 0x06)!= 0 { start += 2; } &bytes[start..] } #[test] fn test_get_payload_with_msg_id() { let pub_bytes = vec![ 0x3c, 0x0d, //fixed header 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8,//topic name 0x00, 0x21, //message ID 1, 2, 3, 4, //payload ]; assert_eq!(publish_payload(&pub_bytes[..]).to_vec(), vec![1, 2, 3, 4]); } #[test] fn test_get_payload_no_msg_id() { let pub_bytes = vec![ 0x30, 0x0a, //fixed header 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8,//topic name 9, 8, 7, //payload ]; assert_eq!(publish_payload(&pub_bytes[..]).to_vec(), vec![9, 8, 7]); } pub fn subscribe_topics(bytes: &[u8]) -> Vec<String> { let start = HEADER_LEN + 2; // final 2 for msg_id let mut res = vec![]; let mut slice = &bytes[start.. ]; while slice.len() > 0 { let topic_len = (((slice[0] as u16) << 8) + slice[1] as u16) as usize; let topic_slice = &slice[2.. 2 + topic_len]; res.push(String::from_utf8(topic_slice.to_vec()) .expect("Could not convert subscribe topic to vec")); //first 2 for topic len, last 1 for qos slice = &slice[2 + topic_len + 1.. ]; } res } #[test] fn test_subscribe_topics1() { let sub_bytes = vec![ 0x8b, 0x13, //fixed header 0x00, 0x21, //message ID 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8, 0x01, //qos 0x00, 0x06,'s' as u8, 'e' as u8, 'c' as u8, 'o' as u8, 'n' as u8, 'd' as u8, 0x02, //qos ]; assert_eq!(subscribe_topics(&sub_bytes[..]), vec!["first".to_string(), "second".to_string()]); } #[test] fn test_subscribe_topics2() { let sub_bytes = vec![ 0x8b, 0x12, //fixed header 0x00, 0x21, //message ID 0x00, 0x04, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 0x01, //qos 0x00, 0x06,'s' as u8, 'e' as u8, 'c' as u8, 'o' as u8, 'n' as u8, 'd' as u8, 0x02, //qos ]; assert_eq!(subscribe_topics(&sub_bytes[..]), vec!["firs".to_string(), "second".to_string()]); } pub fn total_length(bytes: &[u8]) -> usize { return remaining_length(bytes) + HEADER_LEN; }
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 = 0xb, PingReq = 0xc, // PingResp = 0xd, Disconnect = 0xe, } pub fn message_type(bytes: &[u8]) -> MqttType { unsafe { mem::transmute((bytes[0] & 0xf0) >> 4) } } fn connect_bytes() -> Vec<u8> { vec!( 0x10u8, 0x2a, // fixed header 0x00, 0x06, 'M' as u8, 'Q' as u8, 'I' as u8,'s' as u8, 'd' as u8, 'p' as u8, 0x03, // protocol version 0xcc, // connection flags 1100111x user, pw,!wr, w(01), w,!c, x 0x00, 0x0a, // keepalive of 100 0x00, 0x03, 'c' as u8, 'i' as u8, 'd' as u8, // client ID 0x00, 0x04, 'w' as u8, 'i' as u8, 'l' as u8, 'l' as u8, // will topic 0x00, 0x04, 'w' as u8,'m' as u8,'s' as u8, 'g' as u8, // will msg 0x00, 0x07, 'g' as u8, 'l' as u8, 'i' as u8, 'f' as u8, 't' as u8, 'e' as u8, 'l' as u8, // username 0x00, 0x02, 'p' as u8, 'w' as u8, // password ) } #[test] fn connect_type() { let connect_bytes = connect_bytes(); assert_eq!(message_type(&connect_bytes), MqttType::Connect); } #[test] fn ping_type() { let ping_bytes = &[0xc0u8, 0][0..]; assert_eq!(message_type(ping_bytes), MqttType::PingReq); } #[test] fn subscribe_type() { let subscribe_header = &[0x80, 0][0..]; assert_eq!(message_type(subscribe_header), MqttType::Subscribe); } #[test] fn suback_type() { let subscribe_header = &[0x90, 3, 0, 7, 1][0..]; assert_eq!(message_type(subscribe_header), MqttType::SubAck); } #[test] fn disconnect_type() { 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 multiplier: usize = 1; let mut value: usize = 0; let mut digit: usize = bytes[0] as usize; loop { // do-while would be cleaner... value += (digit & 127) * multiplier; multiplier *= 128; if (digit & 128) == 0 { break; } if bytes.len() > 1 { digit = bytes[1..][0] as usize; } } 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_length(&[0x15, 5]), 5); assert_eq!(remaining_length(&[0x27, 7]), 7); assert_eq!(remaining_length(&[0x12, 0xc1, 0x02]), 321); assert_eq!(remaining_length(&[0x12, 0x83, 0x02]), 259); //assert_eq!(remaining_length(&[0x12, 0x85, 0x80, 0x01]), 2097157); } pub fn subscribe_msg_id(bytes: &[u8]) -> u16
#[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 topic_len = topic_len as usize; String::from_utf8(bytes[4.. 4 + topic_len].to_vec()) .expect("Could not convert publish topic to vec") } #[test] fn test_get_topic_with_msg_id() { let pub_bytes = vec![ 0x3c, 0x0d, //fixed header 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8,//topic name 0x00, 0x21, //message ID 'b' as u8, 'o' as u8, 'r' as u8, 'g' as u8, //payload ]; assert_eq!(publish_topic(&pub_bytes[..]), "first"); } pub fn publish_payload(bytes: &[u8]) -> &[u8] { let topic_len = publish_topic(bytes).len(); let mut start = HEADER_LEN + topic_len + 2; if (bytes[0] & 0x06)!= 0 { start += 2; } &bytes[start..] } #[test] fn test_get_payload_with_msg_id() { let pub_bytes = vec![ 0x3c, 0x0d, //fixed header 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8,//topic name 0x00, 0x21, //message ID 1, 2, 3, 4, //payload ]; assert_eq!(publish_payload(&pub_bytes[..]).to_vec(), vec![1, 2, 3, 4]); } #[test] fn test_get_payload_no_msg_id() { let pub_bytes = vec![ 0x30, 0x0a, //fixed header 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8,//topic name 9, 8, 7, //payload ]; assert_eq!(publish_payload(&pub_bytes[..]).to_vec(), vec![9, 8, 7]); } pub fn subscribe_topics(bytes: &[u8]) -> Vec<String> { let start = HEADER_LEN + 2; // final 2 for msg_id let mut res = vec![]; let mut slice = &bytes[start.. ]; while slice.len() > 0 { let topic_len = (((slice[0] as u16) << 8) + slice[1] as u16) as usize; let topic_slice = &slice[2.. 2 + topic_len]; res.push(String::from_utf8(topic_slice.to_vec()) .expect("Could not convert subscribe topic to vec")); //first 2 for topic len, last 1 for qos slice = &slice[2 + topic_len + 1.. ]; } res } #[test] fn test_subscribe_topics1() { let sub_bytes = vec![ 0x8b, 0x13, //fixed header 0x00, 0x21, //message ID 0x00, 0x05, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 't' as u8, 0x01, //qos 0x00, 0x06,'s' as u8, 'e' as u8, 'c' as u8, 'o' as u8, 'n' as u8, 'd' as u8, 0x02, //qos ]; assert_eq!(subscribe_topics(&sub_bytes[..]), vec!["first".to_string(), "second".to_string()]); } #[test] fn test_subscribe_topics2() { let sub_bytes = vec![ 0x8b, 0x12, //fixed header 0x00, 0x21, //message ID 0x00, 0x04, 'f' as u8, 'i' as u8, 'r' as u8,'s' as u8, 0x01, //qos 0x00, 0x06,'s' as u8, 'e' as u8, 'c' as u8, 'o' as u8, 'n' as u8, 'd' as u8, 0x02, //qos ]; assert_eq!(subscribe_topics(&sub_bytes[..]), vec!["firs".to_string(), "second".to_string()]); } pub fn total_length(bytes: &[u8]) -> usize { return remaining_length(bytes) + HEADER_LEN; }
{ 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 Rust is to return a `Result`. pub fn encode(plaintext: &str, a: i32, b: i32) -> Result<String, AffineCipherError> { // Reject the key if `a` and `MODULUS` aren't coprime. match modular_multiplicative_inverse(a) { Some(_) => Ok(plaintext .to_lowercase() .chars() .filter(|&ch| ch.is_ascii_alphanumeric()) .map(|ch| encode_char(ch, a, b)) .collect::<Vec<char>>() .chunks(5) .map(|slice| slice.iter().cloned().collect::<String>()) .collect::<Vec<String>>() .join(" ")), None => Err(AffineCipherError::NotCoprime(a)), } } /// Decodes the ciphertext using the affine cipher with key (`a`, `b`). Note that, rather than /// returning a return code, the more common convention in Rust is to return a `Result`. pub fn decode(ciphertext: &str, a: i32, b: i32) -> Result<String, AffineCipherError> { // Reject the key if `a` and `MODULUS` aren't coprime. match modular_multiplicative_inverse(a) { Some(inv) => Ok(ciphertext .to_lowercase() .chars() .filter(|&ch| ch.is_ascii_alphanumeric()) .map(|ch| decode_char(ch, inv, b)) .collect()), None => Err(AffineCipherError::NotCoprime(a)), } } /// Encodes a single char with the key (`a`, `b`). The key is assumed to be valid (i.e. `a` should /// be coprime to 26). fn encode_char(ch: char, a: i32, b: i32) -> char { if ch.is_digit(10) { ch } else { let index = (ch as i32) - ('a' as i32); let encoded = (a * index + b).rem_euclid(MODULUS) + 'a' as i32; encoded as u8 as char } } /// Decodes a single char using `inv` (the modular multiplicative inverse of `a`) and `b`. fn decode_char(ch: char, inv: i32, b: i32) -> char { 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 }
} /// 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. 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); rs = (rs.1, rs.0 - q * rs.1); ts = (ts.1, ts.0 - q * ts.1); } // `rs.0` gives the GCD. This must be 1 for an inverse to exist. if rs.0 == 1 { // ts.0 gives a number such that (s * 26 + t * a) % 26 == 1. Since (s * 26) % 26 == 0, // we can further reduce this to (t * a) % 26 == 1. In other words, t is the MMI of a. Some(ts.0 as i32) } else { None } }
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 Rust is to return a `Result`. pub fn encode(plaintext: &str, a: i32, b: i32) -> Result<String, AffineCipherError> { // Reject the key if `a` and `MODULUS` aren't coprime. match modular_multiplicative_inverse(a) { Some(_) => Ok(plaintext .to_lowercase() .chars() .filter(|&ch| ch.is_ascii_alphanumeric()) .map(|ch| encode_char(ch, a, b)) .collect::<Vec<char>>() .chunks(5) .map(|slice| slice.iter().cloned().collect::<String>()) .collect::<Vec<String>>() .join(" ")), None => Err(AffineCipherError::NotCoprime(a)), } } /// Decodes the ciphertext using the affine cipher with key (`a`, `b`). Note that, rather than /// returning a return code, the more common convention in Rust is to return a `Result`. pub fn decode(ciphertext: &str, a: i32, b: i32) -> Result<String, AffineCipherError> { // Reject the key if `a` and `MODULUS` aren't coprime. match modular_multiplicative_inverse(a) { Some(inv) => Ok(ciphertext .to_lowercase() .chars() .filter(|&ch| ch.is_ascii_alphanumeric()) .map(|ch| decode_char(ch, inv, b)) .collect()), None => Err(AffineCipherError::NotCoprime(a)), } } /// Encodes a single char with the key (`a`, `b`). The key is assumed to be valid (i.e. `a` should /// be coprime to 26). fn encode_char(ch: char, a: i32, b: i32) -> char { if ch.is_digit(10) { ch } else { let index = (ch as i32) - ('a' as i32); let encoded = (a * index + b).rem_euclid(MODULUS) + 'a' as i32; encoded as u8 as char } } /// Decodes a single char using `inv` (the modular multiplicative inverse of `a`) and `b`. fn decode_char(ch: char, inv: i32, b: i32) -> char { if ch.is_digit(10) { ch } else
} /// 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. 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); rs = (rs.1, rs.0 - q * rs.1); ts = (ts.1, ts.0 - q * ts.1); } // `rs.0` gives the GCD. This must be 1 for an inverse to exist. if rs.0 == 1 { // ts.0 gives a number such that (s * 26 + t * a) % 26 == 1. Since (s * 26) % 26 == 0, // we can further reduce this to (t * a) % 26 == 1. In other words, t is the MMI of a. Some(ts.0 as i32) } else { None } }
{ 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 Rust is to return a `Result`. pub fn encode(plaintext: &str, a: i32, b: i32) -> Result<String, AffineCipherError> { // Reject the key if `a` and `MODULUS` aren't coprime. match modular_multiplicative_inverse(a) { Some(_) => Ok(plaintext .to_lowercase() .chars() .filter(|&ch| ch.is_ascii_alphanumeric()) .map(|ch| encode_char(ch, a, b)) .collect::<Vec<char>>() .chunks(5) .map(|slice| slice.iter().cloned().collect::<String>()) .collect::<Vec<String>>() .join(" ")), None => Err(AffineCipherError::NotCoprime(a)), } } /// Decodes the ciphertext using the affine cipher with key (`a`, `b`). Note that, rather than /// returning a return code, the more common convention in Rust is to return a `Result`. pub fn decode(ciphertext: &str, a: i32, b: i32) -> Result<String, AffineCipherError> { // Reject the key if `a` and `MODULUS` aren't coprime. match modular_multiplicative_inverse(a) { Some(inv) => Ok(ciphertext .to_lowercase() .chars() .filter(|&ch| ch.is_ascii_alphanumeric()) .map(|ch| decode_char(ch, inv, b)) .collect()), None => Err(AffineCipherError::NotCoprime(a)), } } /// Encodes a single char with the key (`a`, `b`). The key is assumed to be valid (i.e. `a` should /// be coprime to 26). fn encode_char(ch: char, a: i32, b: i32) -> char { if ch.is_digit(10) { ch } else { let index = (ch as i32) - ('a' as i32); let encoded = (a * index + b).rem_euclid(MODULUS) + 'a' as i32; encoded as u8 as char } } /// Decodes a single char using `inv` (the modular multiplicative inverse of `a`) and `b`. fn decode_char(ch: char, inv: i32, b: i32) -> char
/// 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. 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); rs = (rs.1, rs.0 - q * rs.1); ts = (ts.1, ts.0 - q * ts.1); } // `rs.0` gives the GCD. This must be 1 for an inverse to exist. if rs.0 == 1 { // ts.0 gives a number such that (s * 26 + t * a) % 26 == 1. Since (s * 26) % 26 == 0, // we can further reduce this to (t * a) % 26 == 1. In other words, t is the MMI of a. Some(ts.0 as i32) } else { None } }
{ 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 Rust is to return a `Result`. pub fn encode(plaintext: &str, a: i32, b: i32) -> Result<String, AffineCipherError> { // Reject the key if `a` and `MODULUS` aren't coprime. match modular_multiplicative_inverse(a) { Some(_) => Ok(plaintext .to_lowercase() .chars() .filter(|&ch| ch.is_ascii_alphanumeric()) .map(|ch| encode_char(ch, a, b)) .collect::<Vec<char>>() .chunks(5) .map(|slice| slice.iter().cloned().collect::<String>()) .collect::<Vec<String>>() .join(" ")), None => Err(AffineCipherError::NotCoprime(a)), } } /// Decodes the ciphertext using the affine cipher with key (`a`, `b`). Note that, rather than /// returning a return code, the more common convention in Rust is to return a `Result`. pub fn decode(ciphertext: &str, a: i32, b: i32) -> Result<String, AffineCipherError> { // Reject the key if `a` and `MODULUS` aren't coprime. match modular_multiplicative_inverse(a) { Some(inv) => Ok(ciphertext .to_lowercase() .chars() .filter(|&ch| ch.is_ascii_alphanumeric()) .map(|ch| decode_char(ch, inv, b)) .collect()), None => Err(AffineCipherError::NotCoprime(a)), } } /// Encodes a single char with the key (`a`, `b`). The key is assumed to be valid (i.e. `a` should /// be coprime to 26). fn encode_char(ch: char, a: i32, b: i32) -> char { if ch.is_digit(10) { ch } else { let index = (ch as i32) - ('a' as i32); let encoded = (a * index + b).rem_euclid(MODULUS) + 'a' as i32; encoded as u8 as char } } /// Decodes a single char using `inv` (the modular multiplicative inverse of `a`) and `b`. fn decode_char(ch: char, inv: i32, b: i32) -> char { 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 } } /// Calculates the modular multiplicative inverse using the extended Euclidean algorithm. /// See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm for details. fn
(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); rs = (rs.1, rs.0 - q * rs.1); ts = (ts.1, ts.0 - q * ts.1); } // `rs.0` gives the GCD. This must be 1 for an inverse to exist. if rs.0 == 1 { // ts.0 gives a number such that (s * 26 + t * a) % 26 == 1. Since (s * 26) % 26 == 0, // we can further reduce this to (t * a) % 26 == 1. In other words, t is the MMI of a. Some(ts.0 as i32) } else { None } }
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. #[repr(i32)] pub enum RebootMode { RB_HALT_SYSTEM, RB_KEXEC, RB_POWER_OFF, RB_AUTOBOOT, // we do not support Restart2, RB_SW_SUSPEND, } } pub fn reboot(how: RebootMode) -> Result<Void> { unsafe { libc::reboot(how as libc::c_int) }; Err(Error::Sys(Errno::last())) } /// Enable or disable the reboot keystroke (Ctrl-Alt-Delete). /// /// Corresponds to calling `reboot(RB_ENABLE_CAD)` or `reboot(RB_DISABLE_CAD)` in C. pub fn
(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. #[repr(i32)] pub enum RebootMode { RB_HALT_SYSTEM, RB_KEXEC, RB_POWER_OFF, RB_AUTOBOOT, // we do not support Restart2, RB_SW_SUSPEND, } } pub fn reboot(how: RebootMode) -> Result<Void> { unsafe { libc::reboot(how as libc::c_int) }; Err(Error::Sys(Errno::last())) } /// Enable or disable the reboot keystroke (Ctrl-Alt-Delete). /// /// Corresponds to calling `reboot(RB_ENABLE_CAD)` or `reboot(RB_DISABLE_CAD)` in C. pub fn set_cad_enabled(enable: bool) -> Result<()> { let cmd = if enable { libc::RB_ENABLE_CAD } else
; 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_HALT_SYSTEM, RB_KEXEC, RB_POWER_OFF, RB_AUTOBOOT, // we do not support Restart2, RB_SW_SUSPEND, } } pub fn reboot(how: RebootMode) -> Result<Void> { unsafe { libc::reboot(how as libc::c_int) }; Err(Error::Sys(Errno::last())) } /// Enable or disable the reboot keystroke (Ctrl-Alt-Delete). /// /// Corresponds to calling `reboot(RB_ENABLE_CAD)` or `reboot(RB_DISABLE_CAD)` in C. pub fn set_cad_enabled(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) }
//! 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. #[repr(i32)] pub enum RebootMode { RB_HALT_SYSTEM, RB_KEXEC, RB_POWER_OFF, RB_AUTOBOOT, // we do not support Restart2, RB_SW_SUSPEND, } } pub fn reboot(how: RebootMode) -> Result<Void> { unsafe { libc::reboot(how as libc::c_int) }; Err(Error::Sys(Errno::last())) } /// Enable or disable the reboot keystroke (Ctrl-Alt-Delete). /// /// Corresponds to calling `reboot(RB_ENABLE_CAD)` or `reboot(RB_DISABLE_CAD)` in C. pub fn set_cad_enabled(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) }
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-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cmp; #[deriving(Show)] enum cat_type { tuxedo, tabby, tortoiseshell } impl cmp::Eq for cat_type { fn eq(&self, other: &cat_type) -> bool { ((*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> { // Yes, you can have negative meows meows : int, how_hungry : int, name : T, } impl<T> cat<T> { pub fn speak(&mut self) { self.meow(); } 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) -> uint { self.meows as uint } fn is_empty(&self) -> bool { self.meows == 0 } } impl<T> Mutable for cat<T> { fn clear(&mut self) {} } impl<T> Map<int, T> for cat<T> { fn contains_key(&self, k: &int) -> bool { *k <= self.meows } fn find<'a>(&'a self, k: &int) -> Option<&'a T> { if *k <= self.meows { Some(&self.name) } else { None } } } impl<T> MutableMap<int, T> for cat<T> { fn insert(&mut self, k: int, _: T) -> bool { self.meows += k; true } fn find_mut<'a>(&'a mut self, _k: &int) -> Option<&'a mut T> { fail!() } fn remove(&mut self, k: &int) -> bool { if self.find(k).is_some() { self.meows -= *k; true } else { false } } fn
(&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: int, in_y: int, in_name: T) -> cat<T> { cat{meows: in_x, how_hungry: in_y, name: in_name } } } impl<T> cat<T> { fn meow(&mut self) { self.meows += 1; println!("Meow {}", self.meows); if self.meows % 5 == 0 { self.how_hungry += 1; } } } pub fn main() { let mut nyan: cat<StrBuf> = cat::new(0, 2, "nyan".to_strbuf()); for _ in range(1u, 5) { nyan.speak(); } assert!(*nyan.find(&1).unwrap() == "nyan".to_strbuf()); assert_eq!(nyan.find(&10), None); let mut spotty: cat<cat_type> = cat::new(2, 57, tuxedo); for _ in range(0u, 6) { spotty.speak(); } assert_eq!(spotty.len(), 8); assert!((spotty.contains_key(&2))); assert_eq!(spotty.get(&3), &tuxedo); }
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-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cmp; #[deriving(Show)] enum cat_type { tuxedo, tabby, tortoiseshell } impl cmp::Eq for cat_type { fn eq(&self, other: &cat_type) -> bool { ((*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> { // Yes, you can have negative meows meows : int, how_hungry : int, name : T, } impl<T> cat<T> { pub fn speak(&mut self)
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) -> uint { self.meows as uint } fn is_empty(&self) -> bool { self.meows == 0 } } impl<T> Mutable for cat<T> { fn clear(&mut self) {} } impl<T> Map<int, T> for cat<T> { fn contains_key(&self, k: &int) -> bool { *k <= self.meows } fn find<'a>(&'a self, k: &int) -> Option<&'a T> { if *k <= self.meows { Some(&self.name) } else { None } } } impl<T> MutableMap<int, T> for cat<T> { fn insert(&mut self, k: int, _: T) -> bool { self.meows += k; true } fn find_mut<'a>(&'a mut self, _k: &int) -> Option<&'a mut T> { fail!() } fn remove(&mut self, k: &int) -> bool { if self.find(k).is_some() { self.meows -= *k; true } else { false } } 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"); } } } pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> { cat{meows: in_x, how_hungry: in_y, name: in_name } } } impl<T> cat<T> { fn meow(&mut self) { self.meows += 1; println!("Meow {}", self.meows); if self.meows % 5 == 0 { self.how_hungry += 1; } } } pub fn main() { let mut nyan: cat<StrBuf> = cat::new(0, 2, "nyan".to_strbuf()); for _ in range(1u, 5) { nyan.speak(); } assert!(*nyan.find(&1).unwrap() == "nyan".to_strbuf()); assert_eq!(nyan.find(&10), None); let mut spotty: cat<cat_type> = cat::new(2, 57, tuxedo); for _ in range(0u, 6) { spotty.speak(); } assert_eq!(spotty.len(), 8); assert!((spotty.contains_key(&2))); assert_eq!(spotty.get(&3), &tuxedo); }
{ 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-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cmp; #[deriving(Show)] enum cat_type { tuxedo, tabby, tortoiseshell } impl cmp::Eq for cat_type { fn eq(&self, other: &cat_type) -> bool { ((*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> { // Yes, you can have negative meows meows : int, how_hungry : int, name : T, } impl<T> cat<T> { pub fn speak(&mut self) { self.meow(); } 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) -> uint { self.meows as uint } fn is_empty(&self) -> bool { self.meows == 0 } } impl<T> Mutable for cat<T> { fn clear(&mut self) {} } impl<T> Map<int, T> for cat<T> { fn contains_key(&self, k: &int) -> bool { *k <= self.meows } fn find<'a>(&'a self, k: &int) -> Option<&'a T> { if *k <= self.meows { Some(&self.name) } else { None } } } impl<T> MutableMap<int, T> for cat<T> { fn insert(&mut self, k: int, _: T) -> bool { self.meows += k; true } fn find_mut<'a>(&'a mut self, _k: &int) -> Option<&'a mut T> { fail!() } fn remove(&mut self, k: &int) -> bool { if self.find(k).is_some() { self.meows -= *k; true } else
} 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"); } } } pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> { cat{meows: in_x, how_hungry: in_y, name: in_name } } } impl<T> cat<T> { fn meow(&mut self) { self.meows += 1; println!("Meow {}", self.meows); if self.meows % 5 == 0 { self.how_hungry += 1; } } } pub fn main() { let mut nyan: cat<StrBuf> = cat::new(0, 2, "nyan".to_strbuf()); for _ in range(1u, 5) { nyan.speak(); } assert!(*nyan.find(&1).unwrap() == "nyan".to_strbuf()); assert_eq!(nyan.find(&10), None); let mut spotty: cat<cat_type> = cat::new(2, 57, tuxedo); for _ in range(0u, 6) { spotty.speak(); } assert_eq!(spotty.len(), 8); assert!((spotty.contains_key(&2))); assert_eq!(spotty.get(&3), &tuxedo); }
{ 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-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cmp;
((*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> { // Yes, you can have negative meows meows : int, how_hungry : int, name : T, } impl<T> cat<T> { pub fn speak(&mut self) { self.meow(); } 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) -> uint { self.meows as uint } fn is_empty(&self) -> bool { self.meows == 0 } } impl<T> Mutable for cat<T> { fn clear(&mut self) {} } impl<T> Map<int, T> for cat<T> { fn contains_key(&self, k: &int) -> bool { *k <= self.meows } fn find<'a>(&'a self, k: &int) -> Option<&'a T> { if *k <= self.meows { Some(&self.name) } else { None } } } impl<T> MutableMap<int, T> for cat<T> { fn insert(&mut self, k: int, _: T) -> bool { self.meows += k; true } fn find_mut<'a>(&'a mut self, _k: &int) -> Option<&'a mut T> { fail!() } fn remove(&mut self, k: &int) -> bool { if self.find(k).is_some() { self.meows -= *k; true } else { false } } 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"); } } } pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> { cat{meows: in_x, how_hungry: in_y, name: in_name } } } impl<T> cat<T> { fn meow(&mut self) { self.meows += 1; println!("Meow {}", self.meows); if self.meows % 5 == 0 { self.how_hungry += 1; } } } pub fn main() { let mut nyan: cat<StrBuf> = cat::new(0, 2, "nyan".to_strbuf()); for _ in range(1u, 5) { nyan.speak(); } assert!(*nyan.find(&1).unwrap() == "nyan".to_strbuf()); assert_eq!(nyan.find(&10), None); let mut spotty: cat<cat_type> = cat::new(2, 57, tuxedo); for _ in range(0u, 6) { spotty.speak(); } assert_eq!(spotty.len(), 8); assert!((spotty.contains_key(&2))); assert_eq!(spotty.get(&3), &tuxedo); }
#[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 mount(config: &Mount, block_device: &str) -> Result<(), MountError> { let mut cmd = Command::new("/bin/mount"); cmd.arg(block_device); cmd.arg(config.target.to_owned()); trace!("invoking mount: {:?}", cmd); let result = try!(cmd.stdin(Stdio::null()).output()); if result.status.success() { trace!("external mount command succeeded"); Ok(()) } else
} #[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("/bin/mount"); cmd.arg(block_device); cmd.arg(config.target.to_owned()); trace!("invoking mount: {:?}", cmd); let result = try!(cmd.stdin(Stdio::null()).output()); if result.status.success() { trace!("external mount command succeeded"); 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 {}
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 mount(config: &Mount, block_device: &str) -> Result<(), MountError> { let mut cmd = Command::new("/bin/mount"); cmd.arg(block_device); cmd.arg(config.target.to_owned()); trace!("invoking mount: {:?}", cmd); let result = try!(cmd.stdin(Stdio::null()).output()); if result.status.success() {
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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(unsafe_destructor)] use std::cell::Cell; use std::gc::{Gc, GC}; // Resources can't be copied, but storing into data structures counts // as a move unless the stored thing is used afterwards. struct r { i: Gc<Cell<int>>, } struct Box { x: r } #[unsafe_destructor] impl Drop for r { fn drop(&mut self) { self.i.set(self.i.get() + 1) } } fn r(i: Gc<Cell<int>>) -> r { r { i: i } } fn test_box() { let i = box(GC) Cell::new(0i); { let _a = box(GC) r(i); } assert_eq!(i.get(), 1); } 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) Cell::new(0i); { let _a = (r(i), 0i); } assert_eq!(i.get(), 1); } fn test_unique() { let i = box(GC) Cell::new(0i); { let _a = box r(i); } assert_eq!(i.get(), 1); } fn
() { 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(unsafe_destructor)] use std::cell::Cell; use std::gc::{Gc, GC}; // Resources can't be copied, but storing into data structures counts // as a move unless the stored thing is used afterwards. struct r { i: Gc<Cell<int>>, } struct Box { x: r } #[unsafe_destructor] impl Drop for r { fn drop(&mut self) { self.i.set(self.i.get() + 1) } } fn r(i: Gc<Cell<int>>) -> r { r { i: i } } fn test_box()
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) Cell::new(0i); { let _a = (r(i), 0i); } assert_eq!(i.get(), 1); } fn test_unique() { let i = box(GC) Cell::new(0i); { let _a = box r(i); } assert_eq!(i.get(), 1); } fn test_box_rec() { 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(); }
{ 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(unsafe_destructor)] use std::cell::Cell; use std::gc::{Gc, GC}; // Resources can't be copied, but storing into data structures counts // as a move unless the stored thing is used afterwards. struct r { i: Gc<Cell<int>>, } struct Box { x: r } #[unsafe_destructor] impl Drop for r { fn drop(&mut self) { self.i.set(self.i.get() + 1) } } fn r(i: Gc<Cell<int>>) -> r { r { i: i } } fn test_box() { let i = box(GC) Cell::new(0i); { let _a = box(GC) r(i); } assert_eq!(i.get(), 1); } 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) Cell::new(0i); { let _a = (r(i), 0i); } assert_eq!(i.get(), 1); } fn test_unique() { let i = box(GC) Cell::new(0i); { let _a = box r(i); } assert_eq!(i.get(), 1); } fn test_box_rec() { 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(); }
};
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-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use self::WhichLine::*; use std::io::{BufferedReader, File}; pub struct ExpectedError { pub line: uint, pub kind: String, pub msg: String, } #[derive(PartialEq, Show)] enum
{ 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: //~^^^ ERROR go up three /// and also //~^ ERROR message one for the preceding line, and /// //~| ERROR message two for that same line. // Load any test directives embedded in the file pub fn load_errors(testfile: &Path) -> Vec<ExpectedError> { let mut rdr = BufferedReader::new(File::open(testfile).unwrap()); // `last_nonfollow_error` tracks the most recently seen // line with an error template that did not use the // follow-syntax, "//~|...". // // (pnkfelix could not find an easy way to compose Iterator::scan // and Iterator::filter_map to pass along this information into // `parse_expected`. So instead I am storing that state here and // updating it in the map callback below.) let mut last_nonfollow_error = None; rdr.lines().enumerate().filter_map(|(line_no, ln)| { parse_expected(last_nonfollow_error, line_no + 1, ln.unwrap().as_slice()) .map(|(which, error)| { match which { FollowPrevious(_) => {} _ => last_nonfollow_error = Some(error.line), } error }) }).collect() } 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, 0) } else { (false, line[start + 3..].chars().take_while(|c| *c == '^').count()) }; let kind_start = start + 3 + adjusts + (follow as usize); let letters = line[kind_start..].chars(); let kind = letters.skip_while(|c| c.is_whitespace()) .take_while(|c|!c.is_whitespace()) .map(|c| c.to_lowercase()) .collect::<String>(); let letters = line[kind_start..].chars(); let msg = letters.skip_while(|c| c.is_whitespace()) .skip_while(|c|!c.is_whitespace()) .collect::<String>().trim().to_string(); let (which, line) = if follow { assert!(adjusts == 0, "use either //~| or //~^, not both."); let line = last_nonfollow_error.unwrap_or_else(|| { panic!("encountered //~| without preceding //~^ line.") }); (FollowPrevious(line), line) } 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, kind: kind, msg: msg, })) }
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-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use self::WhichLine::*; use std::io::{BufferedReader, File}; pub struct ExpectedError { pub line: uint, pub kind: String, pub msg: String, } #[derive(PartialEq, Show)] enum WhichLine { 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: //~^^^ ERROR go up three /// and also //~^ ERROR message one for the preceding line, and /// //~| ERROR message two for that same line. // Load any test directives embedded in the file pub fn load_errors(testfile: &Path) -> Vec<ExpectedError> { let mut rdr = BufferedReader::new(File::open(testfile).unwrap()); // `last_nonfollow_error` tracks the most recently seen // line with an error template that did not use the // follow-syntax, "//~|...". // // (pnkfelix could not find an easy way to compose Iterator::scan // and Iterator::filter_map to pass along this information into // `parse_expected`. So instead I am storing that state here and // updating it in the map callback below.) let mut last_nonfollow_error = None; rdr.lines().enumerate().filter_map(|(line_no, ln)| { parse_expected(last_nonfollow_error, line_no + 1, ln.unwrap().as_slice()) .map(|(which, error)| { match which { FollowPrevious(_) => {} _ => last_nonfollow_error = Some(error.line), } error }) }).collect() }
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, 0) } else { (false, line[start + 3..].chars().take_while(|c| *c == '^').count()) }; let kind_start = start + 3 + adjusts + (follow as usize); let letters = line[kind_start..].chars(); let kind = letters.skip_while(|c| c.is_whitespace()) .take_while(|c|!c.is_whitespace()) .map(|c| c.to_lowercase()) .collect::<String>(); let letters = line[kind_start..].chars(); let msg = letters.skip_while(|c| c.is_whitespace()) .skip_while(|c|!c.is_whitespace()) .collect::<String>().trim().to_string(); let (which, line) = if follow { assert!(adjusts == 0, "use either //~| or //~^, not both."); let line = last_nonfollow_error.unwrap_or_else(|| { panic!("encountered //~| without preceding //~^ line.") }); (FollowPrevious(line), line) } 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, kind: kind, msg: msg, })) }
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-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use self::WhichLine::*; use std::io::{BufferedReader, File}; pub struct ExpectedError { pub line: uint, pub kind: String, pub msg: String, } #[derive(PartialEq, Show)] enum WhichLine { 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: //~^^^ ERROR go up three /// and also //~^ ERROR message one for the preceding line, and /// //~| ERROR message two for that same line. // Load any test directives embedded in the file pub fn load_errors(testfile: &Path) -> Vec<ExpectedError> { let mut rdr = BufferedReader::new(File::open(testfile).unwrap()); // `last_nonfollow_error` tracks the most recently seen // line with an error template that did not use the // follow-syntax, "//~|...". // // (pnkfelix could not find an easy way to compose Iterator::scan // and Iterator::filter_map to pass along this information into // `parse_expected`. So instead I am storing that state here and // updating it in the map callback below.) let mut last_nonfollow_error = None; rdr.lines().enumerate().filter_map(|(line_no, ln)| { parse_expected(last_nonfollow_error, line_no + 1, ln.unwrap().as_slice()) .map(|(which, error)| { match which { FollowPrevious(_) => {} _ => last_nonfollow_error = Some(error.line), } error }) }).collect() } 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, 0) } else { (false, line[start + 3..].chars().take_while(|c| *c == '^').count()) }; let kind_start = start + 3 + adjusts + (follow as usize); let letters = line[kind_start..].chars(); let kind = letters.skip_while(|c| c.is_whitespace()) .take_while(|c|!c.is_whitespace()) .map(|c| c.to_lowercase()) .collect::<String>(); let letters = line[kind_start..].chars(); let msg = letters.skip_while(|c| c.is_whitespace()) .skip_while(|c|!c.is_whitespace()) .collect::<String>().trim().to_string(); let (which, line) = if follow
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, kind: kind, msg: msg, })) }
{ 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 <[email protected]> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate libc; use std::io; use std::mem; pub use self::native::{close, retry, addr_to_sockaddr, sockaddr_to_addr}; mod native; #[cfg(windows)] pub type CSocket = libc::SOCKET; #[cfg(windows)] pub type BufLen = i32; #[cfg(not(windows))] pub type CSocket = libc::c_int; #[cfg(not(windows))] pub type BufLen = u64; // Any file descriptor on unix, only sockets on Windows. pub struct FileDesc { pub fd: CSocket, } impl Drop for FileDesc { fn drop(&mut self)
} 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_len < 0 { Err(io::Error::last_os_error()) } else { Ok(send_len as usize) } } pub fn recv_from(socket: CSocket, buffer: &mut [u8], caddr: *mut libc::sockaddr_storage) -> io::Result<usize> { let mut caddrlen = mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t; let len = retry(&mut || unsafe { libc::recvfrom(socket, buffer.as_ptr() as *mut libc::c_void, buffer.len() as BufLen, 0, caddr as *mut libc::sockaddr, &mut caddrlen) }); if len < 0 { Err(io::Error::last_os_error()) } else { Ok(len as usize) } }
{ unsafe { close(self.fd); } }
identifier_body
mod.rs
// Copyright (c) 2014 Robert Clipsham <[email protected]> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate libc; use std::io; use std::mem; pub use self::native::{close, retry, addr_to_sockaddr, sockaddr_to_addr}; mod native; #[cfg(windows)] pub type CSocket = libc::SOCKET; #[cfg(windows)] pub type BufLen = i32; #[cfg(not(windows))] pub type CSocket = libc::c_int; #[cfg(not(windows))] pub type BufLen = u64;
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.as_ptr() as *const libc::c_void, buffer.len() as BufLen, 0, dst, slen) }); if send_len < 0 { Err(io::Error::last_os_error()) } else { Ok(send_len as usize) } } pub fn recv_from(socket: CSocket, buffer: &mut [u8], caddr: *mut libc::sockaddr_storage) -> io::Result<usize> { let mut caddrlen = mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t; let len = retry(&mut || unsafe { libc::recvfrom(socket, buffer.as_ptr() as *mut libc::c_void, buffer.len() as BufLen, 0, caddr as *mut libc::sockaddr, &mut caddrlen) }); if len < 0 { Err(io::Error::last_os_error()) } else { Ok(len as usize) } }
// 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 <[email protected]> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate libc; use std::io; use std::mem; pub use self::native::{close, retry, addr_to_sockaddr, sockaddr_to_addr}; mod native; #[cfg(windows)] pub type CSocket = libc::SOCKET; #[cfg(windows)] pub type BufLen = i32; #[cfg(not(windows))] pub type CSocket = libc::c_int; #[cfg(not(windows))] pub type BufLen = u64; // Any file descriptor on unix, only sockets on Windows. pub struct FileDesc { pub fd: CSocket, } 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.as_ptr() as *const libc::c_void, buffer.len() as BufLen, 0, dst, slen) }); if send_len < 0 { Err(io::Error::last_os_error()) } else { Ok(send_len as usize) } } pub fn recv_from(socket: CSocket, buffer: &mut [u8], caddr: *mut libc::sockaddr_storage) -> io::Result<usize> { let mut caddrlen = mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t; let len = retry(&mut || unsafe { libc::recvfrom(socket, buffer.as_ptr() as *mut libc::c_void, buffer.len() as BufLen, 0, caddr as *mut libc::sockaddr, &mut caddrlen) }); if len < 0
else { Ok(len as usize) } }
{ Err(io::Error::last_os_error()) }
conditional_block
mod.rs
// Copyright (c) 2014 Robert Clipsham <[email protected]> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate libc; use std::io; use std::mem; pub use self::native::{close, retry, addr_to_sockaddr, sockaddr_to_addr}; mod native; #[cfg(windows)] pub type CSocket = libc::SOCKET; #[cfg(windows)] pub type BufLen = i32; #[cfg(not(windows))] pub type CSocket = libc::c_int; #[cfg(not(windows))] pub type BufLen = u64; // Any file descriptor on unix, only sockets on Windows. pub struct FileDesc { pub fd: CSocket, } impl Drop for FileDesc { fn drop(&mut self) { unsafe { close(self.fd); } } } pub fn
(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 { Err(io::Error::last_os_error()) } else { Ok(send_len as usize) } } pub fn recv_from(socket: CSocket, buffer: &mut [u8], caddr: *mut libc::sockaddr_storage) -> io::Result<usize> { let mut caddrlen = mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t; let len = retry(&mut || unsafe { libc::recvfrom(socket, buffer.as_ptr() as *mut libc::c_void, buffer.len() as BufLen, 0, caddr as *mut libc::sockaddr, &mut caddrlen) }); if len < 0 { Err(io::Error::last_os_error()) } else { Ok(len as usize) } }
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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
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_empty()); }
// 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:Ensure that the child thread runs by panicking // ignore-emscripten Needs threads. use std::thread; fn
() { // 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