<commit_before>use quick_xml::se::{to_string, Serializer};
use quick_xml::writer::Writer;

use pretty_assertions::assert_eq;

use serde::{Serialize, Serializer as SerSerializer};

#[test]
fn serialize_bool() {
    let inputs = [(true, "true"), (false, "false")];

    for (src, should_be) in &inputs {
        let mut buffer = Vec::new();
        let mut ser = Serializer::new(&mut buffer);
        ser.serialize_bool(*src).unwrap();

        assert_eq!(String::from_utf8(buffer).unwrap(), *should_be);
    }
}

#[test]
fn serialize_struct() {
    #[derive(Serialize)]
    struct Person {
        name: String,
        age: u32,
    }

    let bob = Person {
        name: "Bob".to_string(),
        age: 42,
    };

    let mut buffer = Vec::new();
    let mut ser = Serializer::new(&mut buffer);
    bob.serialize(&mut ser).unwrap();

    assert_eq!(
        String::from_utf8(buffer).unwrap(),
        "<Person name=\"Bob\" age=\"42\"/>"
    );
}

#[test]
fn serialize_struct_value_number() {
    #[derive(Serialize)]
    struct Person {
        name: String,
        #[serde(rename = "$value")]
        age: u32,
    }

    let bob = Person {
        name: "Bob".to_string(),
        age: 42,
    };
    assert_eq!(to_string(&bob).unwrap(), "<Person name=\"Bob\">42</Person>");
}

#[test]
fn serialize_struct_value_string() {
    #[derive(Serialize)]
    struct Person {
        name: String,
        #[serde(rename = "$value")]
        age: String,
    }

    let bob = Person {
        name: "Bob".to_string(),
        age: "42".to_string(),
    };
    assert_eq!(to_string(&bob).unwrap(), "<Person name=\"Bob\">42</Person>");
}

#[test]
fn serialize_enum() {
    #[derive(Serialize)]
    #[allow(dead_code)]
    enum Node {
        Boolean(bool),
        Number(f64),
        String(String),
    }

    let mut buffer = Vec::new();
    let mut ser = Serializer::new(&mut buffer);
    let node = Node::Boolean(true);
    node.serialize(&mut ser).unwrap();

    assert_eq!(
        String::from_utf8(buffer).unwrap(),
        "<Boolean>true</Boolean>"
    );
}

#[test]
#[ignore]
fn serialize_a_list() {
    let inputs = vec![1, 2, 3, 4];

    let mut buffer = Vec::new();
    let mut ser = Serializer::new(&mut buffer);
    inputs.serialize(&mut ser).unwrap();

    println!("{}", String::from_utf8(buffer).unwrap());
    panic!();
}

#[derive(Serialize)]
struct Unit;

#[derive(Serialize)]
struct Newtype(bool);

#[derive(Serialize)]
struct Tuple(f32, &'static str);

#[derive(Serialize)]
struct Struct {
    float: f64,
    string: &'static str,
}

#[derive(Serialize)]
struct NestedStruct {
    nested: Nested,
    string: &'static str,
}

#[derive(Serialize)]
struct FlattenStruct {
    #[serde(flatten)]
    nested: Nested,
    string: &'static str,
}

#[derive(Serialize)]
struct Nested {
    float: f64,
}

#[derive(Serialize)]
enum ExternallyTagged {
    Unit,
    #[serde(rename = "$primitive=PrimitiveUnit")]
    PrimitiveUnit,
    Newtype(bool),
    Tuple(f64, &'static str),
    Struct {
        float: f64,
        string: &'static str,
    },
    Holder {
        nested: Nested,
        string: &'static str,
    },
    Flatten {
        #[serde(flatten)]
        nested: Nested,
        string: &'static str,
    },
}

#[derive(Serialize)]
#[serde(tag = "tag")]
enum InternallyTagged {
    Unit,
    /// Primitives (such as `bool`) are not supported by the serde in the internally tagged mode
    Newtype(Nested),
    // Tuple(f64, &'static str),// Tuples are not supported in the internally tagged mode
    Struct {
        float: f64,
        string: &'static str,
    },
    Holder {
        nested: Nested,
        string: &'static str,
    },
    Flatten {
        #[serde(flatten)]
        nested: Nested,
        string: &'static str,
    },
}

#[derive(Serialize)]
#[serde(tag = "tag", content = "content")]
enum AdjacentlyTagged {
    Unit,
    Newtype(bool),
    Tuple(f64, &'static str),
    Struct {
        float: f64,
        string: &'static str,
    },
    Holder {
        nested: Nested,
        string: &'static str,
    },
    Flatten {
        #[serde(flatten)]
        nested: Nested,
        string: &'static str,
    },
}

#[derive(Serialize)]
#[serde(untagged)]
enum Untagged {
    Unit,
    Newtype(bool),
    Tuple(f64, &'static str),
    Struct {
        float: f64,
        string: &'static str,
    },
    Holder {
        nested: Nested,
        string: &'static str,
    },
    Flatten {
        #[serde(flatten)]
        nested: Nested,
        string: &'static str,
    },
}

mod with_root {
    use super::*;
    use pretty_assertions::assert_eq;

    macro_rules! serialize_as {
        ($name:ident: $data:expr => $expected:literal) => {
            #[test]
            fn $name() {
                let mut buffer = Vec::new();
                let mut ser = Serializer::with_root(Writer::new(&mut buffer), Some("root"));

                $data.serialize(&mut ser).unwrap();
                assert_eq!(String::from_utf8(buffer).unwrap(), $expected);
            }
        };
    }

    serialize_as!(unit:
        Unit
        => "<root/>");
    serialize_as!(newtype:
        Newtype(true)
        => "<root>true</root>");
    serialize_as!(tuple:
        (42.0, "answer")
        => "<root>42</root><root>answer</root>");
    serialize_as!(tuple_struct:
        Tuple(42.0, "answer")
        => "<root>42</root><root>answer</root>");
    serialize_as!(struct_:
        Struct {
            float: 42.0,
            string: "answer"
        }
        => r#"<root float="42" string="answer"/>"#);
    serialize_as!(nested_struct:
        NestedStruct {
            nested: Nested { float: 42.0 },
            string: "answer",
        }
        => r#"<root string="answer"><nested float="42"/></root>"#);
    serialize_as!(flatten_struct:
        FlattenStruct {
            nested: Nested { float: 42.0 },
            string: "answer",
        }
        => r#"<root><float>42</float><string>answer</string></root>"#);

    mod enum_ {
        use super::*;

        mod externally_tagged {
            use super::*;
            use pretty_assertions::assert_eq;

            serialize_as!(unit:
                ExternallyTagged::Unit
                => "<Unit/>");
            serialize_as!(primitive_unit:
                ExternallyTagged::PrimitiveUnit
                => "PrimitiveUnit");
            serialize_as!(newtype:
                ExternallyTagged::Newtype(true)
                => "<Newtype>true</Newtype>");
            serialize_as!(tuple_struct:
                ExternallyTagged::Tuple(42.0, "answer")
                => "<Tuple>42</Tuple><Tuple>answer</Tuple>");
            serialize_as!(struct_:
                ExternallyTagged::Struct {
                    float: 42.0,
                    string: "answer",
                }
                => r#"<Struct float="42" string="answer"/>"#);
            serialize_as!(nested_struct:
                ExternallyTagged::Holder {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<Holder string="answer"><nested float="42"/></Holder>"#);
            serialize_as!(flatten_struct:
                ExternallyTagged::Flatten {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<Flatten><float>42</float><string>answer</string></Flatten>"#);
        }

        mod internally_tagged {
            use super::*;
            use pretty_assertions::assert_eq;

            serialize_as!(unit:
                InternallyTagged::Unit
                => r#"<root tag="Unit"/>"#);
            serialize_as!(newtype:
                InternallyTagged::Newtype(Nested { float: 4.2 })
                => r#"<root tag="Newtype" float="4.2"/>"#);
            serialize_as!(struct_:
                InternallyTagged::Struct {
                    float: 42.0,
                    string: "answer",
                }
                => r#"<root tag="Struct" float="42" string="answer"/>"#);
            serialize_as!(nested_struct:
                InternallyTagged::Holder {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<root tag="Holder" string="answer"><nested float="42"/></root>"#);
            serialize_as!(flatten_struct:
                InternallyTagged::Flatten {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<root><tag>Flatten</tag><float>42</float><string>answer</string></root>"#);
        }

        mod adjacently_tagged {
            use super::*;
            use pretty_assertions::assert_eq;

            serialize_as!(unit:
                AdjacentlyTagged::Unit
                => r#"<root tag="Unit"/>"#);
            serialize_as!(newtype:
                AdjacentlyTagged::Newtype(true)
                => r#"<root tag="Newtype" content="true"/>"#);
            serialize_as!(tuple_struct:
                AdjacentlyTagged::Tuple(42.0, "answer")
                => r#"<root tag="Tuple"><content>42</content><content>answer</content></root>"#);
            serialize_as!(struct_:
                AdjacentlyTagged::Struct {
                    float: 42.0,
                    string: "answer",
                }
                => r#"<root tag="Struct"><content float="42" string="answer"/></root>"#);
            serialize_as!(nested_struct:
                AdjacentlyTagged::Holder {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<root tag="Holder"><content string="answer"><nested float="42"/></content></root>"#);
            serialize_as!(flatten_struct:
                AdjacentlyTagged::Flatten {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<root tag="Flatten"><content><float>42</float><string>answer</string></content></root>"#);
        }

        mod untagged {
            use super::*;
            use pretty_assertions::assert_eq;

            serialize_as!(unit:
                Untagged::Unit
                // Unit variant consists just from the tag, and because tags
                // are not written in untagged mode, nothing is written
                => "");
            serialize_as!(newtype:
                Untagged::Newtype(true)
                => "true");
            serialize_as!(tuple_struct:
                Untagged::Tuple(42.0, "answer")
                => "<root>42</root><root>answer</root>");
            serialize_as!(struct_:
                Untagged::Struct {
                    float: 42.0,
                    string: "answer",
                }
                => r#"<root float="42" string="answer"/>"#);
            serialize_as!(nested_struct:
                Untagged::Holder {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<root string="answer"><nested float="42"/></root>"#);
            serialize_as!(flatten_struct:
                Untagged::Flatten {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<root><float>42</float><string>answer</string></root>"#);
        }
    }
}
<commit_msg>Add a special cases of structs: Empty and with `$value` field<commit_after>use quick_xml::se::{to_string, Serializer};
use quick_xml::writer::Writer;

use pretty_assertions::assert_eq;

use serde::{Serialize, Serializer as SerSerializer};

#[test]
fn serialize_bool() {
    let inputs = [(true, "true"), (false, "false")];

    for (src, should_be) in &inputs {
        let mut buffer = Vec::new();
        let mut ser = Serializer::new(&mut buffer);
        ser.serialize_bool(*src).unwrap();

        assert_eq!(String::from_utf8(buffer).unwrap(), *should_be);
    }
}

#[test]
fn serialize_struct() {
    #[derive(Serialize)]
    struct Person {
        name: String,
        age: u32,
    }

    let bob = Person {
        name: "Bob".to_string(),
        age: 42,
    };

    let mut buffer = Vec::new();
    let mut ser = Serializer::new(&mut buffer);
    bob.serialize(&mut ser).unwrap();

    assert_eq!(
        String::from_utf8(buffer).unwrap(),
        "<Person name=\"Bob\" age=\"42\"/>"
    );
}

#[test]
fn serialize_struct_value_number() {
    #[derive(Serialize)]
    struct Person {
        name: String,
        #[serde(rename = "$value")]
        age: u32,
    }

    let bob = Person {
        name: "Bob".to_string(),
        age: 42,
    };
    assert_eq!(to_string(&bob).unwrap(), "<Person name=\"Bob\">42</Person>");
}

#[test]
fn serialize_struct_value_string() {
    #[derive(Serialize)]
    struct Person {
        name: String,
        #[serde(rename = "$value")]
        age: String,
    }

    let bob = Person {
        name: "Bob".to_string(),
        age: "42".to_string(),
    };
    assert_eq!(to_string(&bob).unwrap(), "<Person name=\"Bob\">42</Person>");
}

#[test]
fn serialize_enum() {
    #[derive(Serialize)]
    #[allow(dead_code)]
    enum Node {
        Boolean(bool),
        Number(f64),
        String(String),
    }

    let mut buffer = Vec::new();
    let mut ser = Serializer::new(&mut buffer);
    let node = Node::Boolean(true);
    node.serialize(&mut ser).unwrap();

    assert_eq!(
        String::from_utf8(buffer).unwrap(),
        "<Boolean>true</Boolean>"
    );
}

#[test]
#[ignore]
fn serialize_a_list() {
    let inputs = vec![1, 2, 3, 4];

    let mut buffer = Vec::new();
    let mut ser = Serializer::new(&mut buffer);
    inputs.serialize(&mut ser).unwrap();

    println!("{}", String::from_utf8(buffer).unwrap());
    panic!();
}

#[derive(Serialize)]
struct Unit;

#[derive(Serialize)]
struct Newtype(bool);

#[derive(Serialize)]
struct Tuple(f32, &'static str);

#[derive(Serialize)]
struct Struct {
    float: f64,
    string: &'static str,
}

#[derive(Serialize)]
struct NestedStruct {
    nested: Nested,
    string: &'static str,
}

#[derive(Serialize)]
struct FlattenStruct {
    #[serde(flatten)]
    nested: Nested,
    string: &'static str,
}

#[derive(Serialize)]
struct Nested {
    float: f64,
}

#[derive(Serialize)]
struct Empty {}

#[derive(Serialize)]
struct Value {
    #[serde(rename = "$value")]
    float: f64,
    string: &'static str,
}

#[derive(Serialize)]
enum ExternallyTagged {
    Unit,
    #[serde(rename = "$primitive=PrimitiveUnit")]
    PrimitiveUnit,
    Newtype(bool),
    Tuple(f64, &'static str),
    Struct {
        float: f64,
        string: &'static str,
    },
    Holder {
        nested: Nested,
        string: &'static str,
    },
    Flatten {
        #[serde(flatten)]
        nested: Nested,
        string: &'static str,
    },
    Empty {},
    Value {
        #[serde(rename = "$value")]
        float: f64,
        string: &'static str,
    },
}

#[derive(Serialize)]
#[serde(tag = "tag")]
enum InternallyTagged {
    Unit,
    /// Primitives (such as `bool`) are not supported by the serde in the internally tagged mode
    Newtype(Nested),
    // Tuple(f64, &'static str),// Tuples are not supported in the internally tagged mode
    Struct {
        float: f64,
        string: &'static str,
    },
    Holder {
        nested: Nested,
        string: &'static str,
    },
    Flatten {
        #[serde(flatten)]
        nested: Nested,
        string: &'static str,
    },
    Empty {},
    Value {
        #[serde(rename = "$value")]
        float: f64,
        string: &'static str,
    },
}

#[derive(Serialize)]
#[serde(tag = "tag", content = "content")]
enum AdjacentlyTagged {
    Unit,
    Newtype(bool),
    Tuple(f64, &'static str),
    Struct {
        float: f64,
        string: &'static str,
    },
    Holder {
        nested: Nested,
        string: &'static str,
    },
    Flatten {
        #[serde(flatten)]
        nested: Nested,
        string: &'static str,
    },
    Empty {},
    Value {
        #[serde(rename = "$value")]
        float: f64,
        string: &'static str,
    },
}

#[derive(Serialize)]
#[serde(untagged)]
enum Untagged {
    Unit,
    Newtype(bool),
    Tuple(f64, &'static str),
    Struct {
        float: f64,
        string: &'static str,
    },
    Holder {
        nested: Nested,
        string: &'static str,
    },
    Flatten {
        #[serde(flatten)]
        nested: Nested,
        string: &'static str,
    },
    Empty {},
    Value {
        #[serde(rename = "$value")]
        float: f64,
        string: &'static str,
    },
}

mod with_root {
    use super::*;
    use pretty_assertions::assert_eq;

    macro_rules! serialize_as {
        ($name:ident: $data:expr => $expected:literal) => {
            #[test]
            fn $name() {
                let mut buffer = Vec::new();
                let mut ser = Serializer::with_root(Writer::new(&mut buffer), Some("root"));

                $data.serialize(&mut ser).unwrap();
                assert_eq!(String::from_utf8(buffer).unwrap(), $expected);
            }
        };
    }

    serialize_as!(unit:
        Unit
        => "<root/>");
    serialize_as!(newtype:
        Newtype(true)
        => "<root>true</root>");
    serialize_as!(tuple:
        (42.0, "answer")
        => "<root>42</root><root>answer</root>");
    serialize_as!(tuple_struct:
        Tuple(42.0, "answer")
        => "<root>42</root><root>answer</root>");
    serialize_as!(struct_:
        Struct {
            float: 42.0,
            string: "answer"
        }
        => r#"<root float="42" string="answer"/>"#);
    serialize_as!(nested_struct:
        NestedStruct {
            nested: Nested { float: 42.0 },
            string: "answer",
        }
        => r#"<root string="answer"><nested float="42"/></root>"#);
    serialize_as!(flatten_struct:
        FlattenStruct {
            nested: Nested { float: 42.0 },
            string: "answer",
        }
        => r#"<root><float>42</float><string>answer</string></root>"#);
    serialize_as!(empty_struct:
        Empty {}
        => "<root/>");
    serialize_as!(value:
        Value {
            float: 42.0,
            string: "answer"
        }
        => r#"<root string="answer">42</root>"#);

    mod enum_ {
        use super::*;

        mod externally_tagged {
            use super::*;
            use pretty_assertions::assert_eq;

            serialize_as!(unit:
                ExternallyTagged::Unit
                => "<Unit/>");
            serialize_as!(primitive_unit:
                ExternallyTagged::PrimitiveUnit
                => "PrimitiveUnit");
            serialize_as!(newtype:
                ExternallyTagged::Newtype(true)
                => "<Newtype>true</Newtype>");
            serialize_as!(tuple_struct:
                ExternallyTagged::Tuple(42.0, "answer")
                => "<Tuple>42</Tuple><Tuple>answer</Tuple>");
            serialize_as!(struct_:
                ExternallyTagged::Struct {
                    float: 42.0,
                    string: "answer",
                }
                => r#"<Struct float="42" string="answer"/>"#);
            serialize_as!(nested_struct:
                ExternallyTagged::Holder {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<Holder string="answer"><nested float="42"/></Holder>"#);
            serialize_as!(flatten_struct:
                ExternallyTagged::Flatten {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<Flatten><float>42</float><string>answer</string></Flatten>"#);
            serialize_as!(empty_struct:
                ExternallyTagged::Empty {}
                => "<Empty/>");
            serialize_as!(value:
                ExternallyTagged::Value {
                    float: 42.0,
                    string: "answer"
                }
                => r#"<Value string="answer">42</Value>"#);
        }

        mod internally_tagged {
            use super::*;
            use pretty_assertions::assert_eq;

            serialize_as!(unit:
                InternallyTagged::Unit
                => r#"<root tag="Unit"/>"#);
            serialize_as!(newtype:
                InternallyTagged::Newtype(Nested { float: 4.2 })
                => r#"<root tag="Newtype" float="4.2"/>"#);
            serialize_as!(struct_:
                InternallyTagged::Struct {
                    float: 42.0,
                    string: "answer",
                }
                => r#"<root tag="Struct" float="42" string="answer"/>"#);
            serialize_as!(nested_struct:
                InternallyTagged::Holder {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<root tag="Holder" string="answer"><nested float="42"/></root>"#);
            serialize_as!(flatten_struct:
                InternallyTagged::Flatten {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<root><tag>Flatten</tag><float>42</float><string>answer</string></root>"#);
            serialize_as!(empty_struct:
                InternallyTagged::Empty {}
                => r#"<root tag="Empty"/>"#);
            serialize_as!(value:
                InternallyTagged::Value {
                    float: 42.0,
                    string: "answer"
                }
                => r#"<root tag="Value" string="answer">42</root>"#);
        }

        mod adjacently_tagged {
            use super::*;
            use pretty_assertions::assert_eq;

            serialize_as!(unit:
                AdjacentlyTagged::Unit
                => r#"<root tag="Unit"/>"#);
            serialize_as!(newtype:
                AdjacentlyTagged::Newtype(true)
                => r#"<root tag="Newtype" content="true"/>"#);
            serialize_as!(tuple_struct:
                AdjacentlyTagged::Tuple(42.0, "answer")
                => r#"<root tag="Tuple"><content>42</content><content>answer</content></root>"#);
            serialize_as!(struct_:
                AdjacentlyTagged::Struct {
                    float: 42.0,
                    string: "answer",
                }
                => r#"<root tag="Struct"><content float="42" string="answer"/></root>"#);
            serialize_as!(nested_struct:
                AdjacentlyTagged::Holder {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<root tag="Holder"><content string="answer"><nested float="42"/></content></root>"#);
            serialize_as!(flatten_struct:
                AdjacentlyTagged::Flatten {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<root tag="Flatten"><content><float>42</float><string>answer</string></content></root>"#);
            serialize_as!(empty_struct:
                AdjacentlyTagged::Empty {}
                => r#"<root tag="Empty"><content/></root>"#);
            serialize_as!(value:
                AdjacentlyTagged::Value {
                    float: 42.0,
                    string: "answer",
                }
                => r#"<root tag="Value"><content string="answer">42</content></root>"#);
        }

        mod untagged {
            use super::*;
            use pretty_assertions::assert_eq;

            serialize_as!(unit:
                Untagged::Unit
                // Unit variant consists just from the tag, and because tags
                // are not written in untagged mode, nothing is written
                => "");
            serialize_as!(newtype:
                Untagged::Newtype(true)
                => "true");
            serialize_as!(tuple_struct:
                Untagged::Tuple(42.0, "answer")
                => "<root>42</root><root>answer</root>");
            serialize_as!(struct_:
                Untagged::Struct {
                    float: 42.0,
                    string: "answer",
                }
                => r#"<root float="42" string="answer"/>"#);
            serialize_as!(nested_struct:
                Untagged::Holder {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<root string="answer"><nested float="42"/></root>"#);
            serialize_as!(flatten_struct:
                Untagged::Flatten {
                    nested: Nested { float: 42.0 },
                    string: "answer",
                }
                => r#"<root><float>42</float><string>answer</string></root>"#);
            serialize_as!(empty_struct:
                Untagged::Empty {}
                => "<root/>");
            serialize_as!(value:
                Untagged::Value {
                    float: 42.0,
                    string: "answer"
                }
                => r#"<root string="answer">42</root>"#);
        }
    }
}
<|endoftext|>


<commit_before>extern crate toml;

use std::path::PathBuf;
use super::util;
use std::error::Error;
//[replay]
//browser = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
//url = "localhost"
//port = "8000"
#[derive(Deserialize, Debug)]
pub struct ScaiiConfig {
    replay: Option<ReplayConfig>,
}
#[derive(Deserialize, Debug)]
struct ReplayConfig {
    #[serde(default = "default_browser")]
    browser: String,
    #[serde(default = "default_url")]
    url: String,
    #[serde(default = "default_port")]
    port: String,
}

#[cfg(target_os = "windows")]
fn default_browser() -> String {
    "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe".to_string()
}
#[cfg(target_os = "macos")]
fn default_browser() -> String {
    "open".to_string(); // will open url in safari
}
#[cfg(target_os = "linux")]
fn default_browser() -> String {
    "/usr/bin/chrome".to_string()
}

fn default_url() -> String {
    "localhost".to_string()
}

fn default_port() -> String {
    "8000".to_string()
}

#[allow(unused_assignments)]
pub fn load_scaii_config() -> ScaiiConfig {
    use std::fs::File;
    use std::io::prelude::*;
    // create the path to cfg.toml
    let scaii_root_result = util::get_scaii_root();
    let mut config_file_pathbuf: PathBuf = PathBuf::new();
    match scaii_root_result {
        Ok(root) => {
            config_file_pathbuf = root;
        }
        Err(_) => {
            panic!("Could not determine SCAII root directory while loading config file");
        }
    }
    config_file_pathbuf.push("cfg.toml");
    // try loading the cfg.toml file
    let file_open_result = File::open(config_file_pathbuf.as_path());
    let default_scaii_config = get_default_scaii_config();
    match file_open_result {
        Ok(mut config_file) => {
            // read the contents
            let mut config_data = String::new();
            let read_result = config_file.read_to_string(&mut config_data);
            match read_result {
                Ok(_) => {}
                //Ok(_) => { return default_scaii_config ;},
                Err(_) => {
                    println!(
                        "Problem reading data from config file {:?}.  Will try default values.",
                        config_file_pathbuf.as_path()
                    );
                    return default_scaii_config;
                }
            }
            let scaii_config_parse_result = toml::from_str(&config_data);

            match scaii_config_parse_result {
                Ok(parsed_scaii_config) => {
                    return parsed_scaii_config;
                }
                Err(error) => {
                    println!(
                        "Problem parsing data from config file {:?}.  Will try default values. {:?}",
                        config_file_pathbuf.as_path(),
                        error.description()
                    );
                    return default_scaii_config;
                }
            }
        }
        Err(error) => {
            println!(
                "config file {:?} not found.  Will use default values. {:?}",
                config_file_pathbuf.as_path(),
                error
            );
            default_scaii_config
        }
    }
}

fn get_default_scaii_config() -> ScaiiConfig {
    ScaiiConfig {
        replay: Some(ReplayConfig {
            browser: default_browser(),
            url: default_url(),
            port: default_port(),
        }),
    }
}

impl ScaiiConfig {
    pub fn get_replay_url(&mut self) -> String {
        match &self.replay {
            &None => default_url(),
            &Some(ref replay) => replay.url.clone(),
        }
    }

    pub fn get_replay_port(&mut self) -> String {
        match &self.replay {
            &None => default_port(),
            &Some(ref replay) => replay.port.clone(),
        }
    }

    pub fn get_replay_browser(&mut self) -> String {
        match &self.replay {
            &None => default_browser(),
            &Some(ref replay) => replay.browser.clone(),
        }
    }

    pub fn get_full_replay_http_url(&mut self) -> String {
        let url = self.get_replay_url();
        let port = self.get_replay_port();
        return format!("http://{}:{}", url, port);
    }
}
<commit_msg>Removed semicolon. Unable to build in MacOS without this<commit_after>extern crate toml;

use std::path::PathBuf;
use super::util;
use std::error::Error;
//[replay]
//browser = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
//url = "localhost"
//port = "8000"
#[derive(Deserialize, Debug)]
pub struct ScaiiConfig {
    replay: Option<ReplayConfig>,
}
#[derive(Deserialize, Debug)]
struct ReplayConfig {
    #[serde(default = "default_browser")]
    browser: String,
    #[serde(default = "default_url")]
    url: String,
    #[serde(default = "default_port")]
    port: String,
}

#[cfg(target_os = "windows")]
fn default_browser() -> String {
    "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe".to_string()
}
#[cfg(target_os = "macos")]
fn default_browser() -> String {
    "open".to_string() // will open url in safari
}
#[cfg(target_os = "linux")]
fn default_browser() -> String {
    "/usr/bin/chrome".to_string()
}

fn default_url() -> String {
    "localhost".to_string()
}

fn default_port() -> String {
    "8000".to_string()
}

#[allow(unused_assignments)]
pub fn load_scaii_config() -> ScaiiConfig {
    use std::fs::File;
    use std::io::prelude::*;
    // create the path to cfg.toml
    let scaii_root_result = util::get_scaii_root();
    let mut config_file_pathbuf: PathBuf = PathBuf::new();
    match scaii_root_result {
        Ok(root) => {
            config_file_pathbuf = root;
        }
        Err(_) => {
            panic!("Could not determine SCAII root directory while loading config file");
        }
    }
    config_file_pathbuf.push("cfg.toml");
    // try loading the cfg.toml file
    let file_open_result = File::open(config_file_pathbuf.as_path());
    let default_scaii_config = get_default_scaii_config();
    match file_open_result {
        Ok(mut config_file) => {
            // read the contents
            let mut config_data = String::new();
            let read_result = config_file.read_to_string(&mut config_data);
            match read_result {
                Ok(_) => {}
                //Ok(_) => { return default_scaii_config ;},
                Err(_) => {
                    println!(
                        "Problem reading data from config file {:?}.  Will try default values.",
                        config_file_pathbuf.as_path()
                    );
                    return default_scaii_config;
                }
            }
            let scaii_config_parse_result = toml::from_str(&config_data);

            match scaii_config_parse_result {
                Ok(parsed_scaii_config) => {
                    return parsed_scaii_config;
                }
                Err(error) => {
                    println!(
                        "Problem parsing data from config file {:?}.  Will try default values. {:?}",
                        config_file_pathbuf.as_path(),
                        error.description()
                    );
                    return default_scaii_config;
                }
            }
        }
        Err(error) => {
            println!(
                "config file {:?} not found.  Will use default values. {:?}",
                config_file_pathbuf.as_path(),
                error
            );
            default_scaii_config
        }
    }
}

fn get_default_scaii_config() -> ScaiiConfig {
    ScaiiConfig {
        replay: Some(ReplayConfig {
            browser: default_browser(),
            url: default_url(),
            port: default_port(),
        }),
    }
}

impl ScaiiConfig {
    pub fn get_replay_url(&mut self) -> String {
        match &self.replay {
            &None => default_url(),
            &Some(ref replay) => replay.url.clone(),
        }
    }

    pub fn get_replay_port(&mut self) -> String {
        match &self.replay {
            &None => default_port(),
            &Some(ref replay) => replay.port.clone(),
        }
    }

    pub fn get_replay_browser(&mut self) -> String {
        match &self.replay {
            &None => default_browser(),
            &Some(ref replay) => replay.browser.clone(),
        }
    }

    pub fn get_full_replay_http_url(&mut self) -> String {
        let url = self.get_replay_url();
        let port = self.get_replay_port();
        return format!("http://{}:{}", url, port);
    }
}
<|endoftext|>


<commit_before>// run-pass
// ignore-emscripten
// min-llvm-version 7.0
// error-pattern: panicked

// Test that the simd_f{min,max} intrinsics produce the correct results.

#![feature(repr_simd, platform_intrinsics)]
#![allow(non_camel_case_types)]

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct f32x4(pub f32, pub f32, pub f32, pub f32);

extern "platform-intrinsic" {
    fn simd_fmin<T>(x: T, y: T) -> T;
    fn simd_fmax<T>(x: T, y: T) -> T;
}

fn main() {
    let x = f32x4(1.0, 2.0, 3.0, 4.0);
    let y = f32x4(2.0, 1.0, 4.0, 3.0);

    #[cfg(not(any(target_arch = "mips", target_arch = "mips64")))]
    let nan = ::std::f32::NAN;
    // MIPS hardware treats f32::NAN as SNAN. Clear the signaling bit.
    // See https://github.com/rust-lang/rust/issues/52746.
    #[cfg(any(target_arch = "mips", target_arch = "mips64"))]
    let nan = f32::from_bits(::std::f32::NAN.to_bits() - 1);

    let n = f32x4(nan, nan, nan, nan);

    unsafe {
        let min0 = simd_fmin(x, y);
        let min1 = simd_fmin(y, x);
        assert_eq!(min0, min1);
        let e = f32x4(1.0, 1.0, 3.0, 3.0);
        assert_eq!(min0, e);
        let minn = simd_fmin(x, n);
        assert_eq!(minn, x);
        let minn = simd_fmin(y, n);
        assert_eq!(minn, y);

        let max0 = simd_fmax(x, y);
        let max1 = simd_fmax(y, x);
        assert_eq!(max0, max1);
        let e = f32x4(2.0, 2.0, 4.0, 4.0);
        assert_eq!(max0, e);
        let maxn = simd_fmax(x, n);
        assert_eq!(maxn, x);
        let maxn = simd_fmax(y, n);
        assert_eq!(maxn, y);
    }
}
<commit_msg>Remove erroneous error-pattern from run-pass test<commit_after>// run-pass
// ignore-emscripten
// min-llvm-version 7.0

// Test that the simd_f{min,max} intrinsics produce the correct results.

#![feature(repr_simd, platform_intrinsics)]
#![allow(non_camel_case_types)]

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct f32x4(pub f32, pub f32, pub f32, pub f32);

extern "platform-intrinsic" {
    fn simd_fmin<T>(x: T, y: T) -> T;
    fn simd_fmax<T>(x: T, y: T) -> T;
}

fn main() {
    let x = f32x4(1.0, 2.0, 3.0, 4.0);
    let y = f32x4(2.0, 1.0, 4.0, 3.0);

    #[cfg(not(any(target_arch = "mips", target_arch = "mips64")))]
    let nan = ::std::f32::NAN;
    // MIPS hardware treats f32::NAN as SNAN. Clear the signaling bit.
    // See https://github.com/rust-lang/rust/issues/52746.
    #[cfg(any(target_arch = "mips", target_arch = "mips64"))]
    let nan = f32::from_bits(::std::f32::NAN.to_bits() - 1);

    let n = f32x4(nan, nan, nan, nan);

    unsafe {
        let min0 = simd_fmin(x, y);
        let min1 = simd_fmin(y, x);
        assert_eq!(min0, min1);
        let e = f32x4(1.0, 1.0, 3.0, 3.0);
        assert_eq!(min0, e);
        let minn = simd_fmin(x, n);
        assert_eq!(minn, x);
        let minn = simd_fmin(y, n);
        assert_eq!(minn, y);

        let max0 = simd_fmax(x, y);
        let max1 = simd_fmax(y, x);
        assert_eq!(max0, max1);
        let e = f32x4(2.0, 2.0, 4.0, 4.0);
        assert_eq!(max0, e);
        let maxn = simd_fmax(x, n);
        assert_eq!(maxn, x);
        let maxn = simd_fmax(y, n);
        assert_eq!(maxn, y);
    }
}
<|endoftext|>


<commit_before>extern crate teleborg;
extern crate reqwest;

#[cfg(test)]
mod tests {
    use teleborg::{Bot, ParseMode, ChatAction, NO_MARKUP};
    use teleborg::objects::{Contact, InlineKeyboardButton, InlineKeyboardMarkup, ForceReply};
    use reqwest::Client;

    use std::env;

    const BASE_URL: &'static str = "https://api.telegram.org/bot";

    fn get_token() -> String {
        env::var("TELEGRAM_BOT_TOKEN")
            .ok()
            .expect("Can't find TELEGRAM_BOT_TOKEN env variable")
    }

    fn setup() -> (Bot, i64) {
        let token = get_token();
        let bot_url = [BASE_URL, &token].concat();
        let bot = Bot::new(bot_url).unwrap();
        let chat_id = env::var("TELEGRAM_CHAT_ID")
            .ok()
            .expect("Can't find TELEGRAM_CHAT_ID env variable")
            .parse::<i64>()
            .unwrap();
        (bot, chat_id)
    }

    #[test]
    fn test_get_me() {
        let token = get_token();
        let bot_url = [BASE_URL, &token].concat();
        let client = Client::new().unwrap();
        let json = Bot::get_me(&client, &bot_url);
        assert!(json.is_ok());
    }

    #[test]
    fn test_send_message() {
        let (bot, chat_id) = setup();
        let message = bot.send_message(&chat_id, "test send_message", None, None, None, None, NO_MARKUP);
        assert!(message.is_ok());
    }

    #[test]
    fn test_send_text_message() {
        let (bot, chat_id) = setup();
        let message = bot.send_message(&chat_id,
                                       "test send text message",
                                       Some(&ParseMode::Text),
                                       None,
                                       None,
                                       None,
                                       NO_MARKUP);
        assert!(message.is_ok());
    }

    #[test]
    fn test_send_markdown_message() {
        let (bot, chat_id) = setup();
        let message = bot.send_message(&chat_id,
                                       "*test send bold message*",
                                       Some(&ParseMode::Markdown),
                                       None,
                                       None,
                                       None,
                                       NO_MARKUP);
        assert!(message.is_ok());
    }

    #[test]
    fn test_send_html_message() {
        let (bot, chat_id) = setup();
        let message = bot.send_message(&chat_id,
                                       "test send HTML message",
                                       Some(&ParseMode::Html),
                                       None,
                                       None,
                                       None,
                                       NO_MARKUP);
        assert!(message.is_ok());
    }

    #[test]
    fn test_url_chat_actions() {
        let (bot, chat_id) = setup();
        let success = bot.send_chat_action(&chat_id, &ChatAction::FindLocation);
        assert!(success.is_ok());
    }

    #[test]
    fn test_url_inline_keyboard() {
        let (bot, chat_id) = setup();
        let mut buttons = Vec::<Vec<InlineKeyboardButton>>::new();
        let mut row = Vec::<InlineKeyboardButton>::new();
        row.push(InlineKeyboardButton::new("TestButton".to_string(),
                                           Some("http://github.com/voider1/teleborg".to_string()),
                                           None,
                                           None,
                                           None));
        buttons.push(row);
        let markup = InlineKeyboardMarkup::new(buttons);
        let message = bot.send_message(&chat_id, "test inline keyboard", None, None, None, None, Some(markup));
        assert!(message.is_ok());
    }

    #[test]
    fn test_force_reply() {
        let (bot, chat_id) = setup();
        let force_reply = ForceReply::new(true, None);
        println!("{:?}", force_reply);
        let message = bot.send_message(&chat_id, "test force reply", None, None, None, None, Some(force_reply));
        println!("{:?}", message);
        assert!(message.is_ok());
    }

    #[test]
    fn test_send_contact() {
        let (bot, chat_id) = setup();

        let contact = Contact {
            phone_number: "0612345678".to_string(),
            first_name: "Voider".to_string(),
            last_name: Some("1".to_string()),
            user_id: Some(666),
        };
        let message = bot.send_contact(&chat_id, &contact, None, None, None);
        assert!(message.is_ok());
    }
}
<commit_msg>Removing debug print statements<commit_after>extern crate teleborg;
extern crate reqwest;

#[cfg(test)]
mod tests {
    use teleborg::{Bot, ParseMode, ChatAction, NO_MARKUP};
    use teleborg::objects::{Contact, InlineKeyboardButton, InlineKeyboardMarkup, ForceReply};
    use reqwest::Client;

    use std::env;

    const BASE_URL: &'static str = "https://api.telegram.org/bot";

    fn get_token() -> String {
        env::var("TELEGRAM_BOT_TOKEN")
            .ok()
            .expect("Can't find TELEGRAM_BOT_TOKEN env variable")
    }

    fn setup() -> (Bot, i64) {
        let token = get_token();
        let bot_url = [BASE_URL, &token].concat();
        let bot = Bot::new(bot_url).unwrap();
        let chat_id = env::var("TELEGRAM_CHAT_ID")
            .ok()
            .expect("Can't find TELEGRAM_CHAT_ID env variable")
            .parse::<i64>()
            .unwrap();
        (bot, chat_id)
    }

    #[test]
    fn test_get_me() {
        let token = get_token();
        let bot_url = [BASE_URL, &token].concat();
        let client = Client::new().unwrap();
        let json = Bot::get_me(&client, &bot_url);
        assert!(json.is_ok());
    }

    #[test]
    fn test_send_message() {
        let (bot, chat_id) = setup();
        let message = bot.send_message(&chat_id, "test send_message", None, None, None, None, NO_MARKUP);
        assert!(message.is_ok());
    }

    #[test]
    fn test_send_text_message() {
        let (bot, chat_id) = setup();
        let message = bot.send_message(&chat_id,
                                       "test send text message",
                                       Some(&ParseMode::Text),
                                       None,
                                       None,
                                       None,
                                       NO_MARKUP);
        assert!(message.is_ok());
    }

    #[test]
    fn test_send_markdown_message() {
        let (bot, chat_id) = setup();
        let message = bot.send_message(&chat_id,
                                       "*test send bold message*",
                                       Some(&ParseMode::Markdown),
                                       None,
                                       None,
                                       None,
                                       NO_MARKUP);
        assert!(message.is_ok());
    }

    #[test]
    fn test_send_html_message() {
        let (bot, chat_id) = setup();
        let message = bot.send_message(&chat_id,
                                       "test send HTML message",
                                       Some(&ParseMode::Html),
                                       None,
                                       None,
                                       None,
                                       NO_MARKUP);
        assert!(message.is_ok());
    }

    #[test]
    fn test_url_chat_actions() {
        let (bot, chat_id) = setup();
        let success = bot.send_chat_action(&chat_id, &ChatAction::FindLocation);
        assert!(success.is_ok());
    }

    #[test]
    fn test_url_inline_keyboard() {
        let (bot, chat_id) = setup();
        let mut buttons = Vec::<Vec<InlineKeyboardButton>>::new();
        let mut row = Vec::<InlineKeyboardButton>::new();
        row.push(InlineKeyboardButton::new("TestButton".to_string(),
                                           Some("http://github.com/voider1/teleborg".to_string()),
                                           None,
                                           None,
                                           None));
        buttons.push(row);
        let markup = InlineKeyboardMarkup::new(buttons);
        let message = bot.send_message(&chat_id, "test inline keyboard", None, None, None, None, Some(markup));
        assert!(message.is_ok());
    }

    #[test]
    fn test_force_reply() {
        let (bot, chat_id) = setup();
        let force_reply = ForceReply::new(true, None);
        let message = bot.send_message(&chat_id, "test force reply", None, None, None, None, Some(force_reply));
        assert!(message.is_ok());
    }

    #[test]
    fn test_send_contact() {
        let (bot, chat_id) = setup();

        let contact = Contact {
            phone_number: "0612345678".to_string(),
            first_name: "Voider".to_string(),
            last_name: Some("1".to_string()),
            user_id: Some(666),
        };
        let message = bot.send_contact(&chat_id, &contact, None, None, None);
        assert!(message.is_ok());
    }
}
<|endoftext|>


<commit_before>//! HIR (previsouly known as descriptors) provides a high-level OO acess to Rust
//! code.
//!
//! The principal difference between HIR and syntax trees is that HIR is bound
//! to a particular crate instance. That is, it has cfg flags and features
//! applied. So, there relation between syntax and HIR is many-to-one.

macro_rules! ctry {
    ($expr:expr) => {
        match $expr {
            None => return Ok(None),
            Some(it) => it,
        }
    };
}

pub mod db;
#[cfg(test)]
mod mock;
mod query_definitions;
mod path;
pub mod source_binder;

mod ids;
mod macros;
mod name;
mod module_tree;
mod nameres;
mod function;
mod adt;
mod type_ref;
mod ty;
mod impl_block;
mod expr;

mod code_model_api;
mod code_model_impl;

use crate::{
    db::HirDatabase,
    name::{AsName, KnownName},
    ids::{DefKind, SourceItemId, SourceFileItemId, SourceFileItems},
};

pub use self::{
    path::{Path, PathKind},
    name::Name,
    ids::{HirFileId, DefId, DefLoc, MacroCallId, MacroCallLoc},
    macros::{MacroDef, MacroInput, MacroExpansion},
    module::{Module, ModuleId, Problem, nameres::{ItemMap, PerNs, Namespace}, ModuleScope, Resolution},
    function::{Function, FnSignature, FnScopes, ScopesWithSyntaxMapping},
    adt::{Struct, Enum},
    ty::Ty,
    impl_block::{ImplBlock, ImplItem},
};

pub use self::function::FnSignatureInfo;

pub use self::code_model_api::{
    Crate, CrateDependency,
    Module, ModuleSource, Problem,
};

pub enum Def {
    Module(Module),
    Function(Function),
    Struct(Struct),
    Enum(Enum),
    Item,
}
<commit_msg>fix after rebase<commit_after>//! HIR (previsouly known as descriptors) provides a high-level OO acess to Rust
//! code.
//!
//! The principal difference between HIR and syntax trees is that HIR is bound
//! to a particular crate instance. That is, it has cfg flags and features
//! applied. So, there relation between syntax and HIR is many-to-one.

macro_rules! ctry {
    ($expr:expr) => {
        match $expr {
            None => return Ok(None),
            Some(it) => it,
        }
    };
}

pub mod db;
#[cfg(test)]
mod mock;
mod query_definitions;
mod path;
pub mod source_binder;

mod ids;
mod macros;
mod name;
mod module_tree;
mod nameres;
mod function;
mod adt;
mod type_ref;
mod ty;
mod impl_block;
mod expr;

mod code_model_api;
mod code_model_impl;

use crate::{
    db::HirDatabase,
    name::{AsName, KnownName},
    ids::{DefKind, SourceItemId, SourceFileItemId, SourceFileItems},
};

pub use self::{
    path::{Path, PathKind},
    name::Name,
    ids::{HirFileId, DefId, DefLoc, MacroCallId, MacroCallLoc},
    macros::{MacroDef, MacroInput, MacroExpansion},
    module_tree::ModuleId,
    nameres::{ItemMap, PerNs, Namespace, Resolution},
    function::{Function, FnSignature, FnScopes, ScopesWithSyntaxMapping},
    adt::{Struct, Enum},
    ty::Ty,
    impl_block::{ImplBlock, ImplItem},
};

pub use self::function::FnSignatureInfo;

pub use self::code_model_api::{
    Crate, CrateDependency,
    Module, ModuleSource, Problem,
};

pub enum Def {
    Module(Module),
    Function(Function),
    Struct(Struct),
    Enum(Enum),
    Item,
}
<|endoftext|>


<commit_before>use std::path::PathBuf;
use std::path::Path;
use std::borrow::Borrow;

use glob::Paths;
use semver::Version;
use std::fmt::{Debug, Formatter};
use std::fmt::Error as FmtError;
use std::result::Result as RResult;

use error::{StoreError, StoreErrorKind};
use store::Result;
use store::Store;

/// The Index into the Store
#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
pub struct StoreId(PathBuf);

impl Into<PathBuf> for StoreId {

    fn into(self) -> PathBuf {
        self.0
    }

}

impl From<PathBuf> for StoreId {

    fn from(pb: PathBuf) -> StoreId {
        StoreId(pb)
    }

}

impl From<String> for StoreId {

    fn from(string: String) -> StoreId {
        StoreId(string.into())
    }

}

impl AsRef<Path> for StoreId {

    fn as_ref(&self) -> &Path {
        self.0.as_ref()
    }

}

impl Borrow<Path> for StoreId {

    fn borrow(&self) -> &Path {
        self.0.borrow()
    }

}

/// This Trait allows you to convert various representations to a single one
/// suitable for usage in the Store
pub trait IntoStoreId {
    fn into_storeid(self) -> StoreId;
}

impl IntoStoreId for PathBuf {
    fn into_storeid(self) -> StoreId {
        StoreId(self)
    }
}

pub fn build_entry_path(store: &Store, path_elem: &str) -> Result<PathBuf> {
    debug!("Checking path element for version");
    if path_elem.split("~").last().map(|v| Version::parse(v).is_err()).unwrap_or(false) {
        debug!("Version cannot be parsed from {:?}", path_elem);
        debug!("Path does not contain version!");
        return Err(StoreError::new(StoreErrorKind::StorePathLacksVersion, None));
    }
    debug!("Version checking succeeded");

    debug!("Building path from {:?}", path_elem);
    let mut path = store.path().clone();

    if path_elem.chars().next() == Some('/') {
        path.push(&path_elem[1..path_elem.len()]);
    } else {
        path.push(path_elem);
    }

    Ok(path)
}

#[macro_export]
macro_rules! module_entry_path_mod {
    ($name:expr, $version:expr) => (
        #[deny(missing_docs,
                missing_copy_implementations,
                trivial_casts, trivial_numeric_casts,
                unsafe_code,
                unstable_features,
                unused_import_braces, unused_qualifications,
                unused_imports)]
        /// A helper module to create valid module entry paths
        pub mod module_path {
            use semver::Version;
            use std::convert::AsRef;
            use std::path::Path;
            use std::path::PathBuf;

            /// A Struct giving you the ability to choose store entries assigned
            /// to it.
            ///
            /// It is created through a call to `new`.
            pub struct ModuleEntryPath(PathBuf);

            impl ModuleEntryPath {
                /// Path has to be a valid UTF-8 string or this will panic!
                pub fn new<P: AsRef<Path>>(pa: P) -> ModuleEntryPath {
                    let mut path = PathBuf::new();
                    path.push(format!("{}", $name));
                    path.push(pa.as_ref().clone());
                    let version = Version::parse($version).unwrap();
                    let name = pa.as_ref().file_name().unwrap()
                        .to_str().unwrap();
                    path.set_file_name(format!("{}~{}",
                                               name,
                                               version));
                    ModuleEntryPath(path)
                }
            }

            impl $crate::storeid::IntoStoreId for ModuleEntryPath {
                fn into_storeid(self) -> $crate::storeid::StoreId {
                    self.0
                }
            }
        }
    )
}

pub struct StoreIdIterator {
    paths: Paths,
}

impl Debug for StoreIdIterator {

    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> {
        write!(fmt, "StoreIdIterator")
    }

}

impl StoreIdIterator {

    pub fn new(paths: Paths) -> StoreIdIterator {
        StoreIdIterator {
            paths: paths,
        }
    }

}

impl Iterator for StoreIdIterator {
    type Item = StoreId;

    fn next(&mut self) -> Option<StoreId> {
        self.paths.next().and_then(|o| o.ok()).map(|p| StoreId::from(p))
    }

}

#[cfg(test)]
mod test {

    use storeid::IntoStoreId;

    module_entry_path_mod!("test", "0.2.0-alpha+leet1337");

    #[test]
    fn correct_path() {
        let p = module_path::ModuleEntryPath::new("test");

        assert_eq!(p.into_storeid().to_str().unwrap(), "test/test~0.2.0-alpha+leet1337");
    }

}
<commit_msg>Impl Deref<PathBuf> for StoreId<commit_after>use std::path::PathBuf;
use std::path::Path;
use std::borrow::Borrow;
use std::ops::Deref;

use glob::Paths;
use semver::Version;
use std::fmt::{Debug, Formatter};
use std::fmt::Error as FmtError;
use std::result::Result as RResult;

use error::{StoreError, StoreErrorKind};
use store::Result;
use store::Store;

/// The Index into the Store
#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
pub struct StoreId(PathBuf);

impl Into<PathBuf> for StoreId {

    fn into(self) -> PathBuf {
        self.0
    }

}

impl Deref for StoreId {
    type Target = PathBuf;

    fn deref(&self) -> &PathBuf {
        &self.0
    }

}

impl From<PathBuf> for StoreId {

    fn from(pb: PathBuf) -> StoreId {
        StoreId(pb)
    }

}

impl From<String> for StoreId {

    fn from(string: String) -> StoreId {
        StoreId(string.into())
    }

}

impl AsRef<Path> for StoreId {

    fn as_ref(&self) -> &Path {
        self.0.as_ref()
    }

}

impl Borrow<Path> for StoreId {

    fn borrow(&self) -> &Path {
        self.0.borrow()
    }

}

/// This Trait allows you to convert various representations to a single one
/// suitable for usage in the Store
pub trait IntoStoreId {
    fn into_storeid(self) -> StoreId;
}

impl IntoStoreId for PathBuf {
    fn into_storeid(self) -> StoreId {
        StoreId(self)
    }
}

pub fn build_entry_path(store: &Store, path_elem: &str) -> Result<PathBuf> {
    debug!("Checking path element for version");
    if path_elem.split("~").last().map(|v| Version::parse(v).is_err()).unwrap_or(false) {
        debug!("Version cannot be parsed from {:?}", path_elem);
        debug!("Path does not contain version!");
        return Err(StoreError::new(StoreErrorKind::StorePathLacksVersion, None));
    }
    debug!("Version checking succeeded");

    debug!("Building path from {:?}", path_elem);
    let mut path = store.path().clone();

    if path_elem.chars().next() == Some('/') {
        path.push(&path_elem[1..path_elem.len()]);
    } else {
        path.push(path_elem);
    }

    Ok(path)
}

#[macro_export]
macro_rules! module_entry_path_mod {
    ($name:expr, $version:expr) => (
        #[deny(missing_docs,
                missing_copy_implementations,
                trivial_casts, trivial_numeric_casts,
                unsafe_code,
                unstable_features,
                unused_import_braces, unused_qualifications,
                unused_imports)]
        /// A helper module to create valid module entry paths
        pub mod module_path {
            use semver::Version;
            use std::convert::AsRef;
            use std::path::Path;
            use std::path::PathBuf;

            /// A Struct giving you the ability to choose store entries assigned
            /// to it.
            ///
            /// It is created through a call to `new`.
            pub struct ModuleEntryPath(PathBuf);

            impl ModuleEntryPath {
                /// Path has to be a valid UTF-8 string or this will panic!
                pub fn new<P: AsRef<Path>>(pa: P) -> ModuleEntryPath {
                    let mut path = PathBuf::new();
                    path.push(format!("{}", $name));
                    path.push(pa.as_ref().clone());
                    let version = Version::parse($version).unwrap();
                    let name = pa.as_ref().file_name().unwrap()
                        .to_str().unwrap();
                    path.set_file_name(format!("{}~{}",
                                               name,
                                               version));
                    ModuleEntryPath(path)
                }
            }

            impl $crate::storeid::IntoStoreId for ModuleEntryPath {
                fn into_storeid(self) -> $crate::storeid::StoreId {
                    self.0
                }
            }
        }
    )
}

pub struct StoreIdIterator {
    paths: Paths,
}

impl Debug for StoreIdIterator {

    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> {
        write!(fmt, "StoreIdIterator")
    }

}

impl StoreIdIterator {

    pub fn new(paths: Paths) -> StoreIdIterator {
        StoreIdIterator {
            paths: paths,
        }
    }

}

impl Iterator for StoreIdIterator {
    type Item = StoreId;

    fn next(&mut self) -> Option<StoreId> {
        self.paths.next().and_then(|o| o.ok()).map(|p| StoreId::from(p))
    }

}

#[cfg(test)]
mod test {

    use storeid::IntoStoreId;

    module_entry_path_mod!("test", "0.2.0-alpha+leet1337");

    #[test]
    fn correct_path() {
        let p = module_path::ModuleEntryPath::new("test");

        assert_eq!(p.into_storeid().to_str().unwrap(), "test/test~0.2.0-alpha+leet1337");
    }

}
<|endoftext|>


<commit_before>// Claxon -- A FLAC decoding library in Rust
// Copyright (C) 2014-2015 Ruud van Asseldonk
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License, version 3,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#![feature(test)]

extern crate claxon;
extern crate test;

use std::fs::File;
use std::io::{Cursor, Read};
use std::path::Path;
use test::Bencher;

fn bench_decode(path: &Path, bencher: &mut Bencher) {
    // Read the file into memory. We want to measure decode speed, not IO
    // overhead. (There is no stable form of mmap in Rust that I know of, so
    // we read manually.)
    let mut file = File::open(path).unwrap();
    let mut data = Vec::new();
    file.read_to_end(&mut data).unwrap();
    let mut cursor = Cursor::new(data);

    let mut stream = claxon::FlacStream::new(&mut cursor).unwrap();

    // Use the more space-efficient 16-bit integers if it is sufficient,
    // otherwise decode into 32-bit integers, which is always sufficient.
    // TODO: If the closure gets called more often than the number of blocks
    // in the file, the measurement is wrong.
    match stream.streaminfo().bits_per_sample {
        n if n <= 16 => {
            let mut blocks = stream.blocks::<i16>();
            bencher.iter(|| { test::black_box(blocks.read_next().unwrap()); });
        }
        _ => {
            let mut blocks = stream.blocks::<i32>();
            bencher.iter(|| { test::black_box(blocks.read_next().unwrap()); });
        }
    }
}

#[bench]
fn bench_p0(bencher: &mut Bencher) {
    bench_decode(Path::new("testsamples/p0.flac"), bencher);
}

#[bench]
fn bench_p1(bencher: &mut Bencher) {
    bench_decode(Path::new("testsamples/p1.flac"), bencher);
}

#[bench]
fn bench_p2(bencher: &mut Bencher) {
    bench_decode(Path::new("testsamples/p2.flac"), bencher);
}

#[bench]
fn bench_p3(bencher: &mut Bencher) {
    bench_decode(Path::new("testsamples/p3.flac"), bencher);
}

#[bench]
fn bench_p4(bencher: &mut Bencher) {
    bench_decode(Path::new("testsamples/p4.flac"), bencher);
}
<commit_msg>measure decoding throughput<commit_after>// Claxon -- A FLAC decoding library in Rust
// Copyright (C) 2014-2015 Ruud van Asseldonk
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License, version 3,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#![feature(test)]

extern crate claxon;
extern crate test;

use std::fs::File;
use std::io::{Cursor, Read};
use std::path::Path;
use test::Bencher;

fn bench_decode(path: &Path, bencher: &mut Bencher) {
    // Read the file into memory. We want to measure decode speed, not IO
    // overhead. (There is no stable form of mmap in Rust that I know of, so
    // we read manually.)
    let mut file = File::open(path).unwrap();
    let mut data = Vec::new();
    file.read_to_end(&mut data).unwrap();
    let mut cursor = Cursor::new(data);

    let mut stream = claxon::FlacStream::new(&mut cursor).unwrap();

    let bps = stream.streaminfo().bits_per_sample as u64;
    let channels = stream.streaminfo().channels as u64;
    let bytes_per_sample = channels * (bps / 8);

    // Use the more space-efficient 16-bit integers if it is sufficient,
    // otherwise decode into 32-bit integers, which is always sufficient.
    // TODO: If the closure gets called more often than the number of blocks
    // in the file, the measurement is wrong. When `blocks` implements
    // `Iterator`, we can assume values and panic on `None`.
    match bps {
        n if n <= 16 => {
            let mut blocks = stream.blocks::<i16>();
            let mut bytes = 0u64;
            bencher.iter(|| {
                let block = blocks.read_next().unwrap();
                test::black_box(block.channel(0));
                bytes += bytes_per_sample * block.len() as u64;
            });
            bencher.bytes = bytes;
        }
        _ => {
            let mut blocks = stream.blocks::<i32>();
            let mut bytes = 0u64;
            bencher.iter(|| {
                let block = blocks.read_next().unwrap();
                test::black_box(block.channel(0));
                bytes += bytes_per_sample * block.len() as u64;
            });
            bencher.bytes = bytes;
        }
    }
}

#[bench]
fn bench_p0_mono_16bit(bencher: &mut Bencher) {
    bench_decode(Path::new("testsamples/p0.flac"), bencher);
}

#[bench]
fn bench_p1_stereo_24bit(bencher: &mut Bencher) {
    bench_decode(Path::new("testsamples/p1.flac"), bencher);
}

#[bench]
fn bench_p2_stereo_16bit(bencher: &mut Bencher) {
    bench_decode(Path::new("testsamples/p2.flac"), bencher);
}

#[bench]
fn bench_p3_stereo_16bit(bencher: &mut Bencher) {
    bench_decode(Path::new("testsamples/p3.flac"), bencher);
}

#[bench]
fn bench_p4_stereo_16bit(bencher: &mut Bencher) {
    bench_decode(Path::new("testsamples/p4.flac"), bencher);
}
<|endoftext|>


<commit_before>//! FIXME: write short doc here

use crate::completion::{
    completion_config::SnippetCap, completion_item::Builder, CompletionContext, CompletionItem,
    CompletionItemKind, CompletionKind, Completions,
};

fn snippet(ctx: &CompletionContext, cap: SnippetCap, label: &str, snippet: &str) -> Builder {
    CompletionItem::new(CompletionKind::Snippet, ctx.source_range(), label)
        .insert_snippet(cap, snippet)
        .kind(CompletionItemKind::Snippet)
}

pub(super) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionContext) {
    if !(ctx.is_trivial_path && ctx.function_syntax.is_some()) {
        return;
    }
    let cap = match ctx.config.snippet_cap {
        Some(it) => it,
        None => return,
    };

    snippet(ctx, cap, "pd", "eprintln!(\"$0 = {:?}\", $0);").add_to(acc);
    snippet(ctx, cap, "ppd", "eprintln!(\"$0 = {:#?}\", $0);").add_to(acc);
}

pub(super) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionContext) {
    if !ctx.is_new_item {
        return;
    }
    let cap = match ctx.config.snippet_cap {
        Some(it) => it,
        None => return,
    };

    snippet(
        ctx,
        cap,
        "Test function",
        "\
#[test]
fn ${1:feature}() {
    $0
}",
    )
    .lookup_by("tfn")
    .add_to(acc);

    snippet(ctx, cap, "macro_rules", "macro_rules! $1 {\n\t($2) => {\n\t\t$0\n\t};\n}").add_to(acc);
    snippet(ctx, cap, "pub(crate)", "pub(crate) $0").add_to(acc);
}

#[cfg(test)]
mod tests {
    use crate::completion::{test_utils::do_completion, CompletionItem, CompletionKind};
    use insta::assert_debug_snapshot;

    fn do_snippet_completion(code: &str) -> Vec<CompletionItem> {
        do_completion(code, CompletionKind::Snippet)
    }

    #[test]
    fn completes_snippets_in_expressions() {
        assert_debug_snapshot!(
                    do_snippet_completion(r"fn foo(x: i32) { <|> }"),
        @r###"
        [
            CompletionItem {
                label: "pd",
                source_range: 17..17,
                delete: 17..17,
                insert: "eprintln!(\"$0 = {:?}\", $0);",
                kind: Snippet,
            },
            CompletionItem {
                label: "ppd",
                source_range: 17..17,
                delete: 17..17,
                insert: "eprintln!(\"$0 = {:#?}\", $0);",
                kind: Snippet,
            },
        ]
        "###
                );
    }

    #[test]
    fn should_not_complete_snippets_in_path() {
        assert_debug_snapshot!(
                    do_snippet_completion(r"fn foo(x: i32) { ::foo<|> }"),
        @"[]"
                );
        assert_debug_snapshot!(
                    do_snippet_completion(r"fn foo(x: i32) { ::<|> }"),
        @"[]"
                );
    }

    #[test]
    fn completes_snippets_in_items() {
        assert_debug_snapshot!(
            do_snippet_completion(
                r"
                #[cfg(test)]
                mod tests {
                    <|>
                }
                "
            ),
            @r###"
        [
            CompletionItem {
                label: "Test function",
                source_range: 78..78,
                delete: 78..78,
                insert: "#[test]\nfn ${1:feature}() {\n    $0\n}",
                kind: Snippet,
                lookup: "tfn",
            },
            CompletionItem {
                label: "macro_rules",
                source_range: 78..78,
                delete: 78..78,
                insert: "macro_rules! $1 {\n\t($2) => {\n\t\t$0\n\t};\n}",
                kind: Snippet,
            },
            CompletionItem {
                label: "pub(crate)",
                source_range: 78..78,
                delete: 78..78,
                insert: "pub(crate) $0",
                kind: Snippet,
            },
        ]
        "###
        );
    }
}
<commit_msg>add tests module snippet<commit_after>//! FIXME: write short doc here

use crate::completion::{
    completion_config::SnippetCap, completion_item::Builder, CompletionContext, CompletionItem,
    CompletionItemKind, CompletionKind, Completions,
};

fn snippet(ctx: &CompletionContext, cap: SnippetCap, label: &str, snippet: &str) -> Builder {
    CompletionItem::new(CompletionKind::Snippet, ctx.source_range(), label)
        .insert_snippet(cap, snippet)
        .kind(CompletionItemKind::Snippet)
}

pub(super) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionContext) {
    if !(ctx.is_trivial_path && ctx.function_syntax.is_some()) {
        return;
    }
    let cap = match ctx.config.snippet_cap {
        Some(it) => it,
        None => return,
    };

    snippet(ctx, cap, "pd", "eprintln!(\"$0 = {:?}\", $0);").add_to(acc);
    snippet(ctx, cap, "ppd", "eprintln!(\"$0 = {:#?}\", $0);").add_to(acc);
}

pub(super) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionContext) {
    if !ctx.is_new_item {
        return;
    }
    let cap = match ctx.config.snippet_cap {
        Some(it) => it,
        None => return,
    };

    snippet(
        ctx,
        cap,
        "Test module",
        "\
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ${1:test_name}() {
        $0
    }
}",
    )
    .lookup_by("tmod")
    .add_to(acc);

    snippet(
        ctx,
        cap,
        "Test function",
        "\
#[test]
fn ${1:feature}() {
    $0
}",
    )
    .lookup_by("tfn")
    .add_to(acc);

    snippet(ctx, cap, "macro_rules", "macro_rules! $1 {\n\t($2) => {\n\t\t$0\n\t};\n}").add_to(acc);
    snippet(ctx, cap, "pub(crate)", "pub(crate) $0").add_to(acc);
}

#[cfg(test)]
mod tests {
    use crate::completion::{test_utils::do_completion, CompletionItem, CompletionKind};
    use insta::assert_debug_snapshot;

    fn do_snippet_completion(code: &str) -> Vec<CompletionItem> {
        do_completion(code, CompletionKind::Snippet)
    }

    #[test]
    fn completes_snippets_in_expressions() {
        assert_debug_snapshot!(
                    do_snippet_completion(r"fn foo(x: i32) { <|> }"),
        @r###"
        [
            CompletionItem {
                label: "pd",
                source_range: 17..17,
                delete: 17..17,
                insert: "eprintln!(\"$0 = {:?}\", $0);",
                kind: Snippet,
            },
            CompletionItem {
                label: "ppd",
                source_range: 17..17,
                delete: 17..17,
                insert: "eprintln!(\"$0 = {:#?}\", $0);",
                kind: Snippet,
            },
        ]
        "###
                );
    }

    #[test]
    fn should_not_complete_snippets_in_path() {
        assert_debug_snapshot!(
                    do_snippet_completion(r"fn foo(x: i32) { ::foo<|> }"),
        @"[]"
                );
        assert_debug_snapshot!(
                    do_snippet_completion(r"fn foo(x: i32) { ::<|> }"),
        @"[]"
                );
    }

    #[test]
    fn completes_snippets_in_items() {
        assert_debug_snapshot!(
            do_snippet_completion(
                r"
                #[cfg(test)]
                mod tests {
                    <|>
                }
                "
            ),
            @r###"
        [
            CompletionItem {
                label: "Test function",
                source_range: 78..78,
                delete: 78..78,
                insert: "#[test]\nfn ${1:feature}() {\n    $0\n}",
                kind: Snippet,
                lookup: "tfn",
            },
            CompletionItem {
                label: "macro_rules",
                source_range: 78..78,
                delete: 78..78,
                insert: "macro_rules! $1 {\n\t($2) => {\n\t\t$0\n\t};\n}",
                kind: Snippet,
            },
            CompletionItem {
                label: "pub(crate)",
                source_range: 78..78,
                delete: 78..78,
                insert: "pub(crate) $0",
                kind: Snippet,
            },
        ]
        "###
        );
    }
}
<|endoftext|>