<commit_before>use std;

use rustc_serialize::{Decoder,Decodable};

use types::{BasicValue,Value};

#[derive(Debug)]
pub enum DecodeError {
    BadSignature,
    NotSupported,
    IntTooNarrow
}

pub struct DBusDecoder {
    value: Value,
    map_val: Option<Value>
}

impl DBusDecoder {
    fn get_unsigned_int (v: &BasicValue) -> Result<u64,DecodeError> {
        let val = match v {
            &BasicValue::Byte(x) => x as u64,
            &BasicValue::Uint16(x) => x as u64,
            &BasicValue::Uint32(x) => x as u64,
            &BasicValue::Uint64(x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
	Ok(val)
    }

    fn get_signed_int (v: &BasicValue) -> Result<i64,DecodeError> {
        let val = match v {
            &BasicValue::Int16(x) => x as i64,
            &BasicValue::Int32(x) => x as i64,
            &BasicValue::Int64(x) => x as i64,
            _ => return Err(DecodeError::BadSignature)
        };
	Ok(val)
    }

    fn read_unsigned_int (v: &Value, max: usize) -> Result<u64,DecodeError> {
        let basic_val = match v {
            &Value::BasicValue(ref x) => x,
            _ => return Err(DecodeError::BadSignature)
        };

        // Make sure the value will fit
	let x = try!(DBusDecoder::get_unsigned_int(basic_val));
	if x > (max as u64) {
            return Err(DecodeError::IntTooNarrow);
	}
        Ok(x)
    }

    fn read_signed_int (v: &Value, max: isize, min: isize) -> Result<i64,DecodeError> {
        let basic_val = match v {
            &Value::BasicValue(ref x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
	let x = try!(DBusDecoder::get_signed_int(basic_val));

        // Make sure the value will fit
	if x > (max as i64) {
            return Err(DecodeError::IntTooNarrow);
	}
	if x < (min as i64) {
            return Err(DecodeError::IntTooNarrow);
	}
        Ok(x)
    }

    pub fn new (v: Value) -> DBusDecoder {
        DBusDecoder{
            value: v,
            map_val: None
        }
    }

    pub fn decode<T: Decodable>(v: Value) -> Result<T,DecodeError> {
        let mut decoder = DBusDecoder::new(v);
        T::decode(&mut decoder)
    }
}

impl Decoder for DBusDecoder {
    type Error = DecodeError;

    fn read_usize(&mut self) -> Result<usize, Self::Error> {
        let basic_val = match &self.value {
            &Value::BasicValue(ref x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
	let x = try!(DBusDecoder::get_unsigned_int(basic_val));
        Ok(x as usize)
    }
    fn read_u64(&mut self) -> Result<u64, Self::Error> {
        let val = try!(self.read_usize());
        Ok(val as u64)
    }
    fn read_u32(&mut self) -> Result<u32, Self::Error> {
        Ok(try!(DBusDecoder::read_unsigned_int(&self.value, std::u32::MAX as usize)) as u32)
    }
    fn read_u16(&mut self) -> Result<u16, Self::Error> {
        Ok(try!(DBusDecoder::read_unsigned_int(&self.value, std::u16::MAX as usize)) as u16)
    }
    fn read_u8(&mut self) -> Result<u8, Self::Error> {
        Ok(try!(DBusDecoder::read_unsigned_int(&self.value, std::u8::MAX as usize)) as u8)
    }

    fn read_isize(&mut self) -> Result<isize, Self::Error> {
        let basic_val = match &self.value {
            &Value::BasicValue(ref x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
	let x = try!(DBusDecoder::get_signed_int(basic_val));
        Ok(x as isize)
    }
    fn read_i64(&mut self) -> Result<i64, Self::Error> {
        let val = try!(self.read_isize());
        Ok(val as i64)
    }
    fn read_i32(&mut self) -> Result<i32, Self::Error> {
        Ok(try!(DBusDecoder::read_signed_int(&self.value, std::i32::MAX as isize, std::i32::MIN as isize)) as i32)
    }
    fn read_i16(&mut self) -> Result<i16, Self::Error> {
        Ok(try!(DBusDecoder::read_signed_int(&self.value, std::i16::MAX as isize, std::i16::MIN as isize)) as i16)
    }
    fn read_i8(&mut self) -> Result<i8, Self::Error> {
        Ok(try!(DBusDecoder::read_signed_int(&self.value, std::i8::MAX as isize, std::i8::MIN as isize)) as i8)
    }
    fn read_bool(&mut self) -> Result<bool, Self::Error> {
        let basic_val = match &self.value {
            &Value::BasicValue(ref x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
        let x = match basic_val {
            &BasicValue::Boolean(x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
        Ok(x)
    }
    fn read_f64(&mut self) -> Result<f64, Self::Error> {
        match &self.value {
            &Value::Double(x) => Ok(x),
            _ => return Err(DecodeError::BadSignature)
        }
    }
    fn read_char(&mut self) -> Result<char, Self::Error> {
        let val = try!(self.read_u8());
        Ok(val as char)
    }
    fn read_str(&mut self) -> Result<String, Self::Error> {
        let basic_val = match &self.value {
            &Value::BasicValue(ref x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
        let x = match basic_val {
            &BasicValue::String(ref x) => x.to_string(),
            _ => return Err(DecodeError::BadSignature)
        };
        Ok(x)
    }

    fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error> {
        let len = match self.value {
            Value::Array(ref x) => x.len(),
            _ => return Err(DecodeError::BadSignature)
        };
        f(self, len)
    }
    fn read_seq_elt<T, F>(&mut self, idx: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        let val = match self.value {
            Value::Array(ref mut x) => {
                x.push(Value::BasicValue(BasicValue::Byte(0)));
                x.swap_remove(idx)
            },
            _ => return Err(DecodeError::BadSignature)
        };
        let mut subdecoder = DBusDecoder::new(val);
        f(&mut subdecoder)
    }

    fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error> {
        let len = match self.value {
            Value::Dictionary(ref x) => x.keys().len(),
            _ => return Err(DecodeError::BadSignature)
        };
        f(self, len)
    }
    fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        let dict = match self.value {
            Value::Dictionary(ref mut x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
        let key = {
            dict.keys().next().unwrap().clone()
        };
        self.map_val = Some(dict.remove(&key).unwrap());

        let mut subdecoder = DBusDecoder::new(Value::BasicValue(key));
        f(&mut subdecoder)
    }
    fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        let val = self.map_val.take().unwrap();
        let mut subdecoder = DBusDecoder::new(val);
        f(&mut subdecoder)
    }

    fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        match self.value {
            Value::Struct(_) => (),
            _ => return Err(DecodeError::BadSignature)
        };
        f(self)
    }
    fn read_struct_field<T, F>(&mut self, _f_name: &str, f_idx: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        let val = match self.value {
            Value::Struct(ref mut x) => {
                x.objects.push(Value::BasicValue(BasicValue::Byte(0)));
                x.objects.swap_remove(f_idx)
            },
            _ => return Err(DecodeError::BadSignature)
        };
        let mut subdecoder = DBusDecoder::new(val);
        f(&mut subdecoder)
    }

    fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Self::Error> where F: FnMut(&mut Self, usize) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Self::Error> where F: FnMut(&mut Self, usize) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_option<T, F>(&mut self, _f: F) -> Result<T, Self::Error> where F: FnMut(&mut Self, bool) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_nil(&mut self) -> Result<(), Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_f32(&mut self) -> Result<f32, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn error(&mut self, _err: &str) -> Self::Error {
        DecodeError::NotSupported
    }
}

#[test]
fn test_array () {
    let vec = vec![
        Value::BasicValue(BasicValue::Uint32(1)),
        Value::BasicValue(BasicValue::Uint32(2)),
        Value::BasicValue(BasicValue::Uint32(3)),
    ];
    let val = Value::Array(vec);
    let arr : Vec<u32> = DBusDecoder::decode(val).ok().unwrap();
    assert_eq!(vec![1,2,3], arr);
}
<commit_msg>decoder.rs: unit tests<commit_after>use std;

use rustc_serialize::{Decoder,Decodable};

use types::{BasicValue,Value};

#[derive(Debug,PartialEq)]
pub enum DecodeError {
    BadSignature,
    NotSupported,
    IntTooNarrow
}

pub struct DBusDecoder {
    value: Value,
    map_val: Option<Value>
}

impl DBusDecoder {
    fn get_unsigned_int (v: &BasicValue) -> Result<u64,DecodeError> {
        let val = match v {
            &BasicValue::Byte(x) => x as u64,
            &BasicValue::Uint16(x) => x as u64,
            &BasicValue::Uint32(x) => x as u64,
            &BasicValue::Uint64(x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
	Ok(val)
    }

    fn get_signed_int (v: &BasicValue) -> Result<i64,DecodeError> {
        let val = match v {
            &BasicValue::Int16(x) => x as i64,
            &BasicValue::Int32(x) => x as i64,
            &BasicValue::Int64(x) => x as i64,
            _ => return Err(DecodeError::BadSignature)
        };
	Ok(val)
    }

    fn read_unsigned_int (v: &Value, max: usize) -> Result<u64,DecodeError> {
        let basic_val = match v {
            &Value::BasicValue(ref x) => x,
            _ => return Err(DecodeError::BadSignature)
        };

        // Make sure the value will fit
	let x = try!(DBusDecoder::get_unsigned_int(basic_val));
	if x > (max as u64) {
            return Err(DecodeError::IntTooNarrow);
	}
        Ok(x)
    }

    fn read_signed_int (v: &Value, max: isize, min: isize) -> Result<i64,DecodeError> {
        let basic_val = match v {
            &Value::BasicValue(ref x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
	let x = try!(DBusDecoder::get_signed_int(basic_val));

        // Make sure the value will fit
	if x > (max as i64) {
            return Err(DecodeError::IntTooNarrow);
	}
	if x < (min as i64) {
            return Err(DecodeError::IntTooNarrow);
	}
        Ok(x)
    }

    pub fn new (v: Value) -> DBusDecoder {
        DBusDecoder{
            value: v,
            map_val: None
        }
    }

    pub fn decode<T: Decodable>(v: Value) -> Result<T,DecodeError> {
        let mut decoder = DBusDecoder::new(v);
        T::decode(&mut decoder)
    }
}

impl Decoder for DBusDecoder {
    type Error = DecodeError;

    fn read_usize(&mut self) -> Result<usize, Self::Error> {
        let basic_val = match &self.value {
            &Value::BasicValue(ref x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
	let x = try!(DBusDecoder::get_unsigned_int(basic_val));
        Ok(x as usize)
    }
    fn read_u64(&mut self) -> Result<u64, Self::Error> {
        let val = try!(self.read_usize());
        Ok(val as u64)
    }
    fn read_u32(&mut self) -> Result<u32, Self::Error> {
        Ok(try!(DBusDecoder::read_unsigned_int(&self.value, std::u32::MAX as usize)) as u32)
    }
    fn read_u16(&mut self) -> Result<u16, Self::Error> {
        Ok(try!(DBusDecoder::read_unsigned_int(&self.value, std::u16::MAX as usize)) as u16)
    }
    fn read_u8(&mut self) -> Result<u8, Self::Error> {
        Ok(try!(DBusDecoder::read_unsigned_int(&self.value, std::u8::MAX as usize)) as u8)
    }

    fn read_isize(&mut self) -> Result<isize, Self::Error> {
        let basic_val = match &self.value {
            &Value::BasicValue(ref x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
	let x = try!(DBusDecoder::get_signed_int(basic_val));
        Ok(x as isize)
    }
    fn read_i64(&mut self) -> Result<i64, Self::Error> {
        let val = try!(self.read_isize());
        Ok(val as i64)
    }
    fn read_i32(&mut self) -> Result<i32, Self::Error> {
        Ok(try!(DBusDecoder::read_signed_int(&self.value, std::i32::MAX as isize, std::i32::MIN as isize)) as i32)
    }
    fn read_i16(&mut self) -> Result<i16, Self::Error> {
        Ok(try!(DBusDecoder::read_signed_int(&self.value, std::i16::MAX as isize, std::i16::MIN as isize)) as i16)
    }
    fn read_i8(&mut self) -> Result<i8, Self::Error> {
        Ok(try!(DBusDecoder::read_signed_int(&self.value, std::i8::MAX as isize, std::i8::MIN as isize)) as i8)
    }
    fn read_bool(&mut self) -> Result<bool, Self::Error> {
        let basic_val = match &self.value {
            &Value::BasicValue(ref x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
        let x = match basic_val {
            &BasicValue::Boolean(x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
        Ok(x)
    }
    fn read_f64(&mut self) -> Result<f64, Self::Error> {
        match &self.value {
            &Value::Double(x) => Ok(x),
            _ => return Err(DecodeError::BadSignature)
        }
    }
    fn read_char(&mut self) -> Result<char, Self::Error> {
        let val = try!(self.read_u8());
        Ok(val as char)
    }
    fn read_str(&mut self) -> Result<String, Self::Error> {
        let basic_val = match &self.value {
            &Value::BasicValue(ref x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
        let x = match basic_val {
            &BasicValue::String(ref x) => x.to_string(),
            _ => return Err(DecodeError::BadSignature)
        };
        Ok(x)
    }

    fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error> {
        let len = match self.value {
            Value::Array(ref x) => x.len(),
            _ => return Err(DecodeError::BadSignature)
        };
        f(self, len)
    }
    fn read_seq_elt<T, F>(&mut self, idx: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        let val = match self.value {
            Value::Array(ref mut x) => {
                x.push(Value::BasicValue(BasicValue::Byte(0)));
                x.swap_remove(idx)
            },
            _ => return Err(DecodeError::BadSignature)
        };
        let mut subdecoder = DBusDecoder::new(val);
        f(&mut subdecoder)
    }

    fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error> {
        let len = match self.value {
            Value::Dictionary(ref x) => x.keys().len(),
            _ => return Err(DecodeError::BadSignature)
        };
        f(self, len)
    }
    fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        let dict = match self.value {
            Value::Dictionary(ref mut x) => x,
            _ => return Err(DecodeError::BadSignature)
        };
        let key = {
            dict.keys().next().unwrap().clone()
        };
        self.map_val = Some(dict.remove(&key).unwrap());

        let mut subdecoder = DBusDecoder::new(Value::BasicValue(key));
        f(&mut subdecoder)
    }
    fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        let val = self.map_val.take().unwrap();
        let mut subdecoder = DBusDecoder::new(val);
        f(&mut subdecoder)
    }

    fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        match self.value {
            Value::Struct(_) => (),
            _ => return Err(DecodeError::BadSignature)
        };
        f(self)
    }
    fn read_struct_field<T, F>(&mut self, _f_name: &str, f_idx: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        let val = match self.value {
            Value::Struct(ref mut x) => {
                x.objects.push(Value::BasicValue(BasicValue::Byte(0)));
                x.objects.swap_remove(f_idx)
            },
            _ => return Err(DecodeError::BadSignature)
        };
        let mut subdecoder = DBusDecoder::new(val);
        f(&mut subdecoder)
    }

    fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Self::Error> where F: FnMut(&mut Self, usize) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Self::Error> where F: FnMut(&mut Self, usize) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_option<T, F>(&mut self, _f: F) -> Result<T, Self::Error> where F: FnMut(&mut Self, bool) -> Result<T, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_nil(&mut self) -> Result<(), Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn read_f32(&mut self) -> Result<f32, Self::Error> {
        Err(DecodeError::NotSupported)
    }
    fn error(&mut self, _err: &str) -> Self::Error {
        DecodeError::NotSupported
    }
}

#[test]
fn test_array () {
    let vec = vec![
        Value::BasicValue(BasicValue::Uint32(1)),
        Value::BasicValue(BasicValue::Uint32(2)),
        Value::BasicValue(BasicValue::Uint32(3)),
    ];
    let val = Value::Array(vec);
    let arr : Vec<u32> = DBusDecoder::decode(val).ok().unwrap();
    assert_eq!(vec![1,2,3], arr);
}

#[cfg(test)]
mod test {
    use rustc_serialize::{Decoder,Decodable};
    use types::{BasicValue,Value,Struct,Signature};
    use decoder::*;

    #[test]
    fn test_int () {
        let v = Value::BasicValue(BasicValue::Uint32(1024));
        let i : u32 = DBusDecoder::decode(v).ok().unwrap();
        assert_eq!(i, 1024);

        let x = Value::BasicValue(BasicValue::Uint32(1024));
        let err = DBusDecoder::decode::<u8>(x).err().unwrap();
        assert_eq!(err, DecodeError::IntTooNarrow);
    }

    #[test]
    fn test_string () {
        let v = Value::BasicValue(BasicValue::String("foo".to_string()));
        let i : String = DBusDecoder::decode(v).ok().unwrap();
        assert_eq!(i, "foo");
    }

    #[derive(PartialEq,Debug)]
    struct TestStruct {
        foo: u8,
        bar: u32,
        baz: String,
    }

    impl Decodable for TestStruct {
        fn decode<S: Decoder>(s: &mut S) -> Result<Self, S::Error> {
            s.read_struct("TestStruct", 3, |s: &mut S| {
                let foo = try!(s.read_struct_field("foo", 0, |s: &mut S| {
                    s.read_u8()
                }));
                let bar = try!(s.read_struct_field("bar", 1, |s: &mut S| {
                    s.read_u32()
                }));
                let baz = try!(s.read_struct_field("baz", 2, |s: &mut S| {
                    s.read_str()
                }));
                Ok(TestStruct {
                    foo: foo,
                    bar: bar,
                    baz: baz
                })
            })
        }
    }

    #[test]
    fn test_struct () {
        let objects = vec![
            Value::BasicValue(BasicValue::Byte(1)),
            Value::BasicValue(BasicValue::Uint32(10)),
            Value::BasicValue(BasicValue::String("baz".to_string()))
        ];
        let s = Struct {
            objects: objects,
            signature: Signature("(yus)".to_string())
        };
        let v = Value::Struct(s);

        let x : TestStruct = DBusDecoder::decode(v).unwrap();
        assert_eq!(x, TestStruct {
            foo: 1,
            bar: 10,
            baz: "baz".to_string()
        });
    }
}

<|endoftext|>


<commit_before><commit_msg>Added asynchronous decoding<commit_after>use std::io;
use std::io::Read;
use std::default::Default;
use std::io::BufReader;
use std::path::Path;
use std::fs::File;
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::thread;
use self::mad_decoder_mode::* ;

#[link(name = "mad")]
extern {
    fn mad_decoder_init(decoder: &mad_decoder,
                        message: &mad_message,
                        input_callback: extern fn(message: &mut mad_message, stream: isize) -> mad_flow,
                        header_callback: extern fn(),
                        filter_callback: extern fn(),
                        output_callback: extern fn(message: &mut mad_message,
                                                   header: isize,
                                                   pcm: &mad_pcm) -> mad_flow,
                        error_callback: extern fn(),
                        message_callback: extern fn());
    fn mad_decoder_run(input: &mut mad_decoder, mode: mad_decoder_mode) -> i32;
    fn mad_stream_buffer(stream: isize, buf_start: *const u8, buf_length: usize);
}

#[repr(C)]
enum mad_flow {
    mf_continue = 0x0000,	/* continue normally */
    mf_stop     = 0x0010,	/* stop decoding normally */
    mf_break    = 0x0011,	/* stop decoding and signal an error */
    mf_ignore   = 0x0020	/* ignore the current frame */
}

#[repr(C)]
struct mad_pcm {
    sample_rate: u32,
    channels: u16,
    length: u16,
    samples: [[i32; 1152]; 2],
}

#[repr(C)]
struct mad_message<'a> {
    buffer: &'a mut [u8; 4096],
    reader: &'a mut (io::Read + 'a),
    sender: &'a Sender<Frame>,
}

#[repr(C)]
enum mad_decoder_mode {
    MAD_DECODER_MODE_SYNC = 0,
    MAD_DECODER_MODE_ASYNC
}

impl Default for mad_decoder_mode {
    fn default() -> mad_decoder_mode {MAD_DECODER_MODE_SYNC}
}

#[derive(Default)]
#[repr(C)]
struct mad_async_parameters {
    pid: u32,
    ain: isize,
    aout: isize,
}

#[derive(Default)]
#[repr(C)]
struct mad_decoder {
    mode: mad_decoder_mode,
    options: isize,
    async: mad_async_parameters,
    sync: usize,
    cb_data: usize,
    input_func: usize,
    header_func: usize,
    filter_func: usize,
    output_func: usize,
    error_func: usize,
    message_func: usize,
}

extern fn empty_callback() {

}

pub struct Frame {
    sample_rate: u32,
    channels: u16,
    length: u16,
    samples: [[i32; 1152]; 2],
}

pub fn decode(path_str: &'static str) -> Receiver<Frame> {
    let (tx, rx): (Sender<Frame>, Receiver<Frame>) = mpsc::channel();
    thread::spawn(move || {
        let path = Path::new(path_str);
        let f = File::open(&path).unwrap();
        let mut reader = BufReader::new(f);
        let mut input_buffer = [0u8; 4096];
        reader.read(&mut input_buffer);
        let message = &mut mad_message {
            buffer: &mut input_buffer,
            reader: &mut reader,
            sender: &tx,
        };
        let mut decoder: mad_decoder = Default::default();
        let mut decoding_result: i32 = 42;

        extern fn input_callback (msg: &mut mad_message, stream: isize) -> mad_flow {
            let read_result = msg.reader.read(msg.buffer).unwrap();
            unsafe {
                mad_stream_buffer(stream, msg.buffer.as_ptr(), msg.buffer.len());
            }

            if read_result == 0 {
                return mad_flow::mf_stop;
            }

            mad_flow::mf_continue
        }

        extern fn output_callback(msg: &mut mad_message,
                                  header: isize,
                                  pcm: &mad_pcm) -> mad_flow
        {
            msg.sender.send(Frame {sample_rate: pcm.sample_rate,
                                   channels: pcm.channels,
                                   length: pcm.length,
                                   samples: pcm.samples});
            mad_flow::mf_continue
        }

        unsafe {
            mad_decoder_init(&mut decoder,
                             message,
                             input_callback,
                             empty_callback,
                             empty_callback,
                             output_callback,
                             empty_callback,
                             empty_callback);
            decoding_result = mad_decoder_run(&mut decoder,
                                              mad_decoder_mode::MAD_DECODER_MODE_SYNC);
        }
    });
    rx
}

#[test]
fn test_open_file() {
    let decoder = self::decode("test_samples/fs-242.mp3");
    for frame in decoder.iter() {
        println!("Got frame.");
    }
    assert!(true);
}
<|endoftext|>


<commit_before><commit_msg>set up end2end tests for CosmosDB<commit_after>use azure_sdk_core::errors::AzureError;
use azure_sdk_cosmos::{AuthorizationToken, Client, ClientBuilder, CosmosUriBuilder, TokenType};
use tokio_core::reactor::Core;

pub fn initialize() -> Result<(Client<impl CosmosUriBuilder>, Core), AzureError> {
    let account = std::env::var("COSMOS_ACCOUNT").expect("Set env variable COSMOS_ACCOUNT first!");
    let key = std::env::var("COSMOS_KEY").expect("Set env variable COSMOS_KEY first!");

    let authorization_token = AuthorizationToken::new(account, TokenType::Master, &key)?;
    let client = ClientBuilder::new(authorization_token)?;
    let core = Core::new()?;

    Ok((client, core))
}
<|endoftext|>


<commit_before><commit_msg>Simplify condition with iterator functions<commit_after><|endoftext|>


<commit_before><commit_msg>Remove '-' from Rustual Boy in help text<commit_after><|endoftext|>


<commit_before><commit_msg>Add an example into a specific directory<commit_after><|endoftext|>


<commit_before><commit_msg>update page number logic<commit_after><|endoftext|>


<commit_before><commit_msg>add cgroup_reader<commit_after>use std::fs::File;

pub mod cgroup_reader {
    trait CGroup_Reader {
        fn get_name() -> String;
        fn read(stat: String) -> String;
    }

    fn which_cgroup(pid: u32) -> (Fn(String) -> String) {
        let path = format!("/proc/{}/cgroup");
        let mut cgroup_f = try!(File::open(path));
        let mut buffer = String::new();
        try!(cgroup_f.read_to_string(&mut buffer));
        |resource| {
            let r_cnt = 0;
            let begin = -1;
            let end = -1;
            let colon_cnt = 0;
            for (c, i) in buffer {
                if c == ':' {
                    colon_cnt++;
                } else if begin > 0 && end < 0 && c == '\n'{
                    end = i;
                } else if colon_cnt == 1 {
                    if resource[r_cnt] == c {
                        r_cnt++;
                    } else if r_cnt > 0 && r_cnt + 1 < resource.capacity() {
                        continue;
                    }
                } else {
                    if begin < 0 {
                        begin = i + 1;
                    }
                }
            }
        }
    }

    fn read_cgroup(resource: String, name: String, stat: String) -> String {
        let path = format!("/sys/fs/cgroup/{}/{}/{}", resource, name, stat);
        let mut stat_f = try!(File::open(path))
        let mut buffer = String::new();
        try!(stat_f.read_to_string(&mut buffer));
        return buffer;
    }

    struct CPU_Reader {
        name: String,
        pid: u32,
    }

    impl CGroup_Reader for CPU_Reader {
        fn read(stat: String) -> String {
            return read_cgroup("cpu", self.name, stat);
        }
    }

    struct Mem_Reader {
        name: String,
        pid: u32,
    }

    impl CGroup_Reader for Mem_Reader {
        fn read(stat: String) -> String {
            return read_cgroup("memory", self.name, stat);
        }
    }

    struct BLKIO_Reader {
        name: String,
        pid: u32,
    }

    impl CGroup_Reader for BLKIO_Reader {
        fn read(stat: String) -> String {
            return read_cgroup("blkio", self.name, stat);
        }
    }

    struct Device_Reader {
        name: String,
        pid: u32,
    }

    impl CGroup_Reader for Device_Reader {
        fn read(stat: String) -> String {
            return read_cgroup("devices", self.name, stat);
        }
    }

    struct Net_Reader {
        name: String,
        pid: u32,
    }

    impl CGroup_Reader for Net_Reader {
        fn read(stat: String) -> String {
            return read_cgroup("net_cls", self.name, stat);
        }
    }

    pub struct Reader {
        cpu_stat: CPU_Reader,
    }

    pub fn new(pid: u32) -> Reader {
        let name = which_cgroup(pid);
        return Reader{
            cpu: CPU_Reader{
                name: name("cpu"),
                pid: pid,
            },
            mem: Mem_Reader{
                name: name("memory"),
                pid: pid,
            },
            blkio: BLKIO_Reader{
                name: name("blkio"),
                pid: pid,
            },
            devices: Device_Reader{
                name: name("devices"),
                pid: pid,
            },
            net: Net_Reader{
                name: name("net_cls"),
                pid: pid,
            },
        };
    }
}
<|endoftext|>


<commit_before><commit_msg>Add repository URL<commit_after><|endoftext|>


<commit_before><commit_msg>Do not allow linking with entry itself<commit_after><|endoftext|>


<commit_before><commit_msg>librustc: De-`@mut` `ImportResolution::type_id`<commit_after><|endoftext|>


<commit_before>// 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.

//! Runtime services
//!
//! The `rt` module provides a narrow set of runtime services,
//! including the global heap (exported in `heap`) and unwinding and
//! backtrace support. The APIs in this module are highly unstable,
//! and should be considered as private implementation details for the
//! time being.

#![unstable(feature = "rt",
            reason = "this public module should not exist and is highly likely \
                      to disappear",
            issue = "0")]
#![allow(missing_docs)]

use prelude::v1::*;
use sync::Once;
use sys;
use thread;

// Reexport some of our utilities which are expected by other crates.
pub use self::util::min_stack;
pub use self::unwind::{begin_unwind, begin_unwind_fmt};

// Reexport some functionality from liballoc.
pub use alloc::heap;

// Simple backtrace functionality (to print on panic)
pub mod backtrace;

// Internals
#[macro_use]
mod macros;

// These should be refactored/moved/made private over time
pub mod util;
pub mod unwind;
pub mod args;

mod at_exit_imp;
mod libunwind;

mod dwarf;

/// The default error code of the rust runtime if the main thread panics instead
/// of exiting cleanly.
pub const DEFAULT_ERROR_CODE: isize = 101;

#[cfg(not(test))]
#[lang = "start"]
fn lang_start(main: *const u8, argc: isize, argv: *const *const u8) -> isize {
    use prelude::v1::*;

    use mem;
    use rt;
    use sys_common::thread_info::{self, NewThread};
    use thread::Thread;

    let failed = unsafe {
        let main_guard = sys::thread::guard::init();
        sys::stack_overflow::init();

        // Next, set up the current Thread with the guard information we just
        // created. Note that this isn't necessary in general for new threads,
        // but we just do this to name the main thread and to give it correct
        // info about the stack bounds.
        let thread: Thread = NewThread::new(Some("<main>".to_string()));
        thread_info::set(main_guard, thread);

        // By default, some platforms will send a *signal* when a EPIPE error
        // would otherwise be delivered. This runtime doesn't install a SIGPIPE
        // handler, causing it to kill the program, which isn't exactly what we
        // want!
        //
        // Hence, we set SIGPIPE to ignore when the program starts up in order
        // to prevent this problem.
        #[cfg(windows)] fn ignore_sigpipe() {}
        #[cfg(unix)] fn ignore_sigpipe() {
            use libc;
            use libc::funcs::posix01::signal::signal;
            unsafe {
                assert!(signal(libc::SIGPIPE, libc::SIG_IGN) != !0);
            }
        }
        ignore_sigpipe();

        // Store our args if necessary in a squirreled away location
        args::init(argc, argv);

        // And finally, let's run some code!
        let res = thread::catch_panic(mem::transmute::<_, fn()>(main));
        cleanup();
        res.is_err()
    };

    // If the exit code wasn't set, then the try block must have panicked.
    if failed {
        rt::DEFAULT_ERROR_CODE
    } else {
        0
    }
}

/// Enqueues a procedure to run when the main thread exits.
///
/// Currently these closures are only run once the main *Rust* thread exits.
/// Once the `at_exit` handlers begin running, more may be enqueued, but not
/// infinitely so. Eventually a handler registration will be forced to fail.
///
/// Returns `Ok` if the handler was successfully registered, meaning that the
/// closure will be run once the main thread exits. Returns `Err` to indicate
/// that the closure could not be registered, meaning that it is not scheduled
/// to be rune.
pub fn at_exit<F: FnOnce() + Send + 'static>(f: F) -> Result<(), ()> {
    if at_exit_imp::push(Box::new(f)) {Ok(())} else {Err(())}
}

/// One-time runtime cleanup.
pub fn cleanup() {
    static CLEANUP: Once = Once::new();
    CLEANUP.call_once(|| unsafe {
        args::cleanup();
        sys::stack_overflow::cleanup();
        at_exit_imp::cleanup();
    });
}
<commit_msg>Auto merge of #28278 - pfpacket:typo, r=steveklabnik<commit_after>// 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.

//! Runtime services
//!
//! The `rt` module provides a narrow set of runtime services,
//! including the global heap (exported in `heap`) and unwinding and
//! backtrace support. The APIs in this module are highly unstable,
//! and should be considered as private implementation details for the
//! time being.

#![unstable(feature = "rt",
            reason = "this public module should not exist and is highly likely \
                      to disappear",
            issue = "0")]
#![allow(missing_docs)]

use prelude::v1::*;
use sync::Once;
use sys;
use thread;

// Reexport some of our utilities which are expected by other crates.
pub use self::util::min_stack;
pub use self::unwind::{begin_unwind, begin_unwind_fmt};

// Reexport some functionality from liballoc.
pub use alloc::heap;

// Simple backtrace functionality (to print on panic)
pub mod backtrace;

// Internals
#[macro_use]
mod macros;

// These should be refactored/moved/made private over time
pub mod util;
pub mod unwind;
pub mod args;

mod at_exit_imp;
mod libunwind;

mod dwarf;

/// The default error code of the rust runtime if the main thread panics instead
/// of exiting cleanly.
pub const DEFAULT_ERROR_CODE: isize = 101;

#[cfg(not(test))]
#[lang = "start"]
fn lang_start(main: *const u8, argc: isize, argv: *const *const u8) -> isize {
    use prelude::v1::*;

    use mem;
    use rt;
    use sys_common::thread_info::{self, NewThread};
    use thread::Thread;

    let failed = unsafe {
        let main_guard = sys::thread::guard::init();
        sys::stack_overflow::init();

        // Next, set up the current Thread with the guard information we just
        // created. Note that this isn't necessary in general for new threads,
        // but we just do this to name the main thread and to give it correct
        // info about the stack bounds.
        let thread: Thread = NewThread::new(Some("<main>".to_string()));
        thread_info::set(main_guard, thread);

        // By default, some platforms will send a *signal* when a EPIPE error
        // would otherwise be delivered. This runtime doesn't install a SIGPIPE
        // handler, causing it to kill the program, which isn't exactly what we
        // want!
        //
        // Hence, we set SIGPIPE to ignore when the program starts up in order
        // to prevent this problem.
        #[cfg(windows)] fn ignore_sigpipe() {}
        #[cfg(unix)] fn ignore_sigpipe() {
            use libc;
            use libc::funcs::posix01::signal::signal;
            unsafe {
                assert!(signal(libc::SIGPIPE, libc::SIG_IGN) != !0);
            }
        }
        ignore_sigpipe();

        // Store our args if necessary in a squirreled away location
        args::init(argc, argv);

        // And finally, let's run some code!
        let res = thread::catch_panic(mem::transmute::<_, fn()>(main));
        cleanup();
        res.is_err()
    };

    // If the exit code wasn't set, then the try block must have panicked.
    if failed {
        rt::DEFAULT_ERROR_CODE
    } else {
        0
    }
}

/// Enqueues a procedure to run when the main thread exits.
///
/// Currently these closures are only run once the main *Rust* thread exits.
/// Once the `at_exit` handlers begin running, more may be enqueued, but not
/// infinitely so. Eventually a handler registration will be forced to fail.
///
/// Returns `Ok` if the handler was successfully registered, meaning that the
/// closure will be run once the main thread exits. Returns `Err` to indicate
/// that the closure could not be registered, meaning that it is not scheduled
/// to be run.
pub fn at_exit<F: FnOnce() + Send + 'static>(f: F) -> Result<(), ()> {
    if at_exit_imp::push(Box::new(f)) {Ok(())} else {Err(())}
}

/// One-time runtime cleanup.
pub fn cleanup() {
    static CLEANUP: Once = Once::new();
    CLEANUP.call_once(|| unsafe {
        args::cleanup();
        sys::stack_overflow::cleanup();
        at_exit_imp::cleanup();
    });
}
<|endoftext|>


<commit_before><commit_msg>fix: fixes nightly build with new lints<commit_after><|endoftext|>


<commit_before><commit_msg>Renderer now clears<commit_after><|endoftext|>


<commit_before><commit_msg>Add MIR test<commit_after>// Make sure redundant testing paths in `match` expressions are sorted out.

#![feature(exclusive_range_pattern)]

fn main() {
    let x = 3;
    let b = true;

    // When `(0..=10).contains(x) && !b`, we should jump to the last arm
    // without testing two other candidates.
    match x {
        0..10 if b => 0,
        10..=20 => 1,
        -1 => 2,
        _ => 3,
    };
}

// END RUST SOURCE
// START rustc.main.SimplifyCfg-initial.after.mir
//    bb0: {
//        ...
//        _4 = Le(const 0i32, _1);
//        switchInt(move _4) -> [false: bb10, otherwise: bb11];
//    }
//    bb1: {
//        _3 = const 0i32;
//        goto -> bb16;
//    }
//    bb2: {
//        _3 = const 1i32;
//        goto -> bb16;
//    }
//    bb3: {
//        _3 = const 2i32;
//        goto -> bb16;
//    }
//    bb4: {
//        _3 = const 3i32;
//        goto -> bb16;
//    }
//    bb5: {
//        falseEdges -> [real: bb12, imaginary: bb6];
//    }
//    bb6: {
//        falseEdges -> [real: bb2, imaginary: bb7];
//    }
//    bb7: {
//        falseEdges -> [real: bb3, imaginary: bb8];
//    }
//    bb8: {
//        falseEdges -> [real: bb4, imaginary: bb9];
//    }
//    bb9: {
//        unreachable;
//    }
//    bb10: {
//        _7 = Le(const 10i32, _1);
//        switchInt(move _7) -> [false: bb14, otherwise: bb15];
//    }
//    bb11: {
//        _5 = Lt(_1, const 10i32);
//        switchInt(move _5) -> [false: bb10, otherwise: bb5];
//    }
//    bb12: {
//        StorageLive(_6);
//        _6 = _2;
//        switchInt(move _6) -> [false: bb13, otherwise: bb1];
//    }
//    bb13: {
//        falseEdges -> [real: bb8, imaginary: bb6];
//    }
//    bb14: {
//        switchInt(_1) -> [-1i32: bb7, otherwise: bb8];
//    }
//    bb15: {
//        _8 = Le(_1, const 20i32);
//        switchInt(move _8) -> [false: bb14, otherwise: bb6];
//    }
//    bb16: {
//        StorageDead(_6);
//        ...
//        return;
//    }
// END rustc.main.SimplifyCfg-initial.after.mir<|endoftext|>


<commit_before><commit_msg>fibonacci sequence implemented using rust<commit_after><|endoftext|>


<commit_before>// 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 std::collections::BTreeMap;
use std::path::Path;
use std::path::PathBuf;
use std::vec::Vec;
use std::fs::OpenOptions;

use time;
use uuid::Uuid;
use serde_json;

use engine::EngineError;
use engine::EngineResult;
use engine::ErrorEnum;
use engine::Pool;
use engine::RenameAction;
use engine::engine::Redundancy;

use super::super::super::types::Bytes;

use super::serde_structs::StratSave;
use super::blockdev::{BlockDev, initialize, resolve_devices};
use super::filesystem::StratFilesystem;
use super::metadata::MIN_MDA_SECTORS;

#[derive(Debug)]
pub struct StratPool {
    pub name: String,
    pub pool_uuid: Uuid,
    pub cache_devs: BTreeMap<PathBuf, BlockDev>,
    pub block_devs: BTreeMap<PathBuf, BlockDev>,
    pub filesystems: BTreeMap<String, StratFilesystem>,
    redundancy: Redundancy,
}

impl StratPool {
    pub fn new(name: &str,
               paths: &[&Path],
               redundancy: Redundancy,
               force: bool)
               -> EngineResult<StratPool> {
        let devices = try!(resolve_devices(paths));
        let pool_uuid = Uuid::new_v4();
        let bds = try!(initialize(&pool_uuid, devices, MIN_MDA_SECTORS, force));

        let mut pool = StratPool {
            name: name.to_owned(),
            pool_uuid: pool_uuid,
            cache_devs: BTreeMap::new(),
            block_devs: bds,
            filesystems: BTreeMap::new(),
            redundancy: redundancy,
        };

        try!(pool.write_metadata());

        Ok(pool)
    }

    /// Read the latest data across all blockdevs
    pub fn read_metadata(&self) -> Option<Vec<u8>> {

        let mut bds: Vec<&BlockDev> = self.block_devs
            .iter()
            .map(|(_, bd)| bd)
            .filter(|bd| bd.bda.last_update_time().is_some())
            .collect();

        bds.sort_by_key(|k| k.bda.last_update_time().unwrap());

        // Only try to read blockdevs with the latest metadata
        let last_update_time = match bds.last() {
            Some(bd) => bd.bda.last_update_time().unwrap(),
            None => return None,
        };

        for bd in bds.iter()
            .rev()
            .take_while(|bd| bd.bda.last_update_time().unwrap() == last_update_time) {
            let mut f = match OpenOptions::new()
                .read(true)
                .open(&bd.devnode) {
                Ok(f) => f,
                Err(_) => continue,
            };
            match bd.bda.load_state(&mut f) {
                Ok(Some(data)) => return Some(data),
                _ => continue,
            }
        }
        None
    }

    /// Write the given data to all blockdevs
    pub fn write_metadata(&mut self) -> EngineResult<()> {

        let data = try!(serde_json::to_string(&self.to_save()));

        // TODO: Cap # of blockdevs written to, as described in SWDD
        // TODO: Check current time against global last updated, and use
        // alternate time value if earlier, as described in SWDD

        let time = time::now().to_timespec();

        for (_, bd) in &mut self.block_devs {
            bd.save_state(&time, data.as_bytes()).unwrap(); // ignoring failure
        }

        Ok(())
    }

    pub fn to_save(&self) -> StratSave {
        StratSave {
            name: self.name.clone(),
            id: self.pool_uuid.simple().to_string(),
            block_devs: self.block_devs
                .iter()
                .map(|(_, bd)| (bd.bda.header.dev_uuid.simple().to_string(), bd.to_save()))
                .collect(),
        }
    }
}

impl Pool for StratPool {
    fn create_filesystems<'a, 'b, 'c>(&'a mut self,
                                      _specs: &[(&'b str, &'c str, Option<Bytes>)])
                                      -> EngineResult<Vec<&'b str>> {
        Ok(vec![])
    }

    fn create_snapshot<'a, 'b, 'c>(&'a mut self,
                                   _snapshot_name: &'b str,
                                   _source: &'c str)
                                   -> EngineResult<&'b str> {
        unimplemented!()
    }

    fn add_blockdevs(&mut self, paths: &[&Path], force: bool) -> EngineResult<Vec<PathBuf>> {
        let devices = try!(resolve_devices(paths));
        let mut bds = try!(initialize(&self.pool_uuid, devices, MIN_MDA_SECTORS, force));
        let bdev_paths = bds.iter().map(|p| p.1.devnode.clone()).collect();
        self.block_devs.append(&mut bds);
        try!(self.write_metadata());
        Ok(bdev_paths)
    }

    fn add_cachedevs(&mut self, paths: &[&Path], force: bool) -> EngineResult<Vec<PathBuf>> {
        let devices = try!(resolve_devices(paths));
        let mut bds = try!(initialize(&self.pool_uuid, devices, MIN_MDA_SECTORS, force));
        let bdev_paths = bds.iter().map(|p| p.1.devnode.clone()).collect();
        self.cache_devs.append(&mut bds);
        Ok(bdev_paths)
    }

    fn destroy(mut self) -> EngineResult<()> {

        // TODO: first, tear down DM mappings

        for bd in self.block_devs.values_mut() {
            try!(bd.wipe_metadata());
        }

        for bd in self.cache_devs.values_mut() {
            try!(bd.wipe_metadata());
        }

        Ok(())
    }

    fn destroy_filesystems<'a, 'b>(&'a mut self,
                                   fs_names: &[&'b str])
                                   -> EngineResult<Vec<&'b str>> {
        destroy_filesystems!{self; fs_names}
    }

    fn remove_blockdevs(&mut self, _paths: &[&Path]) -> EngineResult<Vec<PathBuf>> {
        unimplemented!()
    }

    fn remove_cachedevs(&mut self, _paths: &[&Path]) -> EngineResult<Vec<PathBuf>> {
        unimplemented!()
    }

    fn rename_filesystem(&mut self, old_name: &str, new_name: &str) -> EngineResult<RenameAction> {
        rename_filesystem!{self; old_name; new_name}
    }
}
<commit_msg>Reorder lines to match other methods<commit_after>// 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 std::collections::BTreeMap;
use std::path::Path;
use std::path::PathBuf;
use std::vec::Vec;
use std::fs::OpenOptions;

use time;
use uuid::Uuid;
use serde_json;

use engine::EngineError;
use engine::EngineResult;
use engine::ErrorEnum;
use engine::Pool;
use engine::RenameAction;
use engine::engine::Redundancy;

use super::super::super::types::Bytes;

use super::serde_structs::StratSave;
use super::blockdev::{BlockDev, initialize, resolve_devices};
use super::filesystem::StratFilesystem;
use super::metadata::MIN_MDA_SECTORS;

#[derive(Debug)]
pub struct StratPool {
    pub name: String,
    pub pool_uuid: Uuid,
    pub cache_devs: BTreeMap<PathBuf, BlockDev>,
    pub block_devs: BTreeMap<PathBuf, BlockDev>,
    pub filesystems: BTreeMap<String, StratFilesystem>,
    redundancy: Redundancy,
}

impl StratPool {
    pub fn new(name: &str,
               paths: &[&Path],
               redundancy: Redundancy,
               force: bool)
               -> EngineResult<StratPool> {
        let pool_uuid = Uuid::new_v4();

        let devices = try!(resolve_devices(paths));
        let bds = try!(initialize(&pool_uuid, devices, MIN_MDA_SECTORS, force));

        let mut pool = StratPool {
            name: name.to_owned(),
            pool_uuid: pool_uuid,
            cache_devs: BTreeMap::new(),
            block_devs: bds,
            filesystems: BTreeMap::new(),
            redundancy: redundancy,
        };

        try!(pool.write_metadata());

        Ok(pool)
    }

    /// Read the latest data across all blockdevs
    pub fn read_metadata(&self) -> Option<Vec<u8>> {

        let mut bds: Vec<&BlockDev> = self.block_devs
            .iter()
            .map(|(_, bd)| bd)
            .filter(|bd| bd.bda.last_update_time().is_some())
            .collect();

        bds.sort_by_key(|k| k.bda.last_update_time().unwrap());

        // Only try to read blockdevs with the latest metadata
        let last_update_time = match bds.last() {
            Some(bd) => bd.bda.last_update_time().unwrap(),
            None => return None,
        };

        for bd in bds.iter()
            .rev()
            .take_while(|bd| bd.bda.last_update_time().unwrap() == last_update_time) {
            let mut f = match OpenOptions::new()
                .read(true)
                .open(&bd.devnode) {
                Ok(f) => f,
                Err(_) => continue,
            };
            match bd.bda.load_state(&mut f) {
                Ok(Some(data)) => return Some(data),
                _ => continue,
            }
        }
        None
    }

    /// Write the given data to all blockdevs
    pub fn write_metadata(&mut self) -> EngineResult<()> {

        let data = try!(serde_json::to_string(&self.to_save()));

        // TODO: Cap # of blockdevs written to, as described in SWDD
        // TODO: Check current time against global last updated, and use
        // alternate time value if earlier, as described in SWDD

        let time = time::now().to_timespec();

        for (_, bd) in &mut self.block_devs {
            bd.save_state(&time, data.as_bytes()).unwrap(); // ignoring failure
        }

        Ok(())
    }

    pub fn to_save(&self) -> StratSave {
        StratSave {
            name: self.name.clone(),
            id: self.pool_uuid.simple().to_string(),
            block_devs: self.block_devs
                .iter()
                .map(|(_, bd)| (bd.bda.header.dev_uuid.simple().to_string(), bd.to_save()))
                .collect(),
        }
    }
}

impl Pool for StratPool {
    fn create_filesystems<'a, 'b, 'c>(&'a mut self,
                                      _specs: &[(&'b str, &'c str, Option<Bytes>)])
                                      -> EngineResult<Vec<&'b str>> {
        Ok(vec![])
    }

    fn create_snapshot<'a, 'b, 'c>(&'a mut self,
                                   _snapshot_name: &'b str,
                                   _source: &'c str)
                                   -> EngineResult<&'b str> {
        unimplemented!()
    }

    fn add_blockdevs(&mut self, paths: &[&Path], force: bool) -> EngineResult<Vec<PathBuf>> {
        let devices = try!(resolve_devices(paths));
        let mut bds = try!(initialize(&self.pool_uuid, devices, MIN_MDA_SECTORS, force));
        let bdev_paths = bds.iter().map(|p| p.1.devnode.clone()).collect();
        self.block_devs.append(&mut bds);
        try!(self.write_metadata());
        Ok(bdev_paths)
    }

    fn add_cachedevs(&mut self, paths: &[&Path], force: bool) -> EngineResult<Vec<PathBuf>> {
        let devices = try!(resolve_devices(paths));
        let mut bds = try!(initialize(&self.pool_uuid, devices, MIN_MDA_SECTORS, force));
        let bdev_paths = bds.iter().map(|p| p.1.devnode.clone()).collect();
        self.cache_devs.append(&mut bds);
        Ok(bdev_paths)
    }

    fn destroy(mut self) -> EngineResult<()> {

        // TODO: first, tear down DM mappings

        for bd in self.block_devs.values_mut() {
            try!(bd.wipe_metadata());
        }

        for bd in self.cache_devs.values_mut() {
            try!(bd.wipe_metadata());
        }

        Ok(())
    }

    fn destroy_filesystems<'a, 'b>(&'a mut self,
                                   fs_names: &[&'b str])
                                   -> EngineResult<Vec<&'b str>> {
        destroy_filesystems!{self; fs_names}
    }

    fn remove_blockdevs(&mut self, _paths: &[&Path]) -> EngineResult<Vec<PathBuf>> {
        unimplemented!()
    }

    fn remove_cachedevs(&mut self, _paths: &[&Path]) -> EngineResult<Vec<PathBuf>> {
        unimplemented!()
    }

    fn rename_filesystem(&mut self, old_name: &str, new_name: &str) -> EngineResult<RenameAction> {
        rename_filesystem!{self; old_name; new_name}
    }
}
<|endoftext|>


<commit_before><commit_msg>docs(scanner): initial commit<commit_after><|endoftext|>


<commit_before><commit_msg>continue keyword in loop<commit_after><|endoftext|>


<commit_before><commit_msg>Added tuples example.<commit_after>// Tuples can be used as function arguments and as return values
fn reverse(pair: (i32, bool)) -> (bool, i32) {
    // `let` can be used to bind the members of a tuple to variables
    let (integer, boolean) = pair;

    (boolean, integer)
}

fn main() {
    // A tuple with a bunch of different types
    let long_tuple = (1u8, 2u16, 3u32, 4u64,
                      -1i8, -2i16, -3i32, -4i64,
                      0.1f32, 0.2f64,
                      'a', true);

    // Values can be extracted from the tuple using tuple indexing
    println!("long tuple first value: {}", long_tuple.0);
    println!("long tuple second value: {}", long_tuple.1);

    // Tuples can be tuple members
    let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);

    // Tuples are printable
    println!("tuple of tuples: {:?}", tuple_of_tuples);

    let pair = (1, true);
    println!("pair is {:?}", pair);

    println!("the reversed pair is {:?}", reverse(pair));

    // To create one element tuples, the comma is required to tell them apart
    // from a literal surrounded by parentheses
    println!("one element tuple: {:?}", (5u32,));
    println!("just an integer: {:?}", (5u32));

    //tuples can be destructured to create bindings
    let tuple = (1, "hello", 4.5, true);

    let (a, b, c, d) = tuple;
    println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);
}
<|endoftext|>


<commit_before><commit_msg>Use resiter::IterInnerOkOrElse instead of libimagerror version<commit_after><|endoftext|>


<commit_before><commit_msg>plus_minus<commit_after>//https://www.hackerrank.com/challenges/plus-minus

use std::io;
use std::io::prelude::*;

fn main() {
    let stdin = io::stdin();

    let count: f64 = stdin.lock().lines() //iterator over lines in stdin
        .next().unwrap().unwrap() //finally it's a string
        .trim().parse().unwrap(); //and then parsing count value...
    let mut count_positive: f64 = 0.0;
    let mut count_negative: f64 = 0.0;
    let mut count_zeros: f64 = 0.0;
    for line in stdin.lock().lines() {
        let line: String = line.unwrap();
        let v: Vec<f64> = line.trim().split(' ').map(|x| x.parse::<f64>().unwrap()).collect();
        for item in v {
            if item > 0.0  {
                count_positive += 1.0;
            } else if item < 0.0  {
                count_negative += 1.0;
            } else {
                count_zeros += 1.0;
            }
        }

    }
    println!("{}", count_positive / count);
    println!("{}", count_negative / count);
    println!("{}", count_zeros / count);
}<|endoftext|>


<commit_before><commit_msg>Factor out APU length and stub the triangle wave<commit_after><|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! Stack-scoped thread-local storage for rayon thread pools.

#![allow(unsafe_code)]
#![deny(missing_docs)]

use rayon;
use std::cell::{Ref, RefCell, RefMut};
use std::ops::DerefMut;

/// A scoped TLS set, that is alive during the `'scope` lifetime.
///
/// We use this on Servo to construct thread-local contexts, but clear them once
/// we're done with restyling.
pub struct ScopedTLS<'scope, T: Send> {
    pool: &'scope rayon::ThreadPool,
    slots: Box<[RefCell<Option<T>>]>,
}

/// The scoped TLS is `Sync` because no more than one worker thread can access a
/// given slot.
unsafe impl<'scope, T: Send> Sync for ScopedTLS<'scope, T> {}

impl<'scope, T: Send> ScopedTLS<'scope, T> {
    /// Create a new scoped TLS that will last as long as this rayon threadpool
    /// reference.
    pub fn new(p: &'scope rayon::ThreadPool) -> Self {
        let count = p.current_num_threads();
        let mut v = Vec::with_capacity(count);
        for _ in 0..count {
            v.push(RefCell::new(None));
        }

        ScopedTLS {
            pool: p,
            slots: v.into_boxed_slice(),
        }
    }

    /// Return an immutable reference to the `Option<T>` that this thread owns.
    pub fn borrow(&self) -> Ref<Option<T>> {
        let idx = self.pool.current_thread_index().unwrap();
        self.slots[idx].borrow()
    }

    /// Return a mutable reference to the `Option<T>` that this thread owns.
    pub fn borrow_mut(&self) -> RefMut<Option<T>> {
        let idx = self.pool.current_thread_index().unwrap();
        self.slots[idx].borrow_mut()
    }

    /// Ensure that the current data this thread owns is initialized, or
    /// initialize it using `f`.  We want ensure() to be fast and inline, and we
    /// want to inline the memmove that initializes the Option<T>.  But we don't
    /// want to inline space for the entire large T struct in our stack frame.
    /// That's why we hand `f` a mutable borrow to write to instead of just
    /// having it return a T.
    #[inline(always)]
    pub fn ensure<F: FnOnce(&mut Option<T>)>(&self, f: F) -> RefMut<T> {
        let mut opt = self.borrow_mut();
        if opt.is_none() {
            f(opt.deref_mut());
        }

        RefMut::map(opt, |x| x.as_mut().unwrap())
    }

    /// Unsafe access to the slots. This can be used to access the TLS when
    /// the caller knows that the pool does not have access to the TLS.
    pub unsafe fn unsafe_get(&self) -> &[RefCell<Option<T>>] {
        &self.slots
    }
}
<commit_msg>style: Add a comment about a Send bound that may look confusing.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! Stack-scoped thread-local storage for rayon thread pools.

#![allow(unsafe_code)]
#![deny(missing_docs)]

use rayon;
use std::cell::{Ref, RefCell, RefMut};
use std::ops::DerefMut;

/// A scoped TLS set, that is alive during the `'scope` lifetime.
///
/// We use this on Servo to construct thread-local contexts, but clear them once
/// we're done with restyling.
///
/// Note that the cleanup is done on the thread that owns the scoped TLS, thus
/// the Send bound.
pub struct ScopedTLS<'scope, T: Send> {
    pool: &'scope rayon::ThreadPool,
    slots: Box<[RefCell<Option<T>>]>,
}

/// The scoped TLS is `Sync` because no more than one worker thread can access a
/// given slot.
unsafe impl<'scope, T: Send> Sync for ScopedTLS<'scope, T> {}

impl<'scope, T: Send> ScopedTLS<'scope, T> {
    /// Create a new scoped TLS that will last as long as this rayon threadpool
    /// reference.
    pub fn new(p: &'scope rayon::ThreadPool) -> Self {
        let count = p.current_num_threads();
        let mut v = Vec::with_capacity(count);
        for _ in 0..count {
            v.push(RefCell::new(None));
        }

        ScopedTLS {
            pool: p,
            slots: v.into_boxed_slice(),
        }
    }

    /// Return an immutable reference to the `Option<T>` that this thread owns.
    pub fn borrow(&self) -> Ref<Option<T>> {
        let idx = self.pool.current_thread_index().unwrap();
        self.slots[idx].borrow()
    }

    /// Return a mutable reference to the `Option<T>` that this thread owns.
    pub fn borrow_mut(&self) -> RefMut<Option<T>> {
        let idx = self.pool.current_thread_index().unwrap();
        self.slots[idx].borrow_mut()
    }

    /// Ensure that the current data this thread owns is initialized, or
    /// initialize it using `f`.  We want ensure() to be fast and inline, and we
    /// want to inline the memmove that initializes the Option<T>.  But we don't
    /// want to inline space for the entire large T struct in our stack frame.
    /// That's why we hand `f` a mutable borrow to write to instead of just
    /// having it return a T.
    #[inline(always)]
    pub fn ensure<F: FnOnce(&mut Option<T>)>(&self, f: F) -> RefMut<T> {
        let mut opt = self.borrow_mut();
        if opt.is_none() {
            f(opt.deref_mut());
        }

        RefMut::map(opt, |x| x.as_mut().unwrap())
    }

    /// Unsafe access to the slots. This can be used to access the TLS when
    /// the caller knows that the pool does not have access to the TLS.
    pub unsafe fn unsafe_get(&self) -> &[RefCell<Option<T>>] {
        &self.slots
    }
}
<|endoftext|>


<commit_before><commit_msg>add simple example<commit_after>// Copyright (C) 2015  Jonas Pollok <jonas.p@gmail.com>

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#![feature(ers1)]

extern crate ers;

use ers::Expression;

#[cfg(not(test))]
fn main() {
    let expr = "((x r) (x s))".parse::<Expression>().unwrap();
    let pattern = "(x a_)".parse::<Expression>().unwrap();
    let template = "(y a)".parse::<Expression>().unwrap();

    println!("{:?}", expr.replace_all(&pattern, template)); // => ((y z))

    //let t = "a".parse::<Expression>().unwrap();
    //let p = "x".parse::<Expression>().unwrap();

    //let e = "(x x ((x) x) x)".parse::<Expression>().unwrap();
    //for sub in e.subexpressions() {
        //print!("{:?} -> ", sub);
        //match sub.match_pattern(&p) {
            //Some(bs) => {
                //println!("{:?}", t.clone().bind(&bs));
            //}
            //None => {
                //println!("{:?}", sub);
            //}
        //}
    //}
}
<|endoftext|>


<commit_before>fn main() {
    // Iterators can be collected into vectors
    let collected_iterator: Vec<int> = range(0i, 10).collect();
    println!("Collected range(0, 10) into: {}", collected_iterator);

    // The `vec!` macro can be used to initialize a vector
    let mut xs = vec![1i, 2, 3];
    println!("Initial vector: {}", xs);

    // Insert new element at the end of the vector
    println!("Push 4 into the vector")
    xs.push(4);
    println!("Vector: {}", xs);

    // Error! Immutable vectors can't grow
    collected_iterator.push(0);
    // FIXME ^ Comment out this line

    // The `len` method yields the current size of the vector
    println!("Vector size: {}", xs.len());

    // Indexing is done using the square brackets (indexing starts at 0)
    println!("Second element: {}", xs[1]);

    // `pop` removes the last element from the vector and returns it
    println!("Pop last element: {}", xs.pop());

    // Out of bounds indexing yields a task failure
    println!("Fourth element: {}", xs[3]);
}
<commit_msg>fix: cannot borrow immutable local variable `collected_iterator` as mutable<commit_after>fn main() {
    // Iterators can be collected into vectors
    let mut collected_iterator: Vec<int> = range(0i, 10).collect();
    println!("Collected range(0, 10) into: {}", collected_iterator);

    // The `vec!` macro can be used to initialize a vector
    let mut xs = vec![1i, 2, 3];
    println!("Initial vector: {}", xs);

    // Insert new element at the end of the vector
    println!("Push 4 into the vector")
    xs.push(4);
    println!("Vector: {}", xs);

    // Error! Immutable vectors can't grow
    collected_iterator.push(0);
    // FIXME ^ Comment out this line

    // The `len` method yields the current size of the vector
    println!("Vector size: {}", xs.len());

    // Indexing is done using the square brackets (indexing starts at 0)
    println!("Second element: {}", xs[1]);

    // `pop` removes the last element from the vector and returns it
    println!("Pop last element: {}", xs.pop());

    // Out of bounds indexing yields a task failure
    println!("Fourth element: {}", xs[3]);
}
<|endoftext|>


<commit_before><commit_msg>Fix some warnings in the 'menu' example.<commit_after><|endoftext|>


<commit_before><commit_msg>example: Add forward example<commit_after>extern crate fruently;
extern crate time;
use fruently::fluent::Fluent;
use std::collections::HashMap;
use fruently::forwardable::Forwardable;

fn main() {
    let fruently = Fluent::new("0.0.0.0:24224", "test");
    let mut obj = HashMap::new();
    let time = time::now().to_timespec().sec;
    let thmap = (0..10).fold(&mut obj, |mut acc, i| {
        {
            acc.insert(format!("fwd{}", i), "fruently".to_string());
        }
        acc
    });
    let hmap = thmap.clone();
    let entry = (time, hmap);
    let _ = fruently.post(vec![(entry.clone()),(entry.clone())]);
}
<|endoftext|>


<commit_before><commit_msg>Get started on map editor<commit_after>extern crate calx;
extern crate content;
extern crate world;

use calx::backend::{Key, Event};
use calx::backend::{WindowBuilder, Canvas, CanvasBuilder};
use content::TerrainType;
use world::Location;

pub fn main() {
    let window = WindowBuilder::new()
                     .set_title("Mapedit")
                     .build();

    let mut builder = CanvasBuilder::new();
    let mut ctx = builder.build(window);

    loop {
        for event in ctx.events().into_iter() {
            match event {
                Event::Quit => {
                    return;
                }
                _ => (),
            }
        }
        ctx.end_frame();
    }
}

pub struct EditState {
    center: Location,
    brush: TerrainType,
}

impl EditState {
    pub fn new() -> EditState {
        EditState {
            center: Location::new(0, 0),
            brush: TerrainType::Rock,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add support for ~ on unix<commit_after><|endoftext|>


<commit_before><commit_msg>Add boolean parser tests<commit_after>extern crate robin_core;

extern crate nom;

#[cfg(test)]
mod parser_tests {
    use nom::IResult;

    use robin_core::parser::boolean;
    use robin_core::ast::Expression;

    #[test]
    fn parse_a_true_literal() {
        assert_eq!(boolean::boolean_literal(b"true"),
                   IResult::Done(&b""[..], Expression::Boolean(true)));
    }

    #[test]
    fn parse_a_false_literal() {
        assert_eq!(boolean::boolean_literal(b"false"),
                   IResult::Done(&b""[..], Expression::Boolean(false)));
    }
}<|endoftext|>


<commit_before>// xfail-boot
// error-pattern: unresolved import: baz
import zed.bar;
import zed.baz;
mod zed {
  fn bar() {
    log "bar";
  }
}
fn main(vec[str] args) {
   bar();
}
<commit_msg>Add a missed xfail-stage0<commit_after>// xfail-boot
// xfail-stage0
// error-pattern: unresolved import: baz
import zed.bar;
import zed.baz;
mod zed {
  fn bar() {
    log "bar";
  }
}
fn main(vec[str] args) {
   bar();
}
<|endoftext|>


<commit_before><commit_msg>Add macros to simplify reading from stdin in Rust<commit_after>macro_rules! read_line {
    ($v:ident) => {
        let mut temp = String::new();
        std::io::stdin().read_line(&mut temp).unwrap();
        let $v = temp;
    };
    (var, $t:ty, $($v:ident), *) => {
        read_line!(input_line);
        let mut iter = parse_token!($t, input_line);
        $(
            let $v = iter.next().unwrap();
        )*
    };
    (vec, $t:ty, $v:ident) => {
        read_line!(input_line);
        let iter = parse_token!($t, input_line);
        let $v: Vec<$t> = iter.collect();
    };
    ($($v:ident; $t:ty), *) => {
        read_line!(input_line);
        let mut iter = input_line.split_whitespace();
        $(
            let $v: $t = iter.next().unwrap().parse().unwrap();
        )*
    };
}

macro_rules! parse_token {
    ($t:ty, $e:expr) => {
        $e.split_whitespace().map(|x| x.parse::<$t>().unwrap());
    };
}<|endoftext|>


<commit_before><commit_msg>Add devices.rs example, demonstrating the enumeration of available devices and their associated info. A rusty version of the pa_devs.c example.<commit_after>//! The following is an adaptation of the "pa_devs.c" official PortAudio C example.

extern crate portaudio;
use portaudio as pa;

const INTERLEAVED: bool = true;
const LATENCY: pa::Time = 0.0; // Ignored by PortAudio::is_*_format_supported.
const STANDARD_SAMPLE_RATES: [f64; 13] = [
    8000.0, 9600.0, 11025.0, 12000.0, 16000.0, 22050.0, 24000.0, 32000.0,
    44100.0, 48000.0, 88200.0, 96000.0, 192000.0,
];

fn main() {
    run().unwrap()
}

fn run() -> Result<(), pa::Error> {

    let pa = try!(pa::PortAudio::new());

    let num_devices = try!(pa.device_count());
    println!("Number of devices = {}", num_devices);

    for device in try!(pa.devices()) {
        let (idx, info) = try!(device);
        println!("--------------------------------------- {:?}", idx);
        println!("{:#?}", &info);

        let in_channels = info.max_input_channels;
        let input_params = pa::StreamParameters::<i16>::new(idx, in_channels, INTERLEAVED, LATENCY);
        let out_channels = info.max_output_channels;
        let output_params = pa::StreamParameters::<i16>::new(idx, out_channels, INTERLEAVED, LATENCY);

        println!("Supported standard sample rates for half-duplex 16-bit {} channel input:", in_channels);
        for &sample_rate in &STANDARD_SAMPLE_RATES {
            if pa.is_input_format_supported(input_params, sample_rate).is_ok() {
                println!("\t{}hz", sample_rate);
            }
        }

        println!("Supported standard sample rates for half-duplex 16-bit {} channel output:", out_channels);
        for &sample_rate in &STANDARD_SAMPLE_RATES {
            if pa.is_output_format_supported(output_params, sample_rate).is_ok() {
                println!("\t{}hz", sample_rate);
            }
        }

        println!("Supported standard sample rates for full-duplex 16-bit {} channel input, {} channel output:",
                 in_channels, out_channels);
        for &sample_rate in &STANDARD_SAMPLE_RATES {
            if pa.is_duplex_format_supported(input_params, output_params, sample_rate).is_ok() {
                println!("\t{}hz", sample_rate);
            }
        }
    }

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Allow unreachable_code in generated route functions for new ! error types.<commit_after><|endoftext|>


<commit_before>// Copyright 2014-2017 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.

//! # The Rust core allocation and collections library
//!
//! This library provides smart pointers and collections for managing
//! heap-allocated values.
//!
//! This library, like libcore, is not intended for general usage, but rather as
//! a building block of other libraries. The types and interfaces in this
//! library are re-exported through the [standard library](../std/index.html),
//! and should not be used through this library.
//!
//! ## Boxed values
//!
//! The [`Box`](boxed/index.html) type is a smart pointer type. There can
//! only be one owner of a `Box`, and the owner can decide to mutate the
//! contents, which live on the heap.
//!
//! This type can be sent among threads efficiently as the size of a `Box` value
//! is the same as that of a pointer. Tree-like data structures are often built
//! with boxes because each node often has only one owner, the parent.
//!
//! ## Reference counted pointers
//!
//! The [`Rc`](rc/index.html) type is a non-threadsafe reference-counted pointer
//! type intended for sharing memory within a thread. An `Rc` pointer wraps a
//! type, `T`, and only allows access to `&T`, a shared reference.
//!
//! This type is useful when inherited mutability (such as using `Box`) is too
//! constraining for an application, and is often paired with the `Cell` or
//! `RefCell` types in order to allow mutation.
//!
//! ## Atomically reference counted pointers
//!
//! The [`Arc`](sync/index.html) type is the threadsafe equivalent of the `Rc`
//! type. It provides all the same functionality of `Rc`, except it requires
//! that the contained type `T` is shareable. Additionally, `Arc<T>` is itself
//! sendable while `Rc<T>` is not.
//!
//! This type allows for shared access to the contained data, and is often
//! paired with synchronization primitives such as mutexes to allow mutation of
//! shared resources.
//!
//! ## Collections
//!
//! Implementations of the most common general purpose data structures are
//! defined in this library. They are re-exported through the
//! [standard collections library](../std/collections/index.html).
//!
//! ## Heap interfaces
//!
//! The [`alloc`](alloc/index.html) module defines the low-level interface to the
//! default global allocator. It is not compatible with the libc allocator API.

#![allow(unused_attributes)]
#![unstable(feature = "alloc",
            reason = "this library is unlikely to be stabilized in its current \
                      form or name",
            issue = "27783")]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
       html_root_url = "https://doc.rust-lang.org/nightly/",
       issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
       test(no_crate_inject, attr(allow(unused_variables), deny(warnings))))]
#![no_std]
#![needs_allocator]
#![deny(missing_debug_implementations)]

#![cfg_attr(test, allow(deprecated))] // rand
#![cfg_attr(not(test), feature(exact_size_is_empty))]
#![cfg_attr(not(test), feature(generator_trait))]
#![cfg_attr(test, feature(rand, test))]
#![feature(allocator_api)]
#![feature(allow_internal_unstable)]
#![feature(arbitrary_self_types)]
#![feature(ascii_ctype)]
#![feature(box_into_raw_non_null)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(cfg_target_has_atomic)]
#![feature(coerce_unsized)]
#![feature(collections_range)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(dropck_eyepatch)]
#![feature(exact_size_is_empty)]
#![feature(fmt_internals)]
#![feature(from_ref)]
#![feature(fundamental)]
#![feature(futures_api)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(needs_allocator)]
#![feature(optin_builtin_traits)]
#![feature(pattern)]
#![feature(pin)]
#![feature(ptr_internals)]
#![feature(ptr_offset_from)]
#![cfg_attr(stage0, feature(repr_transparent))]
#![feature(rustc_attrs)]
#![feature(specialization)]
#![feature(split_ascii_whitespace)]
#![feature(staged_api)]
#![feature(str_internals)]
#![feature(trusted_len)]
#![feature(try_reserve)]
#![feature(unboxed_closures)]
#![feature(unicode_internals)]
#![feature(unsize)]
#![feature(allocator_internals)]
#![feature(on_unimplemented)]
#![feature(exact_chunks)]
#![feature(pointer_methods)]
#![feature(inclusive_range_methods)]
#![feature(rustc_const_unstable)]
#![feature(const_vec_new)]

#![cfg_attr(not(test), feature(fn_traits, i128))]
#![cfg_attr(test, feature(test))]

// Allow testing this library

#[cfg(test)]
#[macro_use]
extern crate std;
#[cfg(test)]
extern crate test;
#[cfg(test)]
extern crate rand;

// Module with internal macros used by other modules (needs to be included before other modules).
#[macro_use]
mod macros;

// Heaps provided for low-level allocation strategies

pub mod alloc;

#[unstable(feature = "futures_api",
           reason = "futures in libcore are unstable",
           issue = "50547")]
pub mod task;
// Primitive types using the heaps above

// Need to conditionally define the mod from `boxed.rs` to avoid
// duplicating the lang-items when building in test cfg; but also need
// to allow code to have `use boxed::Box;` declarations.
#[cfg(not(test))]
pub mod boxed;
#[cfg(test)]
mod boxed {
    pub use std::boxed::Box;
}
#[cfg(test)]
mod boxed_test;
pub mod collections;
#[cfg(target_has_atomic = "ptr")]
pub mod sync;
pub mod rc;
pub mod raw_vec;

pub mod borrow;
pub mod fmt;
pub mod slice;
pub mod str;
pub mod string;
pub mod vec;

#[cfg(not(test))]
mod std {
    pub use core::ops;      // RangeFull
}
<commit_msg>liballoc docs: Remove “not intended for general usage”<commit_after>// Copyright 2014-2017 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.

//! # The Rust core allocation and collections library
//!
//! This library provides smart pointers and collections for managing
//! heap-allocated values.
//!
//! This library, like libcore, normally doesn’t need to be used directly
//! since its contents are re-exported in the [`std` crate](../std/index.html).
//! Crates that use the `#![no_std]` attribute however will typically
//! not depend on `std`, so they’d use this crate instead.
//!
//! ## Boxed values
//!
//! The [`Box`](boxed/index.html) type is a smart pointer type. There can
//! only be one owner of a `Box`, and the owner can decide to mutate the
//! contents, which live on the heap.
//!
//! This type can be sent among threads efficiently as the size of a `Box` value
//! is the same as that of a pointer. Tree-like data structures are often built
//! with boxes because each node often has only one owner, the parent.
//!
//! ## Reference counted pointers
//!
//! The [`Rc`](rc/index.html) type is a non-threadsafe reference-counted pointer
//! type intended for sharing memory within a thread. An `Rc` pointer wraps a
//! type, `T`, and only allows access to `&T`, a shared reference.
//!
//! This type is useful when inherited mutability (such as using `Box`) is too
//! constraining for an application, and is often paired with the `Cell` or
//! `RefCell` types in order to allow mutation.
//!
//! ## Atomically reference counted pointers
//!
//! The [`Arc`](sync/index.html) type is the threadsafe equivalent of the `Rc`
//! type. It provides all the same functionality of `Rc`, except it requires
//! that the contained type `T` is shareable. Additionally, `Arc<T>` is itself
//! sendable while `Rc<T>` is not.
//!
//! This type allows for shared access to the contained data, and is often
//! paired with synchronization primitives such as mutexes to allow mutation of
//! shared resources.
//!
//! ## Collections
//!
//! Implementations of the most common general purpose data structures are
//! defined in this library. They are re-exported through the
//! [standard collections library](../std/collections/index.html).
//!
//! ## Heap interfaces
//!
//! The [`alloc`](alloc/index.html) module defines the low-level interface to the
//! default global allocator. It is not compatible with the libc allocator API.

#![allow(unused_attributes)]
#![unstable(feature = "alloc",
            reason = "this library is unlikely to be stabilized in its current \
                      form or name",
            issue = "27783")]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
       html_root_url = "https://doc.rust-lang.org/nightly/",
       issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
       test(no_crate_inject, attr(allow(unused_variables), deny(warnings))))]
#![no_std]
#![needs_allocator]
#![deny(missing_debug_implementations)]

#![cfg_attr(test, allow(deprecated))] // rand
#![cfg_attr(not(test), feature(exact_size_is_empty))]
#![cfg_attr(not(test), feature(generator_trait))]
#![cfg_attr(test, feature(rand, test))]
#![feature(allocator_api)]
#![feature(allow_internal_unstable)]
#![feature(arbitrary_self_types)]
#![feature(ascii_ctype)]
#![feature(box_into_raw_non_null)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(cfg_target_has_atomic)]
#![feature(coerce_unsized)]
#![feature(collections_range)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(dropck_eyepatch)]
#![feature(exact_size_is_empty)]
#![feature(fmt_internals)]
#![feature(from_ref)]
#![feature(fundamental)]
#![feature(futures_api)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(needs_allocator)]
#![feature(optin_builtin_traits)]
#![feature(pattern)]
#![feature(pin)]
#![feature(ptr_internals)]
#![feature(ptr_offset_from)]
#![cfg_attr(stage0, feature(repr_transparent))]
#![feature(rustc_attrs)]
#![feature(specialization)]
#![feature(split_ascii_whitespace)]
#![feature(staged_api)]
#![feature(str_internals)]
#![feature(trusted_len)]
#![feature(try_reserve)]
#![feature(unboxed_closures)]
#![feature(unicode_internals)]
#![feature(unsize)]
#![feature(allocator_internals)]
#![feature(on_unimplemented)]
#![feature(exact_chunks)]
#![feature(pointer_methods)]
#![feature(inclusive_range_methods)]
#![feature(rustc_const_unstable)]
#![feature(const_vec_new)]

#![cfg_attr(not(test), feature(fn_traits, i128))]
#![cfg_attr(test, feature(test))]

// Allow testing this library

#[cfg(test)]
#[macro_use]
extern crate std;
#[cfg(test)]
extern crate test;
#[cfg(test)]
extern crate rand;

// Module with internal macros used by other modules (needs to be included before other modules).
#[macro_use]
mod macros;

// Heaps provided for low-level allocation strategies

pub mod alloc;

#[unstable(feature = "futures_api",
           reason = "futures in libcore are unstable",
           issue = "50547")]
pub mod task;
// Primitive types using the heaps above

// Need to conditionally define the mod from `boxed.rs` to avoid
// duplicating the lang-items when building in test cfg; but also need
// to allow code to have `use boxed::Box;` declarations.
#[cfg(not(test))]
pub mod boxed;
#[cfg(test)]
mod boxed {
    pub use std::boxed::Box;
}
#[cfg(test)]
mod boxed_test;
pub mod collections;
#[cfg(target_has_atomic = "ptr")]
pub mod sync;
pub mod rc;
pub mod raw_vec;

pub mod borrow;
pub mod fmt;
pub mod slice;
pub mod str;
pub mod string;
pub mod vec;

#[cfg(not(test))]
mod std {
    pub use core::ops;      // RangeFull
}
<|endoftext|>


<commit_before><commit_msg>Menu state changes based on its child buttons<commit_after><|endoftext|>


<commit_before><commit_msg>rust casting<commit_after>#![allow(unused_variables,overflowing_literals)]
fn main() {
    // 5
    let decimal = 65.4321_f32;
    // error: mismatched types (because there is no implicit conversion)
    //let integer: u8 = decimal;

    let integer = decimal as u8;
    let character = integer as char;
    println!("Casting: {} -> {} -> {}", decimal, integer, character);

    println!("1000 as u16: {}", 1000 as u16); // 1000
    // 1000 - 256 - 256 - 256 = 232
    println!("1000 as u8: {}", 1000 as u8); // 232
    println!("-1 as u8: {}", (-1i8) as u8); // 255

    // 5.1
    let i = 1; // i32 unless there are constraints in how varible is used
    let f = 1.0; // f64 unless there are constraints
    println!("size of i: {}, f: {}", std::mem::size_of_val(&i), std::mem::size_of_val(&f));

    // 5.2
    let elem = 5u8;
    let mut vec = Vec::new();
    vec.push(elem); // inferred type of Vec<u8>
    println!("{:?}", vec);

    // 5.3
    type NanoSecond = u64;
    type Inch = u64;
    let nanoseconds: NanoSecond = 5;
    let inches: Inch = 2;
    let sum = nanoseconds + inches; // type aliases are NOT new types
}
<|endoftext|>


<commit_before><commit_msg>Impl pat parsing.<commit_after><|endoftext|>


<commit_before><commit_msg>adding chapter on methods<commit_after><|endoftext|>