<commit_before>enum MyEnum {
    MyEmptyVariant,
    MyNewtypeVariant(i32),
    MyTupleVariant(i32, i32),
    MyStructVariant {
        my_first_field: i32,
        my_second_field: i32,
    }
}

fn test(me: MyEnum) {
    match me {
        MyEnum::MyEmptyVariant => {},
        MyEnum::MyNewtypeVariant(ref val) => assert_eq!(val, &42),
        MyEnum::MyTupleVariant(ref a, ref b) => {
            assert_eq!(a, &43);
            assert_eq!(b, &44);
        },
        MyEnum::MyStructVariant { ref my_first_field, ref my_second_field } => {
            assert_eq!(my_first_field, &45);
            assert_eq!(my_second_field, &46);
        },
    }
}

fn discriminant_overflow() {
    // Tests for https://github.com/rust-lang/rust/issues/62138.
    #[repr(u8)]
    #[allow(dead_code)]
    enum WithWraparoundInvalidValues {
        X = 1,
        Y = 254,
    }

    #[allow(dead_code)]
    enum Foo {
        A,
        B,
        C(WithWraparoundInvalidValues),
    }

    let x = Foo::B;
    match x {
        Foo::B => {},
        _ => panic!(),
    }
}

fn main() {
    test(MyEnum::MyEmptyVariant);
    test(MyEnum::MyNewtypeVariant(42));
    test(MyEnum::MyTupleVariant(43, 44));
    test(MyEnum::MyStructVariant{
        my_first_field: 45,
        my_second_field: 46,
    });

    discriminant_overflow();
}
<commit_msg>add another test case<commit_after>enum MyEnum {
    MyEmptyVariant,
    MyNewtypeVariant(i32),
    MyTupleVariant(i32, i32),
    MyStructVariant {
        my_first_field: i32,
        my_second_field: i32,
    }
}

fn test(me: MyEnum) {
    match me {
        MyEnum::MyEmptyVariant => {},
        MyEnum::MyNewtypeVariant(ref val) => assert_eq!(val, &42),
        MyEnum::MyTupleVariant(ref a, ref b) => {
            assert_eq!(a, &43);
            assert_eq!(b, &44);
        },
        MyEnum::MyStructVariant { ref my_first_field, ref my_second_field } => {
            assert_eq!(my_first_field, &45);
            assert_eq!(my_second_field, &46);
        },
    }
}

fn discriminant_overflow() {
    // Tests for https://github.com/rust-lang/rust/issues/62138.
    #[repr(u8)]
    #[allow(dead_code)]
    enum WithWraparoundInvalidValues {
        X = 1,
        Y = 254,
    }

    #[allow(dead_code)]
    enum Foo {
        A,
        B,
        C(WithWraparoundInvalidValues),
    }

    let x = Foo::B;
    match x {
        Foo::B => {},
        _ => panic!(),
    }
}

fn more_discriminant_overflow() {
    pub enum Infallible {}

    // The check that the `bool` field of `V1` is encoding a "niche variant"
    // (i.e. not `V1`, so `V3` or `V4`) used to be mathematically incorrect,
    // causing valid `V1` values to be interpreted as other variants.
    #[allow(dead_code)]
    pub enum E1 {
        V1 { f: bool },
        V2 { f: Infallible },
        V3,
        V4,
    }

    // Computing the discriminant used to be done using the niche type (here `u8`,
    // from the `bool` field of `V1`), overflowing for variants with large enough
    // indices (`V3` and `V4`), causing them to be interpreted as other variants.
    #[allow(dead_code)]
    pub enum E2<X> {
        V1 { f: bool },

        /*_00*/ _01(X), _02(X), _03(X), _04(X), _05(X), _06(X), _07(X),
        _08(X), _09(X), _0A(X), _0B(X), _0C(X), _0D(X), _0E(X), _0F(X),
        _10(X), _11(X), _12(X), _13(X), _14(X), _15(X), _16(X), _17(X),
        _18(X), _19(X), _1A(X), _1B(X), _1C(X), _1D(X), _1E(X), _1F(X),
        _20(X), _21(X), _22(X), _23(X), _24(X), _25(X), _26(X), _27(X),
        _28(X), _29(X), _2A(X), _2B(X), _2C(X), _2D(X), _2E(X), _2F(X),
        _30(X), _31(X), _32(X), _33(X), _34(X), _35(X), _36(X), _37(X),
        _38(X), _39(X), _3A(X), _3B(X), _3C(X), _3D(X), _3E(X), _3F(X),
        _40(X), _41(X), _42(X), _43(X), _44(X), _45(X), _46(X), _47(X),
        _48(X), _49(X), _4A(X), _4B(X), _4C(X), _4D(X), _4E(X), _4F(X),
        _50(X), _51(X), _52(X), _53(X), _54(X), _55(X), _56(X), _57(X),
        _58(X), _59(X), _5A(X), _5B(X), _5C(X), _5D(X), _5E(X), _5F(X),
        _60(X), _61(X), _62(X), _63(X), _64(X), _65(X), _66(X), _67(X),
        _68(X), _69(X), _6A(X), _6B(X), _6C(X), _6D(X), _6E(X), _6F(X),
        _70(X), _71(X), _72(X), _73(X), _74(X), _75(X), _76(X), _77(X),
        _78(X), _79(X), _7A(X), _7B(X), _7C(X), _7D(X), _7E(X), _7F(X),
        _80(X), _81(X), _82(X), _83(X), _84(X), _85(X), _86(X), _87(X),
        _88(X), _89(X), _8A(X), _8B(X), _8C(X), _8D(X), _8E(X), _8F(X),
        _90(X), _91(X), _92(X), _93(X), _94(X), _95(X), _96(X), _97(X),
        _98(X), _99(X), _9A(X), _9B(X), _9C(X), _9D(X), _9E(X), _9F(X),
        _A0(X), _A1(X), _A2(X), _A3(X), _A4(X), _A5(X), _A6(X), _A7(X),
        _A8(X), _A9(X), _AA(X), _AB(X), _AC(X), _AD(X), _AE(X), _AF(X),
        _B0(X), _B1(X), _B2(X), _B3(X), _B4(X), _B5(X), _B6(X), _B7(X),
        _B8(X), _B9(X), _BA(X), _BB(X), _BC(X), _BD(X), _BE(X), _BF(X),
        _C0(X), _C1(X), _C2(X), _C3(X), _C4(X), _C5(X), _C6(X), _C7(X),
        _C8(X), _C9(X), _CA(X), _CB(X), _CC(X), _CD(X), _CE(X), _CF(X),
        _D0(X), _D1(X), _D2(X), _D3(X), _D4(X), _D5(X), _D6(X), _D7(X),
        _D8(X), _D9(X), _DA(X), _DB(X), _DC(X), _DD(X), _DE(X), _DF(X),
        _E0(X), _E1(X), _E2(X), _E3(X), _E4(X), _E5(X), _E6(X), _E7(X),
        _E8(X), _E9(X), _EA(X), _EB(X), _EC(X), _ED(X), _EE(X), _EF(X),
        _F0(X), _F1(X), _F2(X), _F3(X), _F4(X), _F5(X), _F6(X), _F7(X),
        _F8(X), _F9(X), _FA(X), _FB(X), _FC(X), _FD(X), _FE(X), _FF(X),

        V3,
        V4,
    }

    if let E1::V2 { .. } = (E1::V1 { f: true }) {
        unreachable!()
    }
    if let E1::V1 { .. } = (E1::V1 { f: true }) {
    } else {
        unreachable!()
    }

    if let E2::V1 { .. } = E2::V3::<Infallible> {
        unreachable!()
    }
    if let E2::V3 { .. } = E2::V3::<Infallible> {
    } else {
        unreachable!()
    }
}

fn main() {
    test(MyEnum::MyEmptyVariant);
    test(MyEnum::MyNewtypeVariant(42));
    test(MyEnum::MyTupleVariant(43, 44));
    test(MyEnum::MyStructVariant{
        my_first_field: 45,
        my_second_field: 46,
    });

    discriminant_overflow();
    more_discriminant_overflow();
}
<|endoftext|>


<commit_before>//! The test suite in this file is adapted from:
//! https://docs.opencv.org/3.1.0/d3/df2/tutorial_py_basic_ops.html
//!
//! N.B. Blue pixel value at (100, 100) is actually 156, NOT 157...

extern crate cv;
mod utils;

#[test]
fn test_accessing_pixel() {
    let img = utils::load_messi_color();

    let pixel = img.at2::<(u8, u8, u8)>(100, 100);
    assert_eq!(pixel.0, 156);
    assert_eq!(pixel.1, 166);
    assert_eq!(pixel.2, 200);

    let blue = img.at3::<u8>(100, 100, 0);
    assert_eq!(blue, 156);

    // img.set(100, 100, (255, 255, 255));
    // assert!(img.at(100, 100), (255, 255, 255));
}
<commit_msg>allow for pixel variation in testing<commit_after>//! The test suite in this file is adapted from:
//! https://docs.opencv.org/3.1.0/d3/df2/tutorial_py_basic_ops.html
//!
//! N.B. Blue pixel value at (100, 100) is actually 156 on my laptop (Mac OS),
//! but 157 on Travis (trusty). This nuance comes from JPEG decoding...

extern crate cv;
mod utils;

#[test]
fn test_accessing_pixel() {
    let img = utils::load_messi_color();

    let pixel = img.at2::<(u8, u8, u8)>(100, 100);
    assert!(pixel_eq(pixel.0, 156));
    assert!(pixel_eq(pixel.1, 166));
    assert!(pixel_eq(pixel.2, 200));

    let blue = img.at3::<u8>(100, 100, 0);
    assert!(pixel_eq(blue, 156));

    // img.set(100, 100, (255, 255, 255));
    // assert!(img.at(100, 100), (255, 255, 255));
}

fn pixel_eq(a: u8, b: u8) -> bool {
    (a - b) <= 1
}
<|endoftext|>


<commit_before>extern crate ohmers;
extern crate redis;
extern crate rustc_serialize;

use ohmers::{get, Ohmer, Reference};
use rustc_serialize::Encodable;

#[derive(RustcEncodable, RustcDecodable, PartialEq, Debug)]
struct Person {
    id: usize,
    name: String,
    father: Reference<Person>,
    mother: Reference<Person>,
}
impl Ohmer for Person {
    fn id(&self) -> usize { self.id }
    fn set_id(&mut self, id: usize) { self.id = id; }
    fn defaults() -> Self {
        Person {
            id: 0,
            name: "".to_string(),
            father: Reference::new(),
            mother: Reference::new(),
        }
    }
}

#[test]
fn test_reference() {
    let client = redis::Client::open("redis://127.0.0.1/").unwrap();

    let mut father = Person::defaults();
    father.name = "John".to_string();
    father.save(&client).unwrap();

    let mut mother = Person::defaults();
    mother.name = "Jane".to_string();
    mother.save(&client).unwrap();

    let mut person = Person::defaults();
    person.name = "Alice".to_string();
    person.father.set(&father);
    person.mother.set(&mother);
    person.save(&client).unwrap();

    let person2 = get(person.id, &client).unwrap();
    assert_eq!(person, person2);
    assert_eq!(person2.father.get(&client).unwrap(), father);
    assert_eq!(person2.mother.get(&client).unwrap(), mother);
}
<commit_msg>More reference test<commit_after>extern crate ohmers;
extern crate redis;
extern crate rustc_serialize;

use ohmers::{get, Ohmer, Reference};
use rustc_serialize::Encodable;

#[derive(RustcEncodable, RustcDecodable, PartialEq, Debug)]
struct Person {
    id: usize,
    name: String,
    father: Reference<Person>,
    mother: Reference<Person>,
}
impl Ohmer for Person {
    fn id(&self) -> usize { self.id }
    fn set_id(&mut self, id: usize) { self.id = id; }
    fn defaults() -> Self {
        Person {
            id: 0,
            name: "".to_string(),
            father: Reference::new(),
            mother: Reference::new(),
        }
    }
}

#[test]
fn test_reference() {
    let client = redis::Client::open("redis://127.0.0.1/").unwrap();

    let mut father = Person::defaults();
    father.name = "John".to_string();
    father.save(&client).unwrap();

    let mut mother = Person::defaults();
    mother.name = "Jane".to_string();
    mother.save(&client).unwrap();

    let mut person = Person::defaults();
    person.name = "Alice".to_string();
    person.father.set(&father);
    person.mother.set(&mother);
    person.save(&client).unwrap();

    let person2 = get(person.id, &client).unwrap();
    assert_eq!(person, person2);
    assert_eq!(person2.father.get(&client).unwrap(), father);
    assert_eq!(person2.mother.get(&client).unwrap(), mother);
}

#[derive(RustcEncodable, RustcDecodable, PartialEq, Debug)]
struct Location {
    id: usize,
    name: String,
}
impl Ohmer for Location {
    fn id(&self) -> usize { self.id }
    fn set_id(&mut self, id: usize) { self.id = id; }
    fn defaults() -> Self {
        Location {
            id: 0,
            name: "".to_string(),
        }
    }
}

#[derive(RustcEncodable, RustcDecodable, PartialEq, Debug)]
struct Event {
    id: usize,
    name: String,
    location: Reference<Location>
}
impl Ohmer for Event {
    fn id(&self) -> usize { self.id }
    fn set_id(&mut self, id: usize) { self.id = id; }
    fn defaults() -> Self {
        Event {
            id: 0,
            name: "".to_string(),
            location: Reference::new(),
        }
    }
}

#[test]
fn test_event_location() {
    let client = redis::Client::open("redis://127.0.0.1/").unwrap();

    let mut location = Location::defaults();
    location.name = "House".to_string();
    location.save(&client).unwrap();

    let mut event = Event::defaults();
    event.name = "Birthday Party".to_string();
    event.location.set(&location);
    assert_eq!(event.id, 0);
    event.save(&client).unwrap();
    assert!(event.id > 0);

    let event2:Event = get(event.id, &client).unwrap();
    assert_eq!(event2.name, "Birthday Party");
    assert_eq!(event2.location.get(&client).unwrap().name, "House");
}
<|endoftext|>


<commit_before>#![feature(rustc_private)]

extern crate rustc_interface;
extern crate rustc_driver;
extern crate rustc_session;
extern crate rustc_span;

use rustc_session::DiagnosticOutput;
use rustc_session::config::{Input, Options, OutputType, OutputTypes};
use rustc_interface::interface;
use rustc_span::source_map::FileName;

use std::path::PathBuf;

fn main() {
    let src = r#"
    fn main() {}
    "#;

    let args: Vec<String> = std::env::args().collect();

    if args.len() < 4 {
        panic!("expected rustc path");
    }

    let tmpdir = PathBuf::from(&args[1]);

    let mut sysroot = PathBuf::from(&args[3]);
    sysroot.pop();
    sysroot.pop();

    compile(src.to_string(), tmpdir.join("out"), sysroot.clone());

    compile(src.to_string(), tmpdir.join("out"), sysroot.clone());
}

fn compile(code: String, output: PathBuf, sysroot: PathBuf) {
    let mut opts = Options::default();
    opts.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
    opts.maybe_sysroot = Some(sysroot);

    if let Ok(linker) = std::env::var("RUSTC_LINKER") {
        opts.cg.linker = Some(linker.into());
    }

    let name = FileName::anon_source_code(&code);
    let input = Input::Str { name, input: code };

    let config = interface::Config {
        opts,
        crate_cfg: Default::default(),
        input,
        input_path: None,
        output_file: Some(output),
        output_dir: None,
        file_loader: None,
        diagnostic_output: DiagnosticOutput::Default,
        stderr: None,
        lint_caps: Default::default(),
        register_lints: None,
        override_queries: None,
        make_codegen_backend: None,
        registry: rustc_driver::diagnostics_registry(),
    };

    interface::run_compiler(config, |compiler| {
        // This runs all the passes prior to linking, too.
        let linker = compiler.enter(|queries| {
            queries.linker()
        });
        if let Ok(linker) = linker {
            linker.link();
        }
    });
}
<commit_msg>Fix `src/test/run-make-fulldeps/issue-19371`<commit_after>#![feature(rustc_private)]

extern crate rustc_interface;
extern crate rustc_driver;
extern crate rustc_session;
extern crate rustc_span;

use rustc_session::DiagnosticOutput;
use rustc_session::config::{Input, Options, OutputType, OutputTypes};
use rustc_interface::interface;
use rustc_span::source_map::FileName;

use std::path::PathBuf;

fn main() {
    let src = r#"
    fn main() {}
    "#;

    let args: Vec<String> = std::env::args().collect();

    if args.len() < 4 {
        panic!("expected rustc path");
    }

    let tmpdir = PathBuf::from(&args[1]);

    let mut sysroot = PathBuf::from(&args[3]);
    sysroot.pop();
    sysroot.pop();

    compile(src.to_string(), tmpdir.join("out"), sysroot.clone());

    compile(src.to_string(), tmpdir.join("out"), sysroot.clone());
}

fn compile(code: String, output: PathBuf, sysroot: PathBuf) {
    let mut opts = Options::default();
    opts.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
    opts.maybe_sysroot = Some(sysroot);

    if let Ok(linker) = std::env::var("RUSTC_LINKER") {
        opts.cg.linker = Some(linker.into());
    }

    let name = FileName::anon_source_code(&code);
    let input = Input::Str { name, input: code };

    let config = interface::Config {
        opts,
        crate_cfg: Default::default(),
        input,
        input_path: None,
        output_file: Some(output),
        output_dir: None,
        file_loader: None,
        diagnostic_output: DiagnosticOutput::Default,
        stderr: None,
        lint_caps: Default::default(),
        parse_sess_created: None,
        register_lints: None,
        override_queries: None,
        make_codegen_backend: None,
        registry: rustc_driver::diagnostics_registry(),
    };

    interface::run_compiler(config, |compiler| {
        // This runs all the passes prior to linking, too.
        let linker = compiler.enter(|queries| {
            queries.linker()
        });
        if let Ok(linker) = linker {
            linker.link();
        }
    });
}
<|endoftext|>


<commit_before>//! `StructureExtractor` data description.
use crate::data::RoomName;

with_structure_fields_and_update_struct! {
    /// An extractor structure - a structure that can be used to harvest minerals.
    #[derive(Clone, Debug, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct StructureExtractor {
        /// The user ID of the owner of this structure.
        pub user: String,
        /// Whether or not this structure is non-functional due to a degraded controller.
        #[serde(default, rename = "off")]
        pub disabled: bool,
        /// Whether or not an attack on this structure will send an email to the owner automatically.
        pub notify_when_attacked: bool,
    }

    /// The update structure for an extension structure.
    #[derive(Clone, Debug)]
    #[serde(rename_all = "camelCase")]
    pub struct StructureExtractorUpdate {
        - user: String,
        #[serde(rename = "off")]
        - disabled: bool,
        - notify_when_attacked: bool,
    }
}

#[cfg(test)]
mod test {
    use serde::Deserialize;

    use crate::data::RoomName;

    use super::StructureExtractor;

    #[test]
    fn parse_extractor_sample() {
        let json = json!({
            "_id": "5cb56020f7d8904f5df7a1ae",
            "hits": 500,
            "hitsMax": 500,
            "notifyWhenAttacked": true,
            "room": "E8S29",
            "type": "extractor",
            "user": "5ca80c8f3c33e30c8e85555d",
            "x": 29,
            "y": 40,
        });

        let obj = StructureExtractor::deserialize(json).unwrap();

        assert_eq!(
            obj,
            StructureExtractor {
                room: RoomName::new("E8S29").unwrap(),
                x: 29,
                y: 40,
                id: "5cb56020f7d8904f5df7a1ae".to_owned(),
                hits: 500,
                hits_max: 500,
                notify_when_attacked: true,
                disabled: false,
                user: "5ca80c8f3c33e30c8e85555d".to_owned(),
            }
        );
    }
}
<commit_msg>Fix support for ownerless extractors<commit_after>//! `StructureExtractor` data description.
use crate::data::RoomName;

with_structure_fields_and_update_struct! {
    /// An extractor structure - a structure that can be used to harvest minerals.
    #[derive(Clone, Debug, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct StructureExtractor {
        /// The user ID of the owner of this structure.
        pub user: Option<String>,
        /// Whether or not this structure is non-functional due to a degraded controller.
        #[serde(default, rename = "off")]
        pub disabled: bool,
        /// Whether or not an attack on this structure will send an email to the owner automatically.
        #[serde(default)]
        pub notify_when_attacked: bool,
    }

    /// The update structure for an extension structure.
    #[derive(Clone, Debug)]
    #[serde(rename_all = "camelCase")]
    pub struct StructureExtractorUpdate {
        - user: Option<String>,
        #[serde(rename = "off")]
        - disabled: bool,
        - notify_when_attacked: bool,
    }
}

#[cfg(test)]
mod test {
    use serde::Deserialize;

    use crate::data::RoomName;

    use super::StructureExtractor;

    #[test]
    fn parse_extractor_sample() {
        let json = json!({
            "_id": "5cb56020f7d8904f5df7a1ae",
            "hits": 500,
            "hitsMax": 500,
            "notifyWhenAttacked": true,
            "room": "E8S29",
            "type": "extractor",
            "user": "5ca80c8f3c33e30c8e85555d",
            "x": 29,
            "y": 40,
        });

        let obj = StructureExtractor::deserialize(json).unwrap();

        assert_eq!(
            obj,
            StructureExtractor {
                room: RoomName::new("E8S29").unwrap(),
                x: 29,
                y: 40,
                id: "5cb56020f7d8904f5df7a1ae".to_owned(),
                hits: 500,
                hits_max: 500,
                notify_when_attacked: true,
                disabled: false,
                user: Some("5ca80c8f3c33e30c8e85555d".to_owned()),
            }
        );
    }

    #[test]
    fn parse_keeper_room_extractor() {
        let json = json!({
            "_id": "59834302d7922107c0781386",
            "cooldown": 0,
            "room": "W5S35",
            "type": "extractor",
            "x": 9,
            "y": 36,
        });

        let obj = StructureExtractor::deserialize(json).unwrap();

        assert_eq!(
            obj,
            StructureExtractor {
                room: RoomName::new("W5S35").unwrap(),
                x: 9,
                y: 36,
                id: "59834302d7922107c0781386".to_owned(),
                hits: 0,
                hits_max: 0,
                notify_when_attacked: false,
                disabled: false,
                user: None,
            }
        );
    }
}
<|endoftext|>


<commit_before>use decoders::*;
use decoders::tiff::*;
use decoders::basics::*;
use std::f32::NAN;

#[derive(Debug, Clone)]
pub struct MosDecoder<'a> {
  buffer: &'a [u8],
  rawloader: &'a RawLoader,
  tiff: TiffIFD<'a>,
}

impl<'a> MosDecoder<'a> {
  pub fn new(buf: &'a [u8], tiff: TiffIFD<'a>, rawloader: &'a RawLoader) -> MosDecoder<'a> {
    MosDecoder {
      buffer: buf,
      tiff: tiff,
      rawloader: rawloader,
    }
  }
}

impl<'a> Decoder for MosDecoder<'a> {
  fn image(&self) -> Result<Image,String> {
    let make = try!(self.xmp_tag("Make"));
    let model_full = try!(self.xmp_tag("Model")).to_string();
    let model = model_full.split_terminator("(").next().unwrap();
    let camera = try!(self.rawloader.check_supported_with_everything(&make, &model, ""));

    let raw = fetch_ifd!(&self.tiff, Tag::TileOffsets);
    let width = fetch_tag!(raw, Tag::ImageWidth).get_usize(0);
    let height = fetch_tag!(raw, Tag::ImageLength).get_usize(0);
    let offset = fetch_tag!(raw, Tag::TileOffsets).get_usize(0);
    let src = &self.buffer[offset..];

    let image = if self.tiff.little_endian() {
      decode_16le(src, width, height)
    } else {
      decode_16be(src, width, height)
    };

    ok_image(camera, width, height, try!(self.get_wb()), image)
  }
}

impl<'a> MosDecoder<'a> {
  fn get_wb(&self) -> Result<[f32;4], String> {
    let meta = fetch_tag!(self.tiff, Tag::LeafMetadata).get_data();
    let mut pos = 0;
    // We need at least 16+45+10 bytes for the NeutObj_neutrals section itself
    while pos + 70 < meta.len() {
      if meta[pos..pos+16] == b"NeutObj_neutrals"[..] {
        let data = &meta[pos+44..];
        if let Some(endpos) = data.iter().position(|&x| x == 0) {
          let nums = String::from_utf8_lossy(&data[0..endpos])
                       .split_terminator("\n")
                       .map(|x| x.parse::<f32>().unwrap_or(NAN))
                       .collect::<Vec<f32>>();
          if nums.len() == 4 {
            return Ok([nums[0]/nums[1], nums[0]/nums[2], nums[0]/nums[3], NAN])
          }
        }
        break;
      }
      pos += 1;
    }
    Ok([NAN,NAN,NAN,NAN])
  }

  fn xmp_tag(&self, tag: &str) -> Result<String, String> {
    let xmp = fetch_tag!(self.tiff, Tag::Xmp).get_str();
    let error = format!("MOS: Couldn't find XMP tag {}", tag).to_string();
    let start = try!(xmp.find(&format!("<tiff:{}>",tag)).ok_or(error.clone()));
    let end   = try!(xmp.find(&format!("</tiff:{}>",tag)).ok_or(error.clone()));

    Ok(xmp[start+tag.len()+7..end].to_string())
  }
}
<commit_msg>MOS: detect unsupported compression<commit_after>use decoders::*;
use decoders::tiff::*;
use decoders::basics::*;
use std::f32::NAN;

#[derive(Debug, Clone)]
pub struct MosDecoder<'a> {
  buffer: &'a [u8],
  rawloader: &'a RawLoader,
  tiff: TiffIFD<'a>,
}

impl<'a> MosDecoder<'a> {
  pub fn new(buf: &'a [u8], tiff: TiffIFD<'a>, rawloader: &'a RawLoader) -> MosDecoder<'a> {
    MosDecoder {
      buffer: buf,
      tiff: tiff,
      rawloader: rawloader,
    }
  }
}

impl<'a> Decoder for MosDecoder<'a> {
  fn image(&self) -> Result<Image,String> {
    let make = try!(self.xmp_tag("Make"));
    let model_full = try!(self.xmp_tag("Model")).to_string();
    let model = model_full.split_terminator("(").next().unwrap();
    let camera = try!(self.rawloader.check_supported_with_everything(&make, &model, ""));

    let raw = fetch_ifd!(&self.tiff, Tag::TileOffsets);
    let width = fetch_tag!(raw, Tag::ImageWidth).get_usize(0);
    let height = fetch_tag!(raw, Tag::ImageLength).get_usize(0);
    let offset = fetch_tag!(raw, Tag::TileOffsets).get_usize(0);
    let src = &self.buffer[offset..];

    let image = match fetch_tag!(raw, Tag::Compression).get_usize(0) {
      1 => {
        if self.tiff.little_endian() {
          decode_16le(src, width, height)
        } else {
          decode_16be(src, width, height)
        }
      },
      x => return Err(format!("MOS: unsupported compression {}", x).to_string())
    };

    ok_image(camera, width, height, try!(self.get_wb()), image)
  }
}

impl<'a> MosDecoder<'a> {
  fn get_wb(&self) -> Result<[f32;4], String> {
    let meta = fetch_tag!(self.tiff, Tag::LeafMetadata).get_data();
    let mut pos = 0;
    // We need at least 16+45+10 bytes for the NeutObj_neutrals section itself
    while pos + 70 < meta.len() {
      if meta[pos..pos+16] == b"NeutObj_neutrals"[..] {
        let data = &meta[pos+44..];
        if let Some(endpos) = data.iter().position(|&x| x == 0) {
          let nums = String::from_utf8_lossy(&data[0..endpos])
                       .split_terminator("\n")
                       .map(|x| x.parse::<f32>().unwrap_or(NAN))
                       .collect::<Vec<f32>>();
          if nums.len() == 4 {
            return Ok([nums[0]/nums[1], nums[0]/nums[2], nums[0]/nums[3], NAN])
          }
        }
        break;
      }
      pos += 1;
    }
    Ok([NAN,NAN,NAN,NAN])
  }

  fn xmp_tag(&self, tag: &str) -> Result<String, String> {
    let xmp = fetch_tag!(self.tiff, Tag::Xmp).get_str();
    let error = format!("MOS: Couldn't find XMP tag {}", tag).to_string();
    let start = try!(xmp.find(&format!("<tiff:{}>",tag)).ok_or(error.clone()));
    let end   = try!(xmp.find(&format!("</tiff:{}>",tag)).ok_or(error.clone()));

    Ok(xmp[start+tag.len()+7..end].to_string())
  }
}
<|endoftext|>


<commit_before>//
//   Copyright 2016 Andrew Hunter
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in 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.
//

//!
//! # DFA compiler
//!
//! The DFA compiler converts NDFAs into DFAs, using a DFA builder.
//!

use std::marker::PhantomData;

use super::dfa_builder::*;
use super::state_machine::*;

///
/// Builds a deterministic finite automaton from a NDFA
///
pub struct DfaCompiler<InputSymbol: PartialOrd, OutputSymbol, DfaType, Ndfa: StateMachine<InputSymbol, OutputSymbol>, Builder: DfaBuilder<InputSymbol, OutputSymbol, DfaType>> {
    ndfa: Ndfa,
    builder: Builder,

    // Phantom data to poke Rust's type system (it's too dumb to see that InputSymbol is used in both Ndfa and Builder there via the type constraint)
    phantom: (PhantomData<InputSymbol>, PhantomData<OutputSymbol>, PhantomData<DfaType>)
}

impl<InputSymbol: PartialOrd, OutputSymbol, DfaType, Ndfa: StateMachine<InputSymbol, OutputSymbol>, Builder: DfaBuilder<InputSymbol, OutputSymbol, DfaType>>
    DfaCompiler<InputSymbol, OutputSymbol, DfaType, Ndfa, Builder> {
    pub fn new(ndfa: Ndfa, builder: Builder) -> Self {
        DfaCompiler { ndfa: ndfa, builder: builder, phantom: (PhantomData, PhantomData, PhantomData) }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use super::super::regular_pattern::*;
    use super::super::state_machine::*;
    use super::super::symbol_range_dfa::*;

    #[test]
    fn create_compiler() {
        let ndfa = "abc".into_pattern().to_ndfa("success");
        let builder = SymbolRangeDfaBuilder::new();

        let compiler = DfaCompiler::new(ndfa, builder);
    }
}<commit_msg>Suppress this dead code warning (sigh)<commit_after>//
//   Copyright 2016 Andrew Hunter
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in 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.
//

//!
//! # DFA compiler
//!
//! The DFA compiler converts NDFAs into DFAs, using a DFA builder.
//!

use std::marker::PhantomData;

use super::dfa_builder::*;
use super::state_machine::*;

///
/// Builds a deterministic finite automaton from a NDFA
///
pub struct DfaCompiler<InputSymbol: PartialOrd, OutputSymbol, DfaType, Ndfa: StateMachine<InputSymbol, OutputSymbol>, Builder: DfaBuilder<InputSymbol, OutputSymbol, DfaType>> {
    ndfa: Ndfa,
    builder: Builder,

    // Phantom data to poke Rust's type system (it's too dumb to see that InputSymbol is used in both Ndfa and Builder there via the type constraint)
    #[allow(dead_code)]
    phantom: (PhantomData<InputSymbol>, PhantomData<OutputSymbol>, PhantomData<DfaType>)
}

impl<InputSymbol: PartialOrd, OutputSymbol, DfaType, Ndfa: StateMachine<InputSymbol, OutputSymbol>, Builder: DfaBuilder<InputSymbol, OutputSymbol, DfaType>>
    DfaCompiler<InputSymbol, OutputSymbol, DfaType, Ndfa, Builder> {
    pub fn new(ndfa: Ndfa, builder: Builder) -> Self {
        DfaCompiler { ndfa: ndfa, builder: builder, phantom: (PhantomData, PhantomData, PhantomData) }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use super::super::regular_pattern::*;
    use super::super::state_machine::*;
    use super::super::symbol_range_dfa::*;

    #[test]
    fn create_compiler() {
        let ndfa = "abc".into_pattern().to_ndfa("success");
        let builder = SymbolRangeDfaBuilder::new();

        let compiler = DfaCompiler::new(ndfa, builder);
    }
}<|endoftext|>


<commit_before>use std::sync::{Arc, Mutex};
use simple_parallel;

use rules::LRules;
use state::LSystem;
use super::{LProcessor, SimpleProcessor};

/// Parallel processor dividing a state into chunks to be individually iterated
/// within a pool of threads.
pub struct ChunksProcessor {
    /// The maximum number of tasks (sub-threads), i.e. the maximum amount of
    /// chunks treated in parallel.
    max_tasks: usize,
    /// The number of symbols per full chunk.
    chunk_size: usize,
    /// The thread pool.
    pool: simple_parallel::Pool,
}

impl ChunksProcessor {
    /// Try and create a new 'ChunksProcessor' instance with the given parameters.
    /// Typical values:
    /// - max_tasks : number of CPU logical cores
    /// - chunks_size : between 100_000 and 1_000_000 symbols per chunk
    pub fn new(max_tasks: usize, chunks_size: usize) -> Result<ChunksProcessor, String> {
        if max_tasks == 0 {
            Err(format!("ChunksProcessor::new : invalid maximum tasks number ({})",
                        max_tasks))
        } else if chunks_size == 0 {
            Err(format!("ChunksProcessor::new : invalid chunks size ({})",
                        chunks_size))
        } else {
            Ok(ChunksProcessor {
                max_tasks: max_tasks,
                chunk_size: chunks_size,
                pool: simple_parallel::Pool::new(max_tasks),
            })
        }
    }
}

impl<S> LProcessor<S> for ChunksProcessor where S: Clone + Eq + Send + Sync
{
    // TODO : better error handling...
    fn iterate<'a>(&mut self, lsystem: &LSystem<'a, S>) -> Result<LSystem<'a, S>, String> {
        // Set-up
        let mut vec: Vec<Vec<S>> = Vec::new();
        let state_len = lsystem.state().len();
        if state_len == 0 {
            return Err(format!("cannot iterate an empty state"));
        }
        let rem = state_len % self.chunk_size;
        let chunks_number = state_len / self.chunk_size +
                            match rem {
            0 => 0,
            _ => 1,
        };
        for _ in 0..chunks_number {
            vec.push(Vec::new());
        }
        let sub_states = Arc::new(Mutex::new(vec));

        // Chunks processing
        let rules = lsystem.rules().clone();
        let errors = Mutex::new(String::new());
        let chunks_iter = lsystem.state().chunks(self.chunk_size);
        self.pool.for_(chunks_iter.enumerate(), |(n, chunk)| {
            let result: Vec<S> = match SimpleProcessor::iterate_slice(chunk, &rules) {
                Ok(v) => v,
                Err(why) => {
                    let mut error_lock = errors.lock().unwrap();
                    *error_lock = format!("{}\n{}", *error_lock, why);
                    Vec::new()
                }
            };
            let mut chunk_data = sub_states.lock().unwrap();
            chunk_data[n] = result;
        });

        // Error handling
        let error_lock = errors.lock().unwrap();
        if !error_lock.is_empty() {
            return Err(format!("ChunksProcessor : iteration error(s):\n{}", *error_lock));
        }

        // Final assembling
        let mut new_state_size = 0usize;
        let mut new_state: Vec<S> = Vec::new();
        let mut data = sub_states.lock().unwrap();
        for n in 0..chunks_number {
            let chunk_iterated = &data[n];
            new_state_size = match new_state_size.checked_add(chunk_iterated.len()) {
                Some(v) => v,
                None => {
                    return Err(format!("ChunksProcessor::iterate : usize overflow, state too big \
                                        for for Vec"))
                }
            };
            new_state.extend(chunk_iterated.iter().cloned());
        }
        Ok(LSystem::<S>::new(new_state, rules, Some(lsystem.iteration() + 1)))
    }
}

#[cfg(test)]
mod test {
    use rules::HashMapRules;
    use state::{LSystem, new_rules_value};
    use interpret::TurtleCommand;
    use process::{LProcessor, ChunksProcessor};

    #[test]
    fn chunks_processing() {
        let mut rules = HashMapRules::new(); // algae rules
        rules.set_str('A', "AB", TurtleCommand::None);
        rules.set_str('B', "A", TurtleCommand::None);
        let expected_sizes = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597,
                              2584, 4181, 6765, 10946, 17711, 28657, 46368];
        let mut lsystem = LSystem::new_with_char("A", new_rules_value(rules));
        let mut processor = ChunksProcessor::new(4, 10_000).ok().unwrap();

        for n in 0..expected_sizes.len() {
            assert_eq!(lsystem.iteration(), n as u64);
            assert_eq!(lsystem.state().len(), expected_sizes[n]);
            lsystem = processor.iterate(&lsystem).ok().unwrap();
        }
    }
}
<commit_msg>fixed some warnings in 'ChunksProcessor'<commit_after>use std::sync::{Arc, Mutex};
use simple_parallel;

use state::LSystem;
use super::{LProcessor, SimpleProcessor};

/// Parallel processor dividing a state into chunks to be individually iterated
/// within a pool of threads.
pub struct ChunksProcessor {
    /// The number of symbols per full chunk.
    chunk_size: usize,
    /// The thread pool.
    pool: simple_parallel::Pool,
}

impl ChunksProcessor {
    /// Try and create a new 'ChunksProcessor' instance with the given parameters.
    /// Typical values:
    /// - max_tasks : number of CPU logical cores
    /// - chunks_size : between 100_000 and 1_000_000 symbols per chunk
    pub fn new(max_tasks: usize, chunks_size: usize) -> Result<ChunksProcessor, String> {
        if max_tasks == 0 {
            Err(format!("ChunksProcessor::new : invalid maximum tasks number ({})",
                        max_tasks))
        } else if chunks_size == 0 {
            Err(format!("ChunksProcessor::new : invalid chunks size ({})",
                        chunks_size))
        } else {
            Ok(ChunksProcessor {
                chunk_size: chunks_size,
                pool: simple_parallel::Pool::new(max_tasks),
            })
        }
    }
}

impl<S> LProcessor<S> for ChunksProcessor where S: Clone + Eq + Send + Sync
{
    // TODO : better error handling...
    fn iterate<'a>(&mut self, lsystem: &LSystem<'a, S>) -> Result<LSystem<'a, S>, String> {
        // Set-up
        let mut vec: Vec<Vec<S>> = Vec::new();
        let state_len = lsystem.state().len();
        if state_len == 0 {
            return Err(format!("cannot iterate an empty state"));
        }
        let rem = state_len % self.chunk_size;
        let chunks_number = state_len / self.chunk_size +
                            match rem {
            0 => 0,
            _ => 1,
        };
        for _ in 0..chunks_number {
            vec.push(Vec::new());
        }
        let sub_states = Arc::new(Mutex::new(vec));

        // Chunks processing
        let rules = lsystem.rules().clone();
        let errors = Mutex::new(String::new());
        let chunks_iter = lsystem.state().chunks(self.chunk_size);
        self.pool.for_(chunks_iter.enumerate(), |(n, chunk)| {
            let result: Vec<S> = match SimpleProcessor::iterate_slice(chunk, &rules) {
                Ok(v) => v,
                Err(why) => {
                    let mut error_lock = errors.lock().unwrap();
                    *error_lock = format!("{}\n{}", *error_lock, why);
                    Vec::new()
                }
            };
            let mut chunk_data = sub_states.lock().unwrap();
            chunk_data[n] = result;
        });

        // Error handling
        let error_lock = errors.lock().unwrap();
        if !error_lock.is_empty() {
            return Err(format!("ChunksProcessor : iteration error(s):\n{}", *error_lock));
        }

        // Final assembling
        let mut new_state_size = 0usize;
        let mut new_state: Vec<S> = Vec::new();
        let data = sub_states.lock().unwrap();
        for n in 0..chunks_number {
            let chunk_iterated = &data[n];
            new_state_size = match new_state_size.checked_add(chunk_iterated.len()) {
                Some(v) => v,
                None => {
                    return Err(format!("ChunksProcessor::iterate : usize overflow, state too big \
                                        for for Vec"))
                }
            };
            new_state.extend(chunk_iterated.iter().cloned());
        }
        Ok(LSystem::<S>::new(new_state, rules, Some(lsystem.iteration() + 1)))
    }
}

#[cfg(test)]
mod test {
    use rules::HashMapRules;
    use state::{LSystem, new_rules_value};
    use interpret::TurtleCommand;
    use process::{LProcessor, ChunksProcessor};

    #[test]
    fn chunks_processing() {
        let mut rules = HashMapRules::new(); // algae rules
        rules.set_str('A', "AB", TurtleCommand::None);
        rules.set_str('B', "A", TurtleCommand::None);
        let expected_sizes = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597,
                              2584, 4181, 6765, 10946, 17711, 28657, 46368];
        let mut lsystem = LSystem::new_with_char("A", new_rules_value(rules));
        let mut processor = ChunksProcessor::new(4, 10_000).ok().unwrap();

        for n in 0..expected_sizes.len() {
            assert_eq!(lsystem.iteration(), n as u64);
            assert_eq!(lsystem.state().len(), expected_sizes[n]);
            lsystem = processor.iterate(&lsystem).ok().unwrap();
        }
    }
}
<|endoftext|>


<commit_before>//! List owned projects
//!
//! https://docs.gitlab.com/ce/api/projects.html#list-owned-projects
//!
//! # List owned projects
//!
//! Get a list of projects which are owned by the authenticated user.
//!
//! ```text
//! GET /projects/owned
//! ```
//!
//! Parameters:
//!
//! | Attribute | Type | Required | Description |
//! | --------- | ---- | -------- | ----------- |
//! | `archived` | boolean | no | Limit by archived status |
//! | `visibility` | string | no | Limit by visibility `public`, `internal`, or `private` |
//! | `order_by` | string | no | Return projects ordered by `id`, `name`, `path`, `created_at`, `updated_at`, or `last_activity_at` fields. Default is `created_at` |
//! | `sort` | string | no | Return projects sorted in `asc` or `desc` order. Default is `desc` |
//! | `search` | string | no | Return list of authorized projects matching the search criteria |

use serde_json;
use serde_urlencoded;

use BuildQuery;
use gitlab::GitLab;
use Projects;
use projects::{OwnedProjectListerInternal, ListingOrderBy};

// impl GitLab {
//     pub fn projects_owned(&self, listing: Listing) -> Result<Projects, serde_json::Error> {
//         let query = listing.build_query();
//         self.get(&query)
//     }
// }

// #[derive(Debug, Copy, Clone)]
// pub enum ListingOrderBy {
//     Id,
//     Name,
//     Path,
//     CreatedAt,
//     UpdatedAt,
//     LastActivityAt,
// }

#[derive(Debug, Clone)]
pub struct ProjectsLister<'a> {
    gl: &'a ::GitLab,
    internal: OwnedProjectListerInternal,
}

impl<'a> ProjectsLister<'a> {
    pub fn new(gl: &'a ::GitLab) -> ProjectsLister {
        ProjectsLister {
            gl: gl,
            internal: OwnedProjectListerInternal {
                archived: None,
                visibility: None,
                order_by: None,
                sort: None,
                search: None,
            },
        }
    }

    pub fn archived(&'a mut self, archived: bool) -> &'a mut ProjectsLister {
        self.internal.archived = Some(archived);
        self
    }

    pub fn visibility(&'a mut self, visibility: ::ListingVisibility) -> &'a mut ProjectsLister {
        self.internal.visibility = Some(visibility);
        self
    }

    pub fn order_by(&'a mut self, order_by: ListingOrderBy) -> &'a mut ProjectsLister {
        self.internal.order_by = Some(order_by);
        self
    }

    pub fn sort(&'a mut self, sort: ::ListingSort) -> &'a mut ProjectsLister {
        self.internal.sort = Some(sort);
        self
    }

    pub fn search(&'a mut self, search: String) -> &'a mut ProjectsLister {
        self.internal.search = Some(search);
        self
    }

    /// Commit the lister: Query GitLab and return a list of projects.
    pub fn list(&self) -> Projects {
        // let query = serde_urlencoded::to_string(&self);
        let query = self.build_query();
        debug!("query: {:?}", query);

        let projects: Result<Projects, serde_json::Error> = self.gl.get(&query);

        projects.unwrap()
    }
}

impl<'a> BuildQuery for ProjectsLister<'a> {
    fn build_query(&self) -> String {

        let encoded = serde_urlencoded::to_string(&self.internal).unwrap();
        let mut query = String::from("projects/owned");
        if !encoded.is_empty() {
            query.push_str("?");
            query.push_str(&encoded);
        }

        query
    }
}

// #[derive(Default, Debug, Clone)]
// pub struct Listing {
//     /// Limit by archived status
//     archived: Option<bool>,
//     /// Limit by visibility.
//     visibility: Option<::ListingVisibility>,
//     /// Return requests ordered by. Default is `ListingOrderBy::CreatedAt`.
//     order_by: Option<ListingOrderBy>,
//     /// Return requests sorted. Default is `::ListingSort::Desc`.
//     sort: Option<::ListingSort>,
//     /// Return list of authorized projects matching the search criteria.
//     search: String,
// }

// #[allow(dead_code)]
// impl Listing {
//     pub fn new() -> Listing {
//         Default::default()
//     }
//     pub fn archived(&mut self, archived: bool) -> &mut Listing {
//         self.archived = Some(archived);
//         self
//     }
//     pub fn visibility(&mut self, visibility: ::ListingVisibility) -> &mut Listing {
//         self.visibility = Some(visibility);
//         self
//     }
//     pub fn order_by(&mut self, order_by: ListingOrderBy) -> &mut Listing {
//         self.order_by = Some(order_by);
//         self
//     }
//     fn sort(&mut self, sort: ::ListingSort) -> &mut Listing {
//         self.sort = Some(sort);
//         self
//     }
//     pub fn search(&mut self, search: String) -> &mut Listing {
//         self.search = search;
//         self
//     }
// }
//
//
// impl BuildQuery for Listing {
//     fn build_query(&self) -> String {
//
//         let mut query = String::from("projects/owned");
//
//         let amp_char = "&";
//         let none_char = "";
//         let mut split_char = &none_char;
//
//         // Append a "?" only if at least one of the `Option` is `Some(_)` or if
//         // strings contain something.
//         query.push_str(match (&self.archived,
//                               &self.visibility,
//                               &self.order_by,
//                               &self.sort,
//                               self.search.is_empty()) {
//             (&None, &None, &None, &None, true) => "",
//             _ => "?",
//         });
//
//         self.archived.map(|archived| {
//             query.push_str(split_char);
//             split_char = &amp_char;
//
//             if archived {
//                 query.push_str("archived=true")
//             } else {
//                 query.push_str("archived=false")
//             }
//         });
//
//         self.visibility.map(|visibility| {
//             query.push_str(split_char);
//             split_char = &amp_char;
//
//             query.push_str("visibility=");
//             query.push_str(match visibility {
//                 ::ListingVisibility::Public => "public",
//                 ::ListingVisibility::Internal => "internal",
//                 ::ListingVisibility::Private => "private",
//             });
//         });
//
//         self.order_by.map(|order_by| {
//             query.push_str(split_char);
//             split_char = &amp_char;
//
//             query.push_str("order_by=");
//             query.push_str(match order_by {
//                 ListingOrderBy::Id => "id",
//                 ListingOrderBy::Name => "name",
//                 ListingOrderBy::Path => "path",
//                 ListingOrderBy::CreatedAt => "created_at",
//                 ListingOrderBy::UpdatedAt => "updated_at",
//                 ListingOrderBy::LastActivityAt => "last_activity_at",
//             });
//         });
//
//         self.sort.map(|sort| {
//             query.push_str(split_char);
//             split_char = &amp_char;
//
//             query.push_str("sort=");
//             query.push_str(match sort {
//                 ::ListingSort::Asc => "asc",
//                 ::ListingSort::Desc => "desc",
//             });
//         });
//
//         if !self.search.is_empty() {
//             query.push_str(split_char);
//             // split_char = &amp_char;
//
//             query.push_str("search=");
//             query.push_str(&self.search);
//         }
//
//         query
//     }
// }

#[cfg(test)]
mod tests {
    use super::*;
    use BuildQuery;

    // #[test]
    // fn build_query_default() {
    //     let expected_string = "projects/owned";
    //     let listing: Listing = Default::default();
    //     let query = listing.build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned";
    //     let listing = Listing::new();
    //     let query = listing.build_query();
    //     assert_eq!(query, expected_string);
    // }
    //
    //
    // #[test]
    // fn build_query_archived() {
    //     let expected_string = "projects/owned?archived=true";
    //     let query = Listing::new().archived(true).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?archived=false";
    //     let query = Listing::new().archived(false).build_query();
    //     assert_eq!(query, expected_string);
    // }
    //
    //
    // #[test]
    // fn build_query_visibility() {
    //     let expected_string = "projects/owned?visibility=public";
    //     let query = Listing::new().visibility(::ListingVisibility::Public).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?visibility=internal";
    //     let query = Listing::new().visibility(::ListingVisibility::Internal).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?visibility=private";
    //     let query = Listing::new().visibility(::ListingVisibility::Private).build_query();
    //     assert_eq!(query, expected_string);
    // }
    //
    //
    // #[test]
    // fn build_query_order_by() {
    //     let expected_string = "projects/owned?order_by=id";
    //     let query = Listing::new().order_by(ListingOrderBy::Id).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?order_by=name";
    //     let query = Listing::new().order_by(ListingOrderBy::Name).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?order_by=path";
    //     let query = Listing::new().order_by(ListingOrderBy::Path).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?order_by=created_at";
    //     let query = Listing::new().order_by(ListingOrderBy::CreatedAt).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?order_by=updated_at";
    //     let query = Listing::new().order_by(ListingOrderBy::UpdatedAt).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?order_by=last_activity_at";
    //     let query = Listing::new().order_by(ListingOrderBy::LastActivityAt).build_query();
    //     assert_eq!(query, expected_string);
    // }
    //
    //
    // #[test]
    // fn build_query_sort() {
    //     let expected_string = "projects/owned?sort=asc";
    //     let query = Listing::new().sort(::ListingSort::Asc).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?sort=desc";
    //     let query = Listing::new().sort(::ListingSort::Desc).build_query();
    //     assert_eq!(query, expected_string);
    // }
    //
    //
    // #[test]
    // fn build_query_search() {
    //     let expected_string = "projects/owned?search=SearchPattern";
    //     let query = Listing::new().search(String::from("SearchPattern")).build_query();
    //     assert_eq!(query, expected_string);
    // }
    //
    //
    // #[test]
    // fn groups_build_query_multiple() {
    //     let expected_string = "projects/owned?archived=false&sort=asc";
    //     let query = Listing::new().archived(false).sort(::ListingSort::Asc).build_query();
    //     assert_eq!(query, expected_string);
    // }
}
<commit_msg>Cleanup old commented code<commit_after>//! List owned projects
//!
//! https://docs.gitlab.com/ce/api/projects.html#list-owned-projects
//!
//! # List owned projects
//!
//! Get a list of projects which are owned by the authenticated user.
//!
//! ```text
//! GET /projects/owned
//! ```
//!
//! Parameters:
//!
//! | Attribute | Type | Required | Description |
//! | --------- | ---- | -------- | ----------- |
//! | `archived` | boolean | no | Limit by archived status |
//! | `visibility` | string | no | Limit by visibility `public`, `internal`, or `private` |
//! | `order_by` | string | no | Return projects ordered by `id`, `name`, `path`, `created_at`, `updated_at`, or `last_activity_at` fields. Default is `created_at` |
//! | `sort` | string | no | Return projects sorted in `asc` or `desc` order. Default is `desc` |
//! | `search` | string | no | Return list of authorized projects matching the search criteria |

use serde_json;
use serde_urlencoded;

use BuildQuery;
use gitlab::GitLab;
use Projects;
use projects::{OwnedProjectListerInternal, ListingOrderBy};

#[derive(Debug, Clone)]
pub struct ProjectsLister<'a> {
    gl: &'a ::GitLab,
    internal: OwnedProjectListerInternal,
}

impl<'a> ProjectsLister<'a> {
    pub fn new(gl: &'a ::GitLab) -> ProjectsLister {
        ProjectsLister {
            gl: gl,
            internal: OwnedProjectListerInternal {
                archived: None,
                visibility: None,
                order_by: None,
                sort: None,
                search: None,
            },
        }
    }

    pub fn archived(&'a mut self, archived: bool) -> &'a mut ProjectsLister {
        self.internal.archived = Some(archived);
        self
    }

    pub fn visibility(&'a mut self, visibility: ::ListingVisibility) -> &'a mut ProjectsLister {
        self.internal.visibility = Some(visibility);
        self
    }

    pub fn order_by(&'a mut self, order_by: ListingOrderBy) -> &'a mut ProjectsLister {
        self.internal.order_by = Some(order_by);
        self
    }

    pub fn sort(&'a mut self, sort: ::ListingSort) -> &'a mut ProjectsLister {
        self.internal.sort = Some(sort);
        self
    }

    pub fn search(&'a mut self, search: String) -> &'a mut ProjectsLister {
        self.internal.search = Some(search);
        self
    }

    /// Commit the lister: Query GitLab and return a list of projects.
    pub fn list(&self) -> Projects {
        // let query = serde_urlencoded::to_string(&self);
        let query = self.build_query();
        debug!("query: {:?}", query);

        let projects: Result<Projects, serde_json::Error> = self.gl.get(&query);

        projects.unwrap()
    }
}

impl<'a> BuildQuery for ProjectsLister<'a> {
    fn build_query(&self) -> String {

        let encoded = serde_urlencoded::to_string(&self.internal).unwrap();
        let mut query = String::from("projects/owned");
        if !encoded.is_empty() {
            query.push_str("?");
            query.push_str(&encoded);
        }
        debug!("query: {}", query);

        query
    }
}

// impl BuildQuery for Listing {
//     fn build_query(&self) -> String {
//
//         let mut query = String::from("projects/owned");
//
//         let amp_char = "&";
//         let none_char = "";
//         let mut split_char = &none_char;
//
//         // Append a "?" only if at least one of the `Option` is `Some(_)` or if
//         // strings contain something.
//         query.push_str(match (&self.archived,
//                               &self.visibility,
//                               &self.order_by,
//                               &self.sort,
//                               self.search.is_empty()) {
//             (&None, &None, &None, &None, true) => "",
//             _ => "?",
//         });
//
//         self.archived.map(|archived| {
//             query.push_str(split_char);
//             split_char = &amp_char;
//
//             if archived {
//                 query.push_str("archived=true")
//             } else {
//                 query.push_str("archived=false")
//             }
//         });
//
//         self.visibility.map(|visibility| {
//             query.push_str(split_char);
//             split_char = &amp_char;
//
//             query.push_str("visibility=");
//             query.push_str(match visibility {
//                 ::ListingVisibility::Public => "public",
//                 ::ListingVisibility::Internal => "internal",
//                 ::ListingVisibility::Private => "private",
//             });
//         });
//
//         self.order_by.map(|order_by| {
//             query.push_str(split_char);
//             split_char = &amp_char;
//
//             query.push_str("order_by=");
//             query.push_str(match order_by {
//                 ListingOrderBy::Id => "id",
//                 ListingOrderBy::Name => "name",
//                 ListingOrderBy::Path => "path",
//                 ListingOrderBy::CreatedAt => "created_at",
//                 ListingOrderBy::UpdatedAt => "updated_at",
//                 ListingOrderBy::LastActivityAt => "last_activity_at",
//             });
//         });
//
//         self.sort.map(|sort| {
//             query.push_str(split_char);
//             split_char = &amp_char;
//
//             query.push_str("sort=");
//             query.push_str(match sort {
//                 ::ListingSort::Asc => "asc",
//                 ::ListingSort::Desc => "desc",
//             });
//         });
//
//         if !self.search.is_empty() {
//             query.push_str(split_char);
//             // split_char = &amp_char;
//
//             query.push_str("search=");
//             query.push_str(&self.search);
//         }
//
//         query
//     }
// }

#[cfg(test)]
mod tests {
    use super::*;
    use BuildQuery;

    // #[test]
    // fn build_query_default() {
    //     let expected_string = "projects/owned";
    //     let listing: Listing = Default::default();
    //     let query = listing.build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned";
    //     let listing = Listing::new();
    //     let query = listing.build_query();
    //     assert_eq!(query, expected_string);
    // }
    //
    //
    // #[test]
    // fn build_query_archived() {
    //     let expected_string = "projects/owned?archived=true";
    //     let query = Listing::new().archived(true).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?archived=false";
    //     let query = Listing::new().archived(false).build_query();
    //     assert_eq!(query, expected_string);
    // }
    //
    //
    // #[test]
    // fn build_query_visibility() {
    //     let expected_string = "projects/owned?visibility=public";
    //     let query = Listing::new().visibility(::ListingVisibility::Public).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?visibility=internal";
    //     let query = Listing::new().visibility(::ListingVisibility::Internal).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?visibility=private";
    //     let query = Listing::new().visibility(::ListingVisibility::Private).build_query();
    //     assert_eq!(query, expected_string);
    // }
    //
    //
    // #[test]
    // fn build_query_order_by() {
    //     let expected_string = "projects/owned?order_by=id";
    //     let query = Listing::new().order_by(ListingOrderBy::Id).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?order_by=name";
    //     let query = Listing::new().order_by(ListingOrderBy::Name).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?order_by=path";
    //     let query = Listing::new().order_by(ListingOrderBy::Path).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?order_by=created_at";
    //     let query = Listing::new().order_by(ListingOrderBy::CreatedAt).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?order_by=updated_at";
    //     let query = Listing::new().order_by(ListingOrderBy::UpdatedAt).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?order_by=last_activity_at";
    //     let query = Listing::new().order_by(ListingOrderBy::LastActivityAt).build_query();
    //     assert_eq!(query, expected_string);
    // }
    //
    //
    // #[test]
    // fn build_query_sort() {
    //     let expected_string = "projects/owned?sort=asc";
    //     let query = Listing::new().sort(::ListingSort::Asc).build_query();
    //     assert_eq!(query, expected_string);
    //
    //     let expected_string = "projects/owned?sort=desc";
    //     let query = Listing::new().sort(::ListingSort::Desc).build_query();
    //     assert_eq!(query, expected_string);
    // }
    //
    //
    // #[test]
    // fn build_query_search() {
    //     let expected_string = "projects/owned?search=SearchPattern";
    //     let query = Listing::new().search(String::from("SearchPattern")).build_query();
    //     assert_eq!(query, expected_string);
    // }
    //
    //
    // #[test]
    // fn groups_build_query_multiple() {
    //     let expected_string = "projects/owned?archived=false&sort=asc";
    //     let query = Listing::new().archived(false).sort(::ListingSort::Asc).build_query();
    //     assert_eq!(query, expected_string);
    // }
}
<|endoftext|>


<commit_before>//extern crate serde_json;
use rustc_serialize::json;

use std::error::Error;
use std::ffi::OsStr;
use std::fs;
use std::fs::File;
use std::io::{ BufReader, BufRead, Read };
use std::path::{ Path, PathBuf };
use std::str::FromStr;

use download;
use verify;

macro_rules! custom_try {
    ($x:expr) => (match $x {
        Ok(x) => x,
        Err(why) => return Err(format!("An error occured during package finding. {}", why)),
    });
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct Package {
    name: String,
    version: String,
    crc32: String,
    url: String,
    dependencies: Vec<Package>
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct PackageList {
    packages: Vec<Package>,
    version: i32
}

pub fn update_package_list(url: &str, path: &Path) -> Result<bool, String> {
    if (path.extension().is_some() &&
        path.extension().unwrap_or(OsStr::new("")) != ".json") ||
       (path.extension().is_none())
    {
        return Err(String::from(
            format!("Extension of package list is not .json: {}", path.to_str().unwrap_or("Invalid File"))
        ));
    }

    let mut path_temp = PathBuf::new();
    path_temp.push(path);
    path_temp.set_extension("json.tmp");

    if download::download_file(url, path_temp.as_path()).is_err() {
        return Err(String::from("Error occured while downloading package list"))
    }

    if verify::verify_file_crc32(&custom_try!(File::open(&path_temp))) ==
       verify::verify_file_crc32(&custom_try!(File::open(&path)))
    {
        fs::remove_file(path_temp);
        return Ok(false)
    } else {
        fs::remove_file(path);
        fs::rename(path_temp, path);
        return Ok(true)
    }
}

pub fn find_package(name: &str, path:&Path) -> Result<Vec<Package>, String> {
    let mut list = custom_try!(File::open(path));
    let mut reader = BufReader::new(list);
    let mut buffer = String::new();

    reader.read_to_string(&mut buffer);
    let package_list: PackageList = custom_try!(json::decode(&buffer));

    let filtered = package_list.packages
                    .into_iter()
                    .filter(|x| !x.name.contains(name))
                    .collect::<Vec<_>>();

    match filtered.len() {
        0 => Err(String::from("Package not found")),
        _ => Ok(filtered)
    }
}

pub fn download_and_find(name: &str, url:&str, path:&Path) -> Result<Vec<Package>, String>{
    if update_package_list(url, path).is_ok() {
        return find_package(name, path)
    } else {
        return Err(String::from("Error occured while downloading package list"))
    }
}
<commit_msg>Make variables of Package public<commit_after>//extern crate serde_json;
use rustc_serialize::json;

use std::error::Error;
use std::ffi::OsStr;
use std::fs;
use std::fs::File;
use std::io::{ BufReader, BufRead, Read };
use std::path::{ Path, PathBuf };
use std::str::FromStr;

use download;
use verify;

macro_rules! custom_try {
    ($x:expr) => (match $x {
        Ok(x) => x,
        Err(why) => return Err(format!("An error occured during package finding. {}", why)),
    });
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct Package {
    pub name: String,
    pub version: String,
    pub crc32: String,
    pub url: String,
    pub dependencies: Vec<Package>
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct PackageList {
    packages: Vec<Package>,
    version: i32
}

pub fn update_package_list(url: &str, path: &Path) -> Result<bool, String> {
    if (path.extension().is_some() &&
        path.extension().unwrap_or(OsStr::new("")) != ".json") ||
       (path.extension().is_none())
    {
        return Err(String::from(
            format!("Extension of package list is not .json: {}", path.to_str().unwrap_or("Invalid File"))
        ));
    }

    let mut path_temp = PathBuf::new();
    path_temp.push(path);
    path_temp.set_extension("json.tmp");

    if download::download_file(url, path_temp.as_path()).is_err() {
        return Err(String::from("Error occured while downloading package list"))
    }

    if verify::verify_file_crc32(&custom_try!(File::open(&path_temp))) ==
       verify::verify_file_crc32(&custom_try!(File::open(&path)))
    {
        fs::remove_file(path_temp);
        return Ok(false)
    } else {
        fs::remove_file(path);
        fs::rename(path_temp, path);
        return Ok(true)
    }
}

pub fn find_package(name: &str, path:&Path) -> Result<Vec<Package>, String> {
    let mut list = custom_try!(File::open(path));
    let mut reader = BufReader::new(list);
    let mut buffer = String::new();

    reader.read_to_string(&mut buffer);
    let package_list: PackageList = custom_try!(json::decode(&buffer));

    let filtered = package_list.packages
                    .into_iter()
                    .filter(|x| !x.name.contains(name))
                    .collect::<Vec<_>>();

    match filtered.len() {
        0 => Err(String::from("Package not found")),
        _ => Ok(filtered)
    }
}

pub fn download_and_find(name: &str, url:&str, path:&Path) -> Result<Vec<Package>, String>{
    if update_package_list(url, path).is_ok() {
        return find_package(name, path)
    } else {
        return Err(String::from("Error occured while downloading package list"))
    }
}
<|endoftext|>


<commit_before>//extern crate serde_json;
use rustc_serialize::json;

use std::error::Error;
use std::fs;
use std::fs::File;
use std::io::{ BufReader, BufRead, Read };
use std::path::{ Path, PathBuf };
use std::str::FromStr;

use download;
use verify;

macro_rules! custom_try {
    ($x:expr) => (match $x {
        Ok(x) => x,
        Err(why) => return Err(format!("An error occured during package finding. {}", why)),
    });
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct Package {
    name: String,
    version: String,
    crc32: String,
    url: String,
    dependencies: Vec<Package>
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct PackageList {
    packages: Vec<Package>,
    version: i32
}

pub fn update_package_list(url: &str, path: &Path) -> Result<bool, String> {
    if (path.extension().is_some() && path.extension().unwrap() != ".json") ||
       (path.extension().is_none())
    {
        return Err(String::from(
            format!("Extension of package list is not .json: {}", path.to_str().unwrap_or("Invalid File"))
        ));
    }

    let mut path_temp = PathBuf::new();
    path_temp.push(path);
    path_temp.set_extension("json.tmp");

    if download::download_file(url, path_temp.as_path()).is_err() {
        return Err(String::from("Error occured while downloading package list"))
    }

    if verify::verify_file_crc32(&custom_try!(File::open(&path_temp))) ==
       verify::verify_file_crc32(&custom_try!(File::open(&path)))
    {
        fs::remove_file(path_temp);
        return Ok(false)
    } else {
        fs::remove_file(path);
        fs::rename(path_temp, path);
        return Ok(true)
    }
}

pub fn find_package(name: &str, path:&Path) -> Result<Vec<Package>, String> {
    let mut list = custom_try!(File::open(path));
    let mut reader = BufReader::new(list);
    let mut buffer = String::new();

    reader.read_to_string(&mut buffer);
    let package_list: PackageList = custom_try!(json::decode(&buffer));

    let filtered = package_list.packages
                    .into_iter()
                    .filter(|x| !x.name.contains(name))
                    .collect::<Vec<_>>();

    match filtered.len() {
        0 => Err(String::from_str("Package not found")),
        _ => Ok(filtered)
    }
}
<commit_msg>Fix typo.<commit_after>//extern crate serde_json;
use rustc_serialize::json;

use std::error::Error;
use std::fs;
use std::fs::File;
use std::io::{ BufReader, BufRead, Read };
use std::path::{ Path, PathBuf };
use std::str::FromStr;

use download;
use verify;

macro_rules! custom_try {
    ($x:expr) => (match $x {
        Ok(x) => x,
        Err(why) => return Err(format!("An error occured during package finding. {}", why)),
    });
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct Package {
    name: String,
    version: String,
    crc32: String,
    url: String,
    dependencies: Vec<Package>
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct PackageList {
    packages: Vec<Package>,
    version: i32
}

pub fn update_package_list(url: &str, path: &Path) -> Result<bool, String> {
    if (path.extension().is_some() && path.extension().unwrap() != ".json") ||
       (path.extension().is_none())
    {
        return Err(String::from(
            format!("Extension of package list is not .json: {}", path.to_str().unwrap_or("Invalid File"))
        ));
    }

    let mut path_temp = PathBuf::new();
    path_temp.push(path);
    path_temp.set_extension("json.tmp");

    if download::download_file(url, path_temp.as_path()).is_err() {
        return Err(String::from("Error occured while downloading package list"))
    }

    if verify::verify_file_crc32(&custom_try!(File::open(&path_temp))) ==
       verify::verify_file_crc32(&custom_try!(File::open(&path)))
    {
        fs::remove_file(path_temp);
        return Ok(false)
    } else {
        fs::remove_file(path);
        fs::rename(path_temp, path);
        return Ok(true)
    }
}

pub fn find_package(name: &str, path:&Path) -> Result<Vec<Package>, String> {
    let mut list = custom_try!(File::open(path));
    let mut reader = BufReader::new(list);
    let mut buffer = String::new();

    reader.read_to_string(&mut buffer);
    let package_list: PackageList = custom_try!(json::decode(&buffer));

    let filtered = package_list.packages
                    .into_iter()
                    .filter(|x| !x.name.contains(name))
                    .collect::<Vec<_>>();

    match filtered.len() {
        0 => Err(String::from("Package not found")),
        _ => Ok(filtered)
    }
}
<|endoftext|>


<commit_before>//extern crate serde_json;
use rustc_serialize::json;

use std::error::Error;
use std::fs::File;
use std::io::{ BufReader, BufRead, Read };
use std::path::Path;
use std::str::FromStr;

use download;

macro_rules! custom_try {
    ($x:expr) => (match $x {
        Ok(x) => x,
        Err(why) => return Err(format!("An error occured during package finding. {}", why)),
    });
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct Package {
    name: String,
    version: String,
    crc32: String,
    url: String,
    dependencies: Vec<Package>
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct PackageList {
    packages: Vec<Package>,
    version: i32
}

pub fn update_package_list(url: &str, path: &Path) -> Result<bool, String> {
    let download_complete = download::download_file(url, path);
    if(download_complete.is_ok()) {
        //TODO: Return true when the package list is updated, false if not
    }
}

pub fn find_package(name: &str, path:&Path) -> Result<Vec<Package>, String> {
    let mut list = custom_try!(File::open(path));
    let mut reader = BufReader::new(list);
    let mut buffer = String::new();

    reader.read_to_string(&mut buffer);
    let package_list: PackageList = custom_try!(json::decode(&buffer));

    let filtered = package_list.packages
                    .into_iter()
                    .filter(|x| !x.name.contains(name))
                    .collect::<Vec<_>>();

    match filtered.len() {
        0 => Err(custom_try!(String::from_str("Package not found"))),
        _ => Ok(filtered)
    }
}
<commit_msg>Fix:Used custom_try in places it isn't supposed to<commit_after>//extern crate serde_json;
use rustc_serialize::json;

use std::error::Error;
use std::fs::File;
use std::io::{ BufReader, BufRead, Read };
use std::path::Path;
use std::str::FromStr;

use download;

macro_rules! custom_try {
    ($x:expr) => (match $x {
        Ok(x) => x,
        Err(why) => return Err(format!("An error occured during package finding. {}", why)),
    });
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct Package {
    name: String,
    version: String,
    crc32: String,
    url: String,
    dependencies: Vec<Package>
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct PackageList {
    packages: Vec<Package>,
    version: i32
}

pub fn update_package_list(url: &str, path: &Path) -> Result<bool, String> {
    let download_complete = download::download_file(url, path);
    if(download_complete.is_ok()) {
        //TODO: Return true when the package list is updated, false if not
    }
}

pub fn find_package(name: &str, path:&Path) -> Result<Vec<Package>, String> {
    let mut list = custom_try!(File::open(path));
    let mut reader = BufReader::new(list);
    let mut buffer = String::new();

    reader.read_to_string(&mut buffer);
    let package_list: PackageList = custom_try!(json::decode(&buffer));

    let filtered = package_list.packages
                    .into_iter()
                    .filter(|x| !x.name.contains(name))
                    .collect::<Vec<_>>();

    match filtered.len() {
        0 => Err(String::from_str("Package not found")),
        _ => Ok(filtered)
    }
}
<|endoftext|>


<commit_before>use nom::{
  be_u8, be_u16,
  IResult,
  ErrorCode, Err,
};

use frame::{
  ChannelAssignment, NumberType,
  Frame,
  Header, Footer,
};

use metadata::StreamInfo;
use utility::{crc8, crc16, to_u32};

pub fn frame_parser<'a>(input: &'a [u8], stream_info: &StreamInfo)
                        -> IResult<'a, &'a [u8], Frame> {
  let result = chain!(input,
    frame_header: apply!(header, stream_info) ~
    frame_footer: footer,
    || {
      Frame {
        header: frame_header,
        footer: frame_footer,
      }
    }
  );

  match result {
    IResult::Done(i, frame)   => {
      // All frame bytes before the crc-16
      let end         = (input.len() - i.len()) - 2;
      let Footer(crc) = frame.footer;

      if crc16(&input[0..end]) == crc {
        IResult::Done(i, frame)
      } else {
        IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
      }
    }
    IResult::Error(error)     => IResult::Error(error),
    IResult::Incomplete(need) => IResult::Incomplete(need),
  }
}

fn blocking_strategy(input: &[u8]) -> IResult<&[u8], bool> {
  match take!(input, 2) {
    IResult::Done(i, bytes)   => {
      let sync_code = ((bytes[0] as u16) << 6) +
                      ((bytes[1] as u16) >> 2);
      let is_valid  = ((bytes[1] >> 1) & 0b01) == 0;

      if sync_code == 0b11111111111110 && is_valid {
        let is_variable_block_size = (bytes[1] & 0b01) == 1;

        IResult::Done(i, is_variable_block_size)
      } else {
        IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
      }
    }
    IResult::Error(error)     => IResult::Error(error),
    IResult::Incomplete(need) => IResult::Incomplete(need),
  }
}

fn block_sample(input: &[u8]) -> IResult<&[u8], (u8, u8)> {
  match be_u8(input) {
    IResult::Done(i, byte)    => {
      let block_byte  = byte >> 4;
      let sample_byte = byte & 0x0f;
      let is_valid    = block_byte != 0b0000 && sample_byte != 0b1111;

      if is_valid {
        IResult::Done(i, (block_byte, sample_byte))
      } else {
        IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
      }
    }
    IResult::Error(error)     => IResult::Error(error),
    IResult::Incomplete(need) => IResult::Incomplete(need),
  }
}

fn channel_bits(input: &[u8]) -> IResult<&[u8], (ChannelAssignment, u8)> {
  match be_u8(input) {
    IResult::Done(i, byte)    => {
      let channel_byte       = byte >> 4;
      let channel_assignment = match channel_byte {
        0b0000...0b0111 => ChannelAssignment::Independent,
        0b1000          => ChannelAssignment::LeftSide,
        0b1001          => ChannelAssignment::RightSide,
        0b1010          => ChannelAssignment::MiddleSide,
        _               => ChannelAssignment::Independent,
      };
      let size_byte = (byte >> 1) & 0b0111;

      // Checks the validity of:
      //
      // * (4 bits) channel assignment
      // * (3 bits) sample size
      // * (1 bit) last bit
      //
      // All these checks are whether of not they are reserved and should
      // return an error if so.
      let is_valid = channel_byte < 0b1011 &&
                     (size_byte != 0b0011 && size_byte != 0b0111) &&
                     (byte & 0b01) == 0;

      if is_valid {
        IResult::Done(i, (channel_assignment, size_byte))
      } else {
        IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
      }
    }
    IResult::Error(error)     => IResult::Error(error),
    IResult::Incomplete(need) => IResult::Incomplete(need),
  }
}

fn utf8_size(input: &[u8], is_u64: bool)
             -> IResult<&[u8], Option<(usize, u8)>> {
  map!(input, be_u8, |utf8_header| {
    match utf8_header {
      0b00000000...0b01111111 => Some((0, utf8_header)),
      0b11000000...0b11011111 => Some((1, utf8_header & 0b00011111)),
      0b11100000...0b11101111 => Some((2, utf8_header & 0b00001111)),
      0b11110000...0b11110111 => Some((3, utf8_header & 0b00000111)),
      0b11111000...0b11111011 => Some((4, utf8_header & 0b00000011)),
      0b11111100...0b11111101 => Some((5, utf8_header & 0b00000001)),
      0b11111110              => if is_u64 { Some((6, 0)) } else { None },
      _                       => None,
    }
  })
}

fn number_type(input: &[u8], is_sample: bool,
               (size, value): (usize, u8))
               -> IResult<&[u8], NumberType> {
  let mut result   = value as u64;
  let mut is_error = false;

  match take!(input, size) {
    IResult::Done(i, bytes)   => {
      for i in 0..size {
        let byte = bytes[i] as u64;

        if byte >= 0b10000000 && byte <= 0b10111111 {
          result = (result << 6) + (byte & 0b00111111);
        } else {
          is_error = true;
          break;
        }
      }

      if is_error {
        IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
      } else if is_sample {
        IResult::Done(i, NumberType::Sample(result))
      } else {
        IResult::Done(i, NumberType::Frame(result as u32))
      }
    }
    IResult::Error(error)     => IResult::Error(error),
    IResult::Incomplete(need) => IResult::Incomplete(need),
  }
}

fn secondary_block_size(input: &[u8], block_byte: u8)
                        -> IResult<&[u8], Option<u32>> {
  match block_byte {
    0b0110 => opt!(input, map!(take!(1), to_u32)),
    0b0111 => opt!(input, map!(take!(2), to_u32)),
    _      => IResult::Done(input, None)
  }
}

fn secondary_sample_rate(input: &[u8], sample_byte: u8)
                        -> IResult<&[u8], Option<u32>> {
  match sample_byte {
    0b1100          => opt!(input, map!(take!(1), to_u32)),
    0b1101 | 0b1110 => opt!(input, map!(take!(2), to_u32)),
    _               => IResult::Done(input, None)
  }
}

pub fn header<'a>(input: &'a [u8], stream_info: &StreamInfo)
                  -> IResult<'a, &'a [u8], Header> {
  let result = chain!(input,
    is_variable_block_size: blocking_strategy ~
    tuple0: block_sample ~
    tuple1: channel_bits ~
    number_opt: apply!(utf8_size, is_variable_block_size) ~
    number_length: expr_opt!(number_opt) ~
    number: apply!(number_type, is_variable_block_size, number_length) ~
    alt_block_size: apply!(secondary_block_size, tuple0.0) ~
    alt_sample_rate: apply!(secondary_sample_rate, tuple0.1) ~
    crc: be_u8,
    || {
      let (block_byte, sample_byte)       = tuple0;
      let (channel_assignment, size_byte) = tuple1;

      let block_size = match block_byte {
        0b0001          => 192,
        0b0010...0b0101 => 576 * 2_u32.pow(block_byte as u32 - 2),
        0b0110 | 0b0111 => alt_block_size.unwrap() + 1,
        0b1000...0b1111 => 256 * 2_u32.pow(block_byte as u32 - 8),
        _               => unreachable!(),
      };

      let sample_rate = match sample_byte {
        0b0000 => stream_info.sample_rate,
        0b0001 => 88200,
        0b0010 => 176400,
        0b0011 => 192000,
        0b0100 => 8000,
        0b0101 => 16000,
        0b0110 => 22050,
        0b0111 => 24000,
        0b1000 => 32000,
        0b1001 => 44100,
        0b1010 => 48000,
        0b1011 => 96000,
        0b1100 => alt_sample_rate.unwrap() * 1000,
        0b1101 => alt_sample_rate.unwrap(),
        0b1110 => alt_sample_rate.unwrap() * 10,
        _      => unreachable!(),
      };

      let bits_per_sample = match size_byte {
        0b0000 => stream_info.bits_per_sample as usize,
        0b0001 => 8,
        0b0010 => 12,
        0b0100 => 16,
        0b0101 => 20,
        0b0110 => 24,
        _      => unreachable!(),
      };

      Header {
        block_size: block_size,
        sample_rate: sample_rate,
        channel_assignment: channel_assignment,
        bits_per_sample: bits_per_sample,
        number: number,
        crc: crc,
      }
    }
  );

  match result {
    IResult::Done(i, frame_header) => {
      // All header bytes before the crc-8
      let end = (input.len() - i.len()) - 1;

      if crc8(&input[0..end]) == frame_header.crc {
        IResult::Done(i, frame_header)
      } else {
        IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
      }
    }
    IResult::Error(error)          => IResult::Error(error),
    IResult::Incomplete(need)      => IResult::Incomplete(need),
  }
}

named!(pub footer <&[u8], Footer>, map!(be_u16, Footer));

#[cfg(test)]
mod tests {
  use super::*;
  use frame::{
    Header, Footer,
    ChannelAssignment, NumberType,
  };
  use metadata::StreamInfo;
  use nom::IResult;

  #[test]
  fn test_header() {
    let inputs   = [ &b"\xff\xf8\x53\x1c\xf0\x90\x80\x80\x2e"[..]
                   , &b"\xff\xf9\x7c\xa0\xfe\xbf\xbf\xbf\xbf\xbf\xbc\x01\xff\
                        \x01\x88"[..]
                   , &b"\xff\xf8\xc8\x72\x40\x19"[..]
                   ];
    let mut info = StreamInfo::new();
    let results  = [ IResult::Done(&[][..], Header {
                      block_size: 4608,
                      sample_rate: 192000,
                      channel_assignment: ChannelAssignment::Independent,
                      bits_per_sample: 24,
                      number: NumberType::Frame(65536),
                      crc: 0x2e,
                    })
                  , IResult::Done(&[][..], Header {
                      block_size: 512,
                      sample_rate: 1000,
                      channel_assignment: ChannelAssignment::MiddleSide,
                      bits_per_sample: 16,
                      number: NumberType::Sample(68719476732),
                      crc: 0x88,
                    })
                  , IResult::Done(&[][..], Header {
                      block_size: 4096,
                      sample_rate: 32000,
                      channel_assignment: ChannelAssignment::Independent,
                      bits_per_sample: 8,
                      number: NumberType::Frame(64),
                      crc: 0x19,
                    })
                  ];

    info.bits_per_sample = 16;

    assert_eq!(header(inputs[0], &info), results[0]);
    assert_eq!(header(inputs[1], &info), results[1]);
    assert_eq!(header(inputs[2], &info), results[2]);
  }

  #[test]
  fn test_footer() {
    let input  = b"\x03\xe8";
    let result = IResult::Done(&[][..], Footer(0x03e8));

    assert_eq!(footer(input), result);
  }
}
<commit_msg>Add number of channels from channel_assignment<commit_after>use nom::{
  be_u8, be_u16,
  IResult,
  ErrorCode, Err,
};

use frame::{
  ChannelAssignment, NumberType,
  Frame,
  Header, Footer,
};

use metadata::StreamInfo;
use utility::{crc8, crc16, to_u32};

pub fn frame_parser<'a>(input: &'a [u8], stream_info: &StreamInfo)
                        -> IResult<'a, &'a [u8], Frame> {
  let result = chain!(input,
    frame_header: apply!(header, stream_info) ~
    frame_footer: footer,
    || {
      Frame {
        header: frame_header,
        footer: frame_footer,
      }
    }
  );

  match result {
    IResult::Done(i, frame)   => {
      // All frame bytes before the crc-16
      let end         = (input.len() - i.len()) - 2;
      let Footer(crc) = frame.footer;

      if crc16(&input[0..end]) == crc {
        IResult::Done(i, frame)
      } else {
        IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
      }
    }
    IResult::Error(error)     => IResult::Error(error),
    IResult::Incomplete(need) => IResult::Incomplete(need),
  }
}

fn blocking_strategy(input: &[u8]) -> IResult<&[u8], bool> {
  match take!(input, 2) {
    IResult::Done(i, bytes)   => {
      let sync_code = ((bytes[0] as u16) << 6) +
                      ((bytes[1] as u16) >> 2);
      let is_valid  = ((bytes[1] >> 1) & 0b01) == 0;

      if sync_code == 0b11111111111110 && is_valid {
        let is_variable_block_size = (bytes[1] & 0b01) == 1;

        IResult::Done(i, is_variable_block_size)
      } else {
        IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
      }
    }
    IResult::Error(error)     => IResult::Error(error),
    IResult::Incomplete(need) => IResult::Incomplete(need),
  }
}

fn block_sample(input: &[u8]) -> IResult<&[u8], (u8, u8)> {
  match be_u8(input) {
    IResult::Done(i, byte)    => {
      let block_byte  = byte >> 4;
      let sample_byte = byte & 0x0f;
      let is_valid    = block_byte != 0b0000 && sample_byte != 0b1111;

      if is_valid {
        IResult::Done(i, (block_byte, sample_byte))
      } else {
        IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
      }
    }
    IResult::Error(error)     => IResult::Error(error),
    IResult::Incomplete(need) => IResult::Incomplete(need),
  }
}

fn channel_bits(input: &[u8]) -> IResult<&[u8], (ChannelAssignment, u8, u8)> {
  match be_u8(input) {
    IResult::Done(i, byte)    => {
      let mut channels       = 2;
      let channel_byte       = byte >> 4;
      let channel_assignment = match channel_byte {
        0b0000...0b0111 => {
          channels = channel_byte + 1;

          ChannelAssignment::Independent
        }
        0b1000          => ChannelAssignment::LeftSide,
        0b1001          => ChannelAssignment::RightSide,
        0b1010          => ChannelAssignment::MiddleSide,
        _               => ChannelAssignment::Independent,
      };
      let size_byte = (byte >> 1) & 0b0111;

      // Checks the validity of:
      //
      // * (4 bits) channel assignment
      // * (3 bits) sample size
      // * (1 bit) last bit
      //
      // All these checks are whether of not they are reserved and should
      // return an error if so.
      let is_valid = channel_byte < 0b1011 &&
                     (size_byte != 0b0011 && size_byte != 0b0111) &&
                     (byte & 0b01) == 0;

      if is_valid {
        IResult::Done(i, (channel_assignment, channels, size_byte))
      } else {
        IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
      }
    }
    IResult::Error(error)     => IResult::Error(error),
    IResult::Incomplete(need) => IResult::Incomplete(need),
  }
}

fn utf8_size(input: &[u8], is_u64: bool)
             -> IResult<&[u8], Option<(usize, u8)>> {
  map!(input, be_u8, |utf8_header| {
    match utf8_header {
      0b00000000...0b01111111 => Some((0, utf8_header)),
      0b11000000...0b11011111 => Some((1, utf8_header & 0b00011111)),
      0b11100000...0b11101111 => Some((2, utf8_header & 0b00001111)),
      0b11110000...0b11110111 => Some((3, utf8_header & 0b00000111)),
      0b11111000...0b11111011 => Some((4, utf8_header & 0b00000011)),
      0b11111100...0b11111101 => Some((5, utf8_header & 0b00000001)),
      0b11111110              => if is_u64 { Some((6, 0)) } else { None },
      _                       => None,
    }
  })
}

fn number_type(input: &[u8], is_sample: bool,
               (size, value): (usize, u8))
               -> IResult<&[u8], NumberType> {
  let mut result   = value as u64;
  let mut is_error = false;

  match take!(input, size) {
    IResult::Done(i, bytes)   => {
      for i in 0..size {
        let byte = bytes[i] as u64;

        if byte >= 0b10000000 && byte <= 0b10111111 {
          result = (result << 6) + (byte & 0b00111111);
        } else {
          is_error = true;
          break;
        }
      }

      if is_error {
        IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
      } else if is_sample {
        IResult::Done(i, NumberType::Sample(result))
      } else {
        IResult::Done(i, NumberType::Frame(result as u32))
      }
    }
    IResult::Error(error)     => IResult::Error(error),
    IResult::Incomplete(need) => IResult::Incomplete(need),
  }
}

fn secondary_block_size(input: &[u8], block_byte: u8)
                        -> IResult<&[u8], Option<u32>> {
  match block_byte {
    0b0110 => opt!(input, map!(take!(1), to_u32)),
    0b0111 => opt!(input, map!(take!(2), to_u32)),
    _      => IResult::Done(input, None)
  }
}

fn secondary_sample_rate(input: &[u8], sample_byte: u8)
                        -> IResult<&[u8], Option<u32>> {
  match sample_byte {
    0b1100          => opt!(input, map!(take!(1), to_u32)),
    0b1101 | 0b1110 => opt!(input, map!(take!(2), to_u32)),
    _               => IResult::Done(input, None)
  }
}

pub fn header<'a>(input: &'a [u8], stream_info: &StreamInfo)
                  -> IResult<'a, &'a [u8], Header> {
  let result = chain!(input,
    is_variable_block_size: blocking_strategy ~
    tuple0: block_sample ~
    tuple1: channel_bits ~
    number_opt: apply!(utf8_size, is_variable_block_size) ~
    number_length: expr_opt!(number_opt) ~
    number: apply!(number_type, is_variable_block_size, number_length) ~
    alt_block_size: apply!(secondary_block_size, tuple0.0) ~
    alt_sample_rate: apply!(secondary_sample_rate, tuple0.1) ~
    crc: be_u8,
    || {
      let (block_byte, sample_byte)       = tuple0;
      let (channel_assignment, size_byte) = tuple1;

      let block_size = match block_byte {
        0b0001          => 192,
        0b0010...0b0101 => 576 * 2_u32.pow(block_byte as u32 - 2),
        0b0110 | 0b0111 => alt_block_size.unwrap() + 1,
        0b1000...0b1111 => 256 * 2_u32.pow(block_byte as u32 - 8),
        _               => unreachable!(),
      };

      let sample_rate = match sample_byte {
        0b0000 => stream_info.sample_rate,
        0b0001 => 88200,
        0b0010 => 176400,
        0b0011 => 192000,
        0b0100 => 8000,
        0b0101 => 16000,
        0b0110 => 22050,
        0b0111 => 24000,
        0b1000 => 32000,
        0b1001 => 44100,
        0b1010 => 48000,
        0b1011 => 96000,
        0b1100 => alt_sample_rate.unwrap() * 1000,
        0b1101 => alt_sample_rate.unwrap(),
        0b1110 => alt_sample_rate.unwrap() * 10,
        _      => unreachable!(),
      };

      let bits_per_sample = match size_byte {
        0b0000 => stream_info.bits_per_sample as usize,
        0b0001 => 8,
        0b0010 => 12,
        0b0100 => 16,
        0b0101 => 20,
        0b0110 => 24,
        _      => unreachable!(),
      };

      Header {
        block_size: block_size,
        sample_rate: sample_rate,
        channel_assignment: channel_assignment,
        bits_per_sample: bits_per_sample,
        number: number,
        crc: crc,
      }
    }
  );

  match result {
    IResult::Done(i, frame_header) => {
      // All header bytes before the crc-8
      let end = (input.len() - i.len()) - 1;

      if crc8(&input[0..end]) == frame_header.crc {
        IResult::Done(i, frame_header)
      } else {
        IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
      }
    }
    IResult::Error(error)          => IResult::Error(error),
    IResult::Incomplete(need)      => IResult::Incomplete(need),
  }
}

named!(pub footer <&[u8], Footer>, map!(be_u16, Footer));

#[cfg(test)]
mod tests {
  use super::*;
  use frame::{
    Header, Footer,
    ChannelAssignment, NumberType,
  };
  use metadata::StreamInfo;
  use nom::IResult;

  #[test]
  fn test_header() {
    let inputs   = [ &b"\xff\xf8\x53\x1c\xf0\x90\x80\x80\x2e"[..]
                   , &b"\xff\xf9\x7c\xa0\xfe\xbf\xbf\xbf\xbf\xbf\xbc\x01\xff\
                        \x01\x88"[..]
                   , &b"\xff\xf8\xc8\x72\x40\x19"[..]
                   ];
    let mut info = StreamInfo::new();
    let results  = [ IResult::Done(&[][..], Header {
                      block_size: 4608,
                      sample_rate: 192000,
                      channel_assignment: ChannelAssignment::Independent,
                      bits_per_sample: 24,
                      number: NumberType::Frame(65536),
                      crc: 0x2e,
                    })
                  , IResult::Done(&[][..], Header {
                      block_size: 512,
                      sample_rate: 1000,
                      channel_assignment: ChannelAssignment::MiddleSide,
                      bits_per_sample: 16,
                      number: NumberType::Sample(68719476732),
                      crc: 0x88,
                    })
                  , IResult::Done(&[][..], Header {
                      block_size: 4096,
                      sample_rate: 32000,
                      channel_assignment: ChannelAssignment::Independent,
                      bits_per_sample: 8,
                      number: NumberType::Frame(64),
                      crc: 0x19,
                    })
                  ];

    info.bits_per_sample = 16;

    assert_eq!(header(inputs[0], &info), results[0]);
    assert_eq!(header(inputs[1], &info), results[1]);
    assert_eq!(header(inputs[2], &info), results[2]);
  }

  #[test]
  fn test_footer() {
    let input  = b"\x03\xe8";
    let result = IResult::Done(&[][..], Footer(0x03e8));

    assert_eq!(footer(input), result);
  }
}
<|endoftext|>