<commit_before>use std::collections::{BTreeMap, HashMap};
use std::net;
use std::path::{Path, PathBuf};
use std::str;

use token::{self, Token};

extern crate fnv;
use self::fnv::FnvHasher;

//////////////////////////////////////////////////////////////////////////

#[derive(Serialize)]
struct UnitStruct;

#[derive(Serialize)]
struct TupleStruct(i32, i32, i32);

#[derive(Serialize)]
struct Struct {
    a: i32,
    b: i32,
    c: i32,
}

#[derive(Serialize)]
enum Enum {
    Unit,
    One(i32),
    Seq(i32, i32),
    Map { a: i32, b: i32 },
}

//////////////////////////////////////////////////////////////////////////

declare_ser_tests! {
    test_unit {
        () => &[Token::Unit],
    }
    test_bool {
        true => &[Token::Bool(true)],
        false => &[Token::Bool(false)],
    }
    test_isizes {
        0isize => &[Token::Isize(0)],
        0i8 => &[Token::I8(0)],
        0i16 => &[Token::I16(0)],
        0i32 => &[Token::I32(0)],
        0i64 => &[Token::I64(0)],
    }
    test_usizes {
        0usize => &[Token::Usize(0)],
        0u8 => &[Token::U8(0)],
        0u16 => &[Token::U16(0)],
        0u32 => &[Token::U32(0)],
        0u64 => &[Token::U64(0)],
    }
    test_floats {
        0f32 => &[Token::F32(0.)],
        0f64 => &[Token::F64(0.)],
    }
    test_char {
        'a' => &[Token::Char('a')],
    }
    test_str {
        "abc" => &[Token::Str("abc")],
        "abc".to_owned() => &[Token::Str("abc")],
    }
    test_option {
        None::<i32> => &[Token::Option(false)],
        Some(1) => &[
            Token::Option(true),
            Token::I32(1),
        ],
    }
    test_result {
        Ok::<i32, i32>(0) => &[
            Token::EnumNewType("Result", "Ok"),
            Token::I32(0),
        ],
        Err::<i32, i32>(1) => &[
            Token::EnumNewType("Result", "Err"),
            Token::I32(1),
        ],
    }
    test_slice {
        &[0][..0] => &[
            Token::SeqStart(Some(0)),
            Token::SeqEnd,
        ],
        &[1, 2, 3][..] => &[
            Token::SeqStart(Some(3)),
                Token::SeqSep,
                Token::I32(1),

                Token::SeqSep,
                Token::I32(2),

                Token::SeqSep,
                Token::I32(3),
            Token::SeqEnd,
        ],
    }
    test_array {
        [0; 0] => &[
            Token::SeqArrayStart(0),
            Token::SeqEnd,
        ],
        [1, 2, 3] => &[
            Token::SeqArrayStart(3),
                Token::SeqSep,
                Token::I32(1),

                Token::SeqSep,
                Token::I32(2),

                Token::SeqSep,
                Token::I32(3),
            Token::SeqEnd,
        ],
    }
    test_vec {
        Vec::<isize>::new() => &[
            Token::SeqStart(Some(0)),
            Token::SeqEnd,
        ],
        vec![vec![], vec![1], vec![2, 3]] => &[
            Token::SeqStart(Some(3)),
                Token::SeqSep,
                Token::SeqStart(Some(0)),
                Token::SeqEnd,

                Token::SeqSep,
                Token::SeqStart(Some(1)),
                    Token::SeqSep,
                    Token::I32(1),
                Token::SeqEnd,

                Token::SeqSep,
                Token::SeqStart(Some(2)),
                    Token::SeqSep,
                    Token::I32(2),

                    Token::SeqSep,
                    Token::I32(3),
                Token::SeqEnd,
            Token::SeqEnd,
        ],
    }
    test_tuple {
        (1,) => &[
            Token::TupleStart(1),
                Token::TupleSep,
                Token::I32(1),
            Token::TupleEnd,
        ],
        (1, 2, 3) => &[
            Token::TupleStart(3),
                Token::TupleSep,
                Token::I32(1),

                Token::TupleSep,
                Token::I32(2),

                Token::TupleSep,
                Token::I32(3),
            Token::TupleEnd,
        ],
    }
    test_btreemap {
        btreemap![1 => 2] => &[
            Token::MapStart(Some(1)),
                Token::MapSep,
                Token::I32(1),
                Token::I32(2),
            Token::MapEnd,
        ],
        btreemap![1 => 2, 3 => 4] => &[
            Token::MapStart(Some(2)),
                Token::MapSep,
                Token::I32(1),
                Token::I32(2),

                Token::MapSep,
                Token::I32(3),
                Token::I32(4),
            Token::MapEnd,
        ],
        btreemap![1 => btreemap![], 2 => btreemap![3 => 4, 5 => 6]] => &[
            Token::MapStart(Some(2)),
                Token::MapSep,
                Token::I32(1),
                Token::MapStart(Some(0)),
                Token::MapEnd,

                Token::MapSep,
                Token::I32(2),
                Token::MapStart(Some(2)),
                    Token::MapSep,
                    Token::I32(3),
                    Token::I32(4),

                    Token::MapSep,
                    Token::I32(5),
                    Token::I32(6),
                Token::MapEnd,
            Token::MapEnd,
        ],
    }
    test_hashmap {
        hashmap![FnvHasher @ 1 => 2, 3 => 4] => &[
            Token::MapStart(Some(2)),
                Token::MapSep,
                Token::I32(1),
                Token::I32(2),

                Token::MapSep,
                Token::I32(3),
                Token::I32(4),
            Token::MapEnd,
        ],
    }
    test_unit_struct {
        UnitStruct => &[Token::UnitStruct("UnitStruct")],
    }
    test_tuple_struct {
        TupleStruct(1, 2, 3) => &[
            Token::TupleStructStart("TupleStruct", Some(3)),
                Token::TupleStructSep,
                Token::I32(1),

                Token::TupleStructSep,
                Token::I32(2),

                Token::TupleStructSep,
                Token::I32(3),
            Token::TupleStructEnd,
        ],
    }
    test_struct {
        Struct { a: 1, b: 2, c: 3 } => &[
            Token::StructStart("Struct", Some(3)),
                Token::StructSep,
                Token::Str("a"),
                Token::I32(1),

                Token::StructSep,
                Token::Str("b"),
                Token::I32(2),

                Token::StructSep,
                Token::Str("c"),
                Token::I32(3),
            Token::StructEnd,
        ],
    }
    test_enum {
        Enum::Unit => &[Token::EnumUnit("Enum", "Unit")],
        Enum::One(42) => &[Token::EnumNewType("Enum", "One"), Token::I32(42)],
        Enum::Seq(1, 2) => &[
            Token::EnumSeqStart("Enum", "Seq", Some(2)),
                Token::EnumSeqSep,
                Token::I32(1),

                Token::EnumSeqSep,
                Token::I32(2),
            Token::EnumSeqEnd,
        ],
        Enum::Map { a: 1, b: 2 } => &[
            Token::EnumMapStart("Enum", "Map", Some(2)),
                Token::EnumMapSep,
                Token::Str("a"),
                Token::I32(1),

                Token::EnumMapSep,
                Token::Str("b"),
                Token::I32(2),
            Token::EnumMapEnd,
        ],
    }
    test_box {
        Box::new(0i32) => &[Token::I32(0)],
    }
    test_boxed_slice {
        Box::new([0, 1, 2]) => &[
            Token::SeqArrayStart(3),
            Token::SeqSep,
            Token::I32(0),
            Token::SeqSep,
            Token::I32(1),
            Token::SeqSep,
            Token::I32(2),
            Token::SeqEnd,
        ],
    }
    test_net_ipv4addr {
        "1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
    }
    test_net_ipv6addr {
        "::1".parse::<net::Ipv6Addr>().unwrap() => &[Token::Str("::1")],
    }
    test_net_socketaddr {
        "1.2.3.4:1234".parse::<net::SocketAddr>().unwrap() => &[Token::Str("1.2.3.4:1234")],
        "1.2.3.4:1234".parse::<net::SocketAddrV4>().unwrap() => &[Token::Str("1.2.3.4:1234")],
        "[::1]:1234".parse::<net::SocketAddrV6>().unwrap() => &[Token::Str("[::1]:1234")],
    }
    test_path {
        Path::new("/usr/local/lib") => &[
            Token::Str("/usr/local/lib"),
        ],
    }
    test_path_buf {
        PathBuf::from("/usr/local/lib") => &[
            Token::Str("/usr/local/lib"),
        ],
    }
}

#[cfg(feature = "nightly")]
#[test]
fn test_net_ipaddr() {
    assert_ser_tokens(
        "1.2.3.4".parse::<net::IpAddr>().unwrap(),
        &[Token::Str("1.2.3.4")],
    );
}

#[test]
fn test_cannot_serialize_paths() {
    let path = unsafe {
        str::from_utf8_unchecked(b"Hello \xF0\x90\x80World")
    };
    token::assert_ser_tokens_error(
        &Path::new(path),
        &[Token::Str("Hello �World")],
        token::Error::InvalidValue("Path contains invalid UTF-8 characters".to_owned()));

    let mut path_buf = PathBuf::new();
    path_buf.push(path);

    token::assert_ser_tokens_error(
        &path_buf,
        &[Token::Str("Hello �World")],
        token::Error::InvalidValue("Path contains invalid UTF-8 characters".to_owned()));
}
<commit_msg>Add ser tests for normal HashMap<commit_after>use std::collections::{BTreeMap, HashMap};
use std::net;
use std::path::{Path, PathBuf};
use std::str;

use token::{self, Token};

extern crate fnv;
use self::fnv::FnvHasher;

//////////////////////////////////////////////////////////////////////////

#[derive(Serialize)]
struct UnitStruct;

#[derive(Serialize)]
struct TupleStruct(i32, i32, i32);

#[derive(Serialize)]
struct Struct {
    a: i32,
    b: i32,
    c: i32,
}

#[derive(Serialize)]
enum Enum {
    Unit,
    One(i32),
    Seq(i32, i32),
    Map { a: i32, b: i32 },
}

//////////////////////////////////////////////////////////////////////////

declare_ser_tests! {
    test_unit {
        () => &[Token::Unit],
    }
    test_bool {
        true => &[Token::Bool(true)],
        false => &[Token::Bool(false)],
    }
    test_isizes {
        0isize => &[Token::Isize(0)],
        0i8 => &[Token::I8(0)],
        0i16 => &[Token::I16(0)],
        0i32 => &[Token::I32(0)],
        0i64 => &[Token::I64(0)],
    }
    test_usizes {
        0usize => &[Token::Usize(0)],
        0u8 => &[Token::U8(0)],
        0u16 => &[Token::U16(0)],
        0u32 => &[Token::U32(0)],
        0u64 => &[Token::U64(0)],
    }
    test_floats {
        0f32 => &[Token::F32(0.)],
        0f64 => &[Token::F64(0.)],
    }
    test_char {
        'a' => &[Token::Char('a')],
    }
    test_str {
        "abc" => &[Token::Str("abc")],
        "abc".to_owned() => &[Token::Str("abc")],
    }
    test_option {
        None::<i32> => &[Token::Option(false)],
        Some(1) => &[
            Token::Option(true),
            Token::I32(1),
        ],
    }
    test_result {
        Ok::<i32, i32>(0) => &[
            Token::EnumNewType("Result", "Ok"),
            Token::I32(0),
        ],
        Err::<i32, i32>(1) => &[
            Token::EnumNewType("Result", "Err"),
            Token::I32(1),
        ],
    }
    test_slice {
        &[0][..0] => &[
            Token::SeqStart(Some(0)),
            Token::SeqEnd,
        ],
        &[1, 2, 3][..] => &[
            Token::SeqStart(Some(3)),
                Token::SeqSep,
                Token::I32(1),

                Token::SeqSep,
                Token::I32(2),

                Token::SeqSep,
                Token::I32(3),
            Token::SeqEnd,
        ],
    }
    test_array {
        [0; 0] => &[
            Token::SeqArrayStart(0),
            Token::SeqEnd,
        ],
        [1, 2, 3] => &[
            Token::SeqArrayStart(3),
                Token::SeqSep,
                Token::I32(1),

                Token::SeqSep,
                Token::I32(2),

                Token::SeqSep,
                Token::I32(3),
            Token::SeqEnd,
        ],
    }
    test_vec {
        Vec::<isize>::new() => &[
            Token::SeqStart(Some(0)),
            Token::SeqEnd,
        ],
        vec![vec![], vec![1], vec![2, 3]] => &[
            Token::SeqStart(Some(3)),
                Token::SeqSep,
                Token::SeqStart(Some(0)),
                Token::SeqEnd,

                Token::SeqSep,
                Token::SeqStart(Some(1)),
                    Token::SeqSep,
                    Token::I32(1),
                Token::SeqEnd,

                Token::SeqSep,
                Token::SeqStart(Some(2)),
                    Token::SeqSep,
                    Token::I32(2),

                    Token::SeqSep,
                    Token::I32(3),
                Token::SeqEnd,
            Token::SeqEnd,
        ],
    }
    test_tuple {
        (1,) => &[
            Token::TupleStart(1),
                Token::TupleSep,
                Token::I32(1),
            Token::TupleEnd,
        ],
        (1, 2, 3) => &[
            Token::TupleStart(3),
                Token::TupleSep,
                Token::I32(1),

                Token::TupleSep,
                Token::I32(2),

                Token::TupleSep,
                Token::I32(3),
            Token::TupleEnd,
        ],
    }
    test_btreemap {
        btreemap![1 => 2] => &[
            Token::MapStart(Some(1)),
                Token::MapSep,
                Token::I32(1),
                Token::I32(2),
            Token::MapEnd,
        ],
        btreemap![1 => 2, 3 => 4] => &[
            Token::MapStart(Some(2)),
                Token::MapSep,
                Token::I32(1),
                Token::I32(2),

                Token::MapSep,
                Token::I32(3),
                Token::I32(4),
            Token::MapEnd,
        ],
        btreemap![1 => btreemap![], 2 => btreemap![3 => 4, 5 => 6]] => &[
            Token::MapStart(Some(2)),
                Token::MapSep,
                Token::I32(1),
                Token::MapStart(Some(0)),
                Token::MapEnd,

                Token::MapSep,
                Token::I32(2),
                Token::MapStart(Some(2)),
                    Token::MapSep,
                    Token::I32(3),
                    Token::I32(4),

                    Token::MapSep,
                    Token::I32(5),
                    Token::I32(6),
                Token::MapEnd,
            Token::MapEnd,
        ],
    }
    test_hashmap {
        HashMap::<isize, isize>::new() => &[
            Token::MapStart(Some(0)),
            Token::MapEnd,
        ],
        hashmap![1 => 2] => &[
            Token::MapStart(Some(1)),
                Token::MapSep,
                Token::I32(1),
                Token::I32(2),
            Token::MapEnd,
        ],
        hashmap![FnvHasher @ 1 => 2] => &[
            Token::MapStart(Some(1)),
                Token::MapSep,
                Token::I32(1),
                Token::I32(2),
            Token::MapEnd,
        ],
    }
    test_unit_struct {
        UnitStruct => &[Token::UnitStruct("UnitStruct")],
    }
    test_tuple_struct {
        TupleStruct(1, 2, 3) => &[
            Token::TupleStructStart("TupleStruct", Some(3)),
                Token::TupleStructSep,
                Token::I32(1),

                Token::TupleStructSep,
                Token::I32(2),

                Token::TupleStructSep,
                Token::I32(3),
            Token::TupleStructEnd,
        ],
    }
    test_struct {
        Struct { a: 1, b: 2, c: 3 } => &[
            Token::StructStart("Struct", Some(3)),
                Token::StructSep,
                Token::Str("a"),
                Token::I32(1),

                Token::StructSep,
                Token::Str("b"),
                Token::I32(2),

                Token::StructSep,
                Token::Str("c"),
                Token::I32(3),
            Token::StructEnd,
        ],
    }
    test_enum {
        Enum::Unit => &[Token::EnumUnit("Enum", "Unit")],
        Enum::One(42) => &[Token::EnumNewType("Enum", "One"), Token::I32(42)],
        Enum::Seq(1, 2) => &[
            Token::EnumSeqStart("Enum", "Seq", Some(2)),
                Token::EnumSeqSep,
                Token::I32(1),

                Token::EnumSeqSep,
                Token::I32(2),
            Token::EnumSeqEnd,
        ],
        Enum::Map { a: 1, b: 2 } => &[
            Token::EnumMapStart("Enum", "Map", Some(2)),
                Token::EnumMapSep,
                Token::Str("a"),
                Token::I32(1),

                Token::EnumMapSep,
                Token::Str("b"),
                Token::I32(2),
            Token::EnumMapEnd,
        ],
    }
    test_box {
        Box::new(0i32) => &[Token::I32(0)],
    }
    test_boxed_slice {
        Box::new([0, 1, 2]) => &[
            Token::SeqArrayStart(3),
            Token::SeqSep,
            Token::I32(0),
            Token::SeqSep,
            Token::I32(1),
            Token::SeqSep,
            Token::I32(2),
            Token::SeqEnd,
        ],
    }
    test_net_ipv4addr {
        "1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
    }
    test_net_ipv6addr {
        "::1".parse::<net::Ipv6Addr>().unwrap() => &[Token::Str("::1")],
    }
    test_net_socketaddr {
        "1.2.3.4:1234".parse::<net::SocketAddr>().unwrap() => &[Token::Str("1.2.3.4:1234")],
        "1.2.3.4:1234".parse::<net::SocketAddrV4>().unwrap() => &[Token::Str("1.2.3.4:1234")],
        "[::1]:1234".parse::<net::SocketAddrV6>().unwrap() => &[Token::Str("[::1]:1234")],
    }
    test_path {
        Path::new("/usr/local/lib") => &[
            Token::Str("/usr/local/lib"),
        ],
    }
    test_path_buf {
        PathBuf::from("/usr/local/lib") => &[
            Token::Str("/usr/local/lib"),
        ],
    }
}

#[cfg(feature = "nightly")]
#[test]
fn test_net_ipaddr() {
    assert_ser_tokens(
        "1.2.3.4".parse::<net::IpAddr>().unwrap(),
        &[Token::Str("1.2.3.4")],
    );
}

#[test]
fn test_cannot_serialize_paths() {
    let path = unsafe {
        str::from_utf8_unchecked(b"Hello \xF0\x90\x80World")
    };
    token::assert_ser_tokens_error(
        &Path::new(path),
        &[Token::Str("Hello �World")],
        token::Error::InvalidValue("Path contains invalid UTF-8 characters".to_owned()));

    let mut path_buf = PathBuf::new();
    path_buf.push(path);

    token::assert_ser_tokens_error(
        &path_buf,
        &[Token::Str("Hello �World")],
        token::Error::InvalidValue("Path contains invalid UTF-8 characters".to_owned()));
}
<|endoftext|>


<commit_before>use bson::Document;
use bson::Bson::{FloatingPoint, I32};
use bson::Bson::String as BsonString;
use mongodb::client::wire_protocol::flags::{OpInsertFlags, OpQueryFlags};
use mongodb::client::wire_protocol::operations::Message;
use std::io::Write;
use std::net::TcpStream;

// #[test]
fn insert_single_key_doc() {
    match TcpStream::connect("localhost:27017") {
        Ok(mut stream) => {
            let mut doc = Document::new();
            doc.insert("foo".to_owned(), FloatingPoint(42.0));
            let docs = vec![doc];
            let flags = OpInsertFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_insert(1, flags, name, docs);

            let cm = match res {
                Ok(message) => message,
                Err(_) => panic!("Could not create message!")
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let doc = Document::new();
            let flags = OpQueryFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_query(1, flags, name, 0, 0, doc, None);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let reply = match Message::read(&mut stream) {
                Ok(m) => m,
                Err(s) => panic!("{}", s)
            };

            let docs = match reply {
                Message::OpReply { header: _, flags: _, cursor_id:_,
                                   starting_from: _, number_returned: _,
                                   documents: d } => d,
                _ => panic!("Invalid response read from server")
            };

            assert_eq!(docs.len() as i32, 1);

            match docs[0].get("foo") {
                Some(&FloatingPoint(42.0)) => (),
                _ => panic!("Wrong value returned!")
            };
        },
        Err(_) => {
            panic!("Could not connect to server")
        }
    }
}

// #[test]
fn insert_multi_key_doc() {
    match TcpStream::connect("localhost:27017") {
        Ok(mut stream) => {
            let mut doc = Document::new();
            doc.insert("foo".to_owned(), FloatingPoint(42.0));
            doc.insert("bar".to_owned(), BsonString("__z&".to_owned()));
            let docs = vec![doc];
            let flags = OpInsertFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_insert(1, flags, name, docs);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let doc = Document::new();
            let flags = OpQueryFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_query(1, flags, name, 0, 0, doc, None);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let reply = match Message::read(&mut stream) {
                Ok(m) => m,
                Err(s) => panic!("{}", s)
            };

            let docs = match reply {
                Message::OpReply { header: _, flags: _, cursor_id:_,
                                   starting_from: _, number_returned: _,
                                   documents: d } => d,
                _ => panic!("Invalid response read from server")
            };

            assert_eq!(docs.len() as i32, 1);

            match docs[0].get("foo") {
                Some(&FloatingPoint(42.0)) => (),
                _ => panic!("Wrong value returned!")
            };

            match docs[0].get("bar") {
                Some(&BsonString(ref s)) => assert_eq!(s, "__z&"),
                _ => panic!("Wrong value returned!")
            };
        },
        Err(_) => {
            panic!("Could not connect to server")
        }
    }
}

// #[test]
fn insert_docs() {
    match TcpStream::connect("localhost:27017") {
        Ok(mut stream) => {
            let mut doc1 = Document::new();
            doc1.insert("foo".to_owned(), FloatingPoint(42.0));
            doc1.insert("bar".to_owned(), BsonString("__z&".to_owned()));

            let mut doc2 = Document::new();
            doc2.insert("booyah".to_owned(), I32(23));

            let docs = vec![doc1, doc2];
            let flags = OpInsertFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_insert(1, flags, name, docs);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let doc = Document::new();
            let flags = OpQueryFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_query(1, flags, name, 0, 0, doc, None);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let reply = match Message::read(&mut stream) {
                Ok(m) => m,
                Err(s) => panic!("{}", s)
            };

            let docs = match reply {
                Message::OpReply { header: _, flags: _, cursor_id:_,
                                   starting_from: _, number_returned: _,
                                   documents: d } => d,
                _ => panic!("Invalid response read from server")
            };

            assert_eq!(docs.len() as i32, 2);

            match docs[0].get("foo") {
                Some(&FloatingPoint(42.0)) => (),
                _ => panic!("Wrong value returned!")
            };

            match docs[0].get("bar") {
                Some(&BsonString(ref s)) => assert_eq!(s, "__z&"),
                _ => panic!("Wrong value returned!")
            };

            match docs[1].get("booyah") {
                Some(&I32(23)) => (),
                _ => panic!("Wrong value returned!")
            };
        },
        Err(_) => {
            panic!("Could not connect to server")
        }
    }
}
<commit_msg>changed tests to use separate column families<commit_after>use bson::Document;
use bson::Bson::{FloatingPoint, I32};
use bson::Bson::String as BsonString;
use mongodb::client::wire_protocol::flags::{OpInsertFlags, OpQueryFlags};
use mongodb::client::wire_protocol::operations::Message;
use std::io::Write;
use std::net::TcpStream;

#[test]
fn insert_single_key_doc() {
    match TcpStream::connect("localhost:27017") {
        Ok(mut stream) => {
            let mut doc = Document::new();
            doc.insert("foo".to_owned(), FloatingPoint(42.0));
            let docs = vec![doc];
            let flags = OpInsertFlags::no_flags();
            let name = "test.single_key".to_owned();
            let res = Message::with_insert(1, flags, name, docs);

            let cm = match res {
                Ok(message) => message,
                Err(_) => panic!("Could not create message!")
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let doc = Document::new();
            let flags = OpQueryFlags::no_flags();
            let name = "test.single_key".to_owned();
            let res = Message::with_query(1, flags, name, 0, 0, doc, None);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let reply = match Message::read(&mut stream) {
                Ok(m) => m,
                Err(s) => panic!("{}", s)
            };

            let docs = match reply {
                Message::OpReply { header: _, flags: _, cursor_id:_,
                                   starting_from: _, number_returned: _,
                                   documents: d } => d,
                _ => panic!("Invalid response read from server")
            };

            assert_eq!(docs.len() as i32, 1);

            match docs[0].get("foo") {
                Some(&FloatingPoint(42.0)) => (),
                _ => panic!("Wrong value returned!")
            };
        },
        Err(_) => {
            panic!("Could not connect to server")
        }
    }
}

#[test]
fn insert_multi_key_doc() {
    match TcpStream::connect("localhost:27017") {
        Ok(mut stream) => {
            let mut doc = Document::new();
            doc.insert("foo".to_owned(), FloatingPoint(42.0));
            doc.insert("bar".to_owned(), BsonString("__z&".to_owned()));
            let docs = vec![doc];
            let flags = OpInsertFlags::no_flags();
            let name = "test.multi_key".to_owned();
            let res = Message::with_insert(1, flags, name, docs);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let doc = Document::new();
            let flags = OpQueryFlags::no_flags();
            let name = "test.multi_key".to_owned();
            let res = Message::with_query(1, flags, name, 0, 0, doc, None);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let reply = match Message::read(&mut stream) {
                Ok(m) => m,
                Err(s) => panic!("{}", s)
            };

            let docs = match reply {
                Message::OpReply { header: _, flags: _, cursor_id:_,
                                   starting_from: _, number_returned: _,
                                   documents: d } => d,
                _ => panic!("Invalid response read from server")
            };

            assert_eq!(docs.len() as i32, 1);

            match docs[0].get("foo") {
                Some(&FloatingPoint(42.0)) => (),
                _ => panic!("Wrong value returned!")
            };

            match docs[0].get("bar") {
                Some(&BsonString(ref s)) => assert_eq!(s, "__z&"),
                _ => panic!("Wrong value returned!")
            };
        },
        Err(_) => {
            panic!("Could not connect to server")
        }
    }
}

#[test]
fn insert_docs() {
    match TcpStream::connect("localhost:27017") {
        Ok(mut stream) => {
            let mut doc1 = Document::new();
            doc1.insert("foo".to_owned(), FloatingPoint(42.0));
            doc1.insert("bar".to_owned(), BsonString("__z&".to_owned()));

            let mut doc2 = Document::new();
            doc2.insert("booyah".to_owned(), I32(23));

            let docs = vec![doc1, doc2];
            let flags = OpInsertFlags::no_flags();
            let name = "test.multi_doc".to_owned();
            let res = Message::with_insert(1, flags, name, docs);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let doc = Document::new();
            let flags = OpQueryFlags::no_flags();
            let name = "test.multi_doc".to_owned();
            let res = Message::with_query(1, flags, name, 0, 0, doc, None);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let reply = match Message::read(&mut stream) {
                Ok(m) => m,
                Err(s) => panic!("{}", s)
            };

            let docs = match reply {
                Message::OpReply { header: _, flags: _, cursor_id:_,
                                   starting_from: _, number_returned: _,
                                   documents: d } => d,
                _ => panic!("Invalid response read from server")
            };

            assert_eq!(docs.len() as i32, 2);

            match docs[0].get("foo") {
                Some(&FloatingPoint(42.0)) => (),
                _ => panic!("Wrong value returned!")
            };

            match docs[0].get("bar") {
                Some(&BsonString(ref s)) => assert_eq!(s, "__z&"),
                _ => panic!("Wrong value returned!")
            };

            match docs[1].get("booyah") {
                Some(&I32(23)) => (),
                _ => panic!("Wrong value returned!")
            };
        },
        Err(_) => {
            panic!("Could not connect to server")
        }
    }
}
<|endoftext|>


<commit_before>use gl;
use yaglw::gl_context::GLContext;
use yaglw::shader::Shader;

pub struct T<'a> {
  #[allow(missing_docs)]
  pub shader: Shader<'a>,
}

pub fn new<'a, 'b:'a>(gl: &'a GLContext) -> T<'b> {
  let components = vec!(
    (gl::VERTEX_SHADER, "
      #version 330 core

      void main() {
        if (gl_VertexID == 0) {
          gl_Position = vec4(1, -1, 0, 1);
        } else if (gl_VertexID == 1) {
          gl_Position = vec4(1, 1, 0, 1);
        } else if (gl_VertexID == 2) {
          gl_Position = vec4(-1, -1, 0, 1);
        } else if (gl_VertexID == 3) {
          gl_Position = vec4(-1, 1, 0, 1);
        }
      }".to_owned()),
    (gl::FRAGMENT_SHADER,
      format!(r#"
        #version 330 core

        uniform vec2 window_size;

        uniform struct Sun {{
          vec3 direction;
          vec3 intensity;
        }} sun;

        const float sun_angular_radius = 3.14/32;

        uniform mat4 projection_matrix;
        uniform vec3 eye_position;

        uniform float time_ms;

        out vec4 frag_color;

        // include depth fog
        {}

        // include cnoise
        {}

        vec3 pixel_direction(vec2 pixel) {{
          // Scale to [0, 1]
          pixel /= window_size;
          // Scale to [-1, 1]
          pixel = 2*pixel - 1;
          vec4 p = inverse(projection_matrix) * vec4(pixel, -1, 1);
          return normalize(vec3(p / p.w) - eye_position);
        }}

        float cloud_noise(vec3 seed) {{
          float f = cnoise(seed + time_ms / 10000);
          // to [0, 1]
          f = f / 2 + 0.5;
          return f;
        }}

        void main() {{
          vec3 c = sun.intensity;

          vec3 direction = pixel_direction(gl_FragCoord.xy);

          const int HEIGHTS = 2;
          float heights[HEIGHTS] = float[](150, 1000);
          vec3 offsets[HEIGHTS] = vec3[](vec3(12,553,239), vec3(-10, 103, 10004));

          if (dot(normalize(sun.direction), direction) > cos(sun_angular_radius)) {{
            c = vec3(1);
          }}

          float alpha = 0;
          for (int i = 0; i < HEIGHTS; ++i) {{
            float cloud_height = heights[i];
            float dist = (cloud_height - eye_position.y) / direction.y;
            if (dist <= 0 || dist > 1000000) {{
              continue;
            }} else {{
              vec3 seed = (eye_position + dist * direction + offsets[i]) / 1000 * vec3(1, 4, 1);
              float f = cloud_noise(seed) * cloud_noise(seed + vec3(-10, -103, 1));
              f = f * f;
              alpha += f * (1 - fog_density(dist / 8));
            }}
          }}

          alpha = min(alpha, 1);
          c = mix(c, vec3(1, 1, 1), alpha);

          frag_color = vec4(c, 1);
        }}"#,
        ::shaders::depth_fog::to_string(),
        ::shaders::noise::cnoise(),
      )
    ),
  );
  T {
    shader: Shader::new(gl, components.into_iter()),
  }
}
<commit_msg>sun++<commit_after>use gl;
use yaglw::gl_context::GLContext;
use yaglw::shader::Shader;

pub struct T<'a> {
  #[allow(missing_docs)]
  pub shader: Shader<'a>,
}

pub fn new<'a, 'b:'a>(gl: &'a GLContext) -> T<'b> {
  let components = vec!(
    (gl::VERTEX_SHADER, "
      #version 330 core

      void main() {
        if (gl_VertexID == 0) {
          gl_Position = vec4(1, -1, 0, 1);
        } else if (gl_VertexID == 1) {
          gl_Position = vec4(1, 1, 0, 1);
        } else if (gl_VertexID == 2) {
          gl_Position = vec4(-1, -1, 0, 1);
        } else if (gl_VertexID == 3) {
          gl_Position = vec4(-1, 1, 0, 1);
        }
      }".to_owned()),
    (gl::FRAGMENT_SHADER,
      format!(r#"
        #version 330 core

        uniform vec2 window_size;

        uniform struct Sun {{
          vec3 direction;
          vec3 intensity;
        }} sun;

        const float sun_angular_radius = 3.14/32;

        uniform mat4 projection_matrix;
        uniform vec3 eye_position;

        uniform float time_ms;

        out vec4 frag_color;

        // include depth fog
        {}

        // include cnoise
        {}

        vec3 pixel_direction(vec2 pixel) {{
          // Scale to [0, 1]
          pixel /= window_size;
          // Scale to [-1, 1]
          pixel = 2*pixel - 1;
          vec4 p = inverse(projection_matrix) * vec4(pixel, -1, 1);
          return normalize(vec3(p / p.w) - eye_position);
        }}

        float cloud_noise(vec3 seed) {{
          float f = cnoise(seed + time_ms / 10000);
          // to [0, 1]
          f = f / 2 + 0.5;
          return f;
        }}

        void main() {{
          vec3 c = sun.intensity;

          vec3 direction = pixel_direction(gl_FragCoord.xy);

          const int HEIGHTS = 2;
          float heights[HEIGHTS] = float[](150, 1000);
          vec3 offsets[HEIGHTS] = vec3[](vec3(12,553,239), vec3(-10, 103, 10004));

          float sunniness = exp(32 * (dot(sun.direction, direction) - cos(sun_angular_radius)));
          c = mix(c, vec3(1), sunniness);

          float alpha = 0;
          for (int i = 0; i < HEIGHTS; ++i) {{
            float cloud_height = heights[i];
            float dist = (cloud_height - eye_position.y) / direction.y;
            if (dist <= 0 || dist > 1000000) {{
              continue;
            }} else {{
              vec3 seed = (eye_position + dist * direction + offsets[i]) / 1000 * vec3(1, 4, 1);
              float f = cloud_noise(seed) * cloud_noise(seed + vec3(-10, -103, 1));
              f = f * f;
              alpha += f * (1 - fog_density(dist / 8));
            }}
          }}

          alpha = min(alpha, 1);
          c = mix(c, vec3(1, 1, 1), alpha);

          frag_color = min(vec4(c, 1), vec4(1));
        }}"#,
        ::shaders::depth_fog::to_string(),
        ::shaders::noise::cnoise(),
      )
    ),
  );
  T {
    shader: Shader::new(gl, components.into_iter()),
  }
}
<|endoftext|>


<commit_before>extern crate lp_modeler;
extern crate quote;
use quote::quote;

use lp_modeler::dsl::*;

#[test]
fn test_quotations() {
  use LpExpression::*;
  let a = LpInteger { name : "a" . to_string ( ) , lower_bound : None , upper_bound : None };
  let quoted_a = quote!(#a);
  let quoted_a_str = "LpInteger { name : \"a\" . to_string ( ) , lower_bound : None , upper_bound : None }";
  assert_eq!(quoted_a.to_string(), quoted_a_str);

  let exp : LpExpression = a.clone().into();
  let quoted_exp = quote!(#exp);
  let quoted_exp_str = "LpExpression :: ConsInt ( ".to_owned() + quoted_a_str + " )";
  assert_eq!(quoted_exp.to_string(), quoted_exp_str);

  let full_exp = LpExpression::MulExpr ( Box::new ( LpExpression::SubExpr ( Box::new ( LpExpression::EmptyExpr ) , Box::new ( LpExpression::LitVal ( 1f32 ) ) ) ) , Box::new ( LpExpression::AddExpr ( Box::new ( LpExpression::ConsCont ( LpContinuous { name : "x".to_string() , lower_bound : None , upper_bound : None } ) ) , Box::new ( LpExpression::ConsInt ( LpInteger { name : "y".to_string() , lower_bound : None , upper_bound : None } ) ) ) ) );

  let full_exp_quoted = quote!(#full_exp);
  let full_exp_str = "LpExpression :: MulExpr ( Box :: new ( LpExpression :: SubExpr ( Box :: new ( LpExpression :: EmptyExpr ) , Box :: new ( LpExpression :: LitVal ( 1f32 ) ) ) ) , Box :: new ( LpExpression :: AddExpr ( Box :: new ( LpExpression :: ConsCont ( LpContinuous { name : \"x\" . to_string ( ) , lower_bound : None , upper_bound : None } ) ) , Box :: new ( LpExpression :: ConsInt ( LpInteger { name : \"y\" . to_string ( ) , lower_bound : None , upper_bound : None } ) ) ) ) )";
  assert_eq!(full_exp_quoted.to_string(), full_exp_str);

  // a.equal(&b);
  let a_eq_b = LpConstraint( SubExpr( Box::new ( ConsInt ( LpInteger { name : "a" . to_string ( ) , lower_bound : None , upper_bound : None } ) ) , Box::new ( ConsInt ( LpInteger { name : "b" . to_string ( ) , lower_bound : None , upper_bound : None } ) ) ) , Constraint::Equal , LitVal(0f32));

  let quoted_a_eq_b = quote!(#a_eq_b);
  let a_eq_b_str = "LpConstraint ( LpExpression :: SubExpr ( Box :: new ( LpExpression :: ConsInt ( LpInteger { name : \"a\" . to_string ( ) , lower_bound : None , upper_bound : None } ) ) , Box :: new ( LpExpression :: ConsInt ( LpInteger { name : \"b\" . to_string ( ) , lower_bound : None , upper_bound : None } ) ) ) , Constraint :: Equal , LpExpression :: LitVal ( 0f32 ) )";
  assert_eq!(quoted_a_eq_b.to_string(), a_eq_b_str)
}
<commit_msg>remove extra whitespace in expected &strs in test_quotations()<commit_after>extern crate lp_modeler;
extern crate quote;
use quote::quote;

use lp_modeler::dsl::*;

#[test]
fn test_quotations() {
  use LpExpression::*;
  let a = LpInteger { name : "a" . to_string ( ) , lower_bound : None , upper_bound : None };
  let quoted_a = quote!(#a);
  let quoted_a_str = "LpInteger { name : \"a\" . to_string () , lower_bound : None , upper_bound : None }";
  assert_eq!(quoted_a.to_string(), quoted_a_str);

  let exp : LpExpression = a.clone().into();
  let quoted_exp = quote!(#exp);
  let quoted_exp_str = "LpExpression :: ConsInt (".to_owned() + quoted_a_str + ")";
  assert_eq!(quoted_exp.to_string(), quoted_exp_str);

  let full_exp = LpExpression::MulExpr ( Box::new ( LpExpression::SubExpr ( Box::new ( LpExpression::EmptyExpr ) , Box::new ( LpExpression::LitVal ( 1f32 ) ) ) ) , Box::new ( LpExpression::AddExpr ( Box::new ( LpExpression::ConsCont ( LpContinuous { name : "x".to_string() , lower_bound : None , upper_bound : None } ) ) , Box::new ( LpExpression::ConsInt ( LpInteger { name : "y".to_string() , lower_bound : None , upper_bound : None } ) ) ) ) );

  let full_exp_quoted = quote!(#full_exp);
  let full_exp_str = "LpExpression :: MulExpr (Box :: new (LpExpression :: SubExpr (Box :: new (LpExpression :: EmptyExpr) , Box :: new (LpExpression :: LitVal (1f32)))) , Box :: new (LpExpression :: AddExpr (Box :: new (LpExpression :: ConsCont (LpContinuous { name : \"x\" . to_string () , lower_bound : None , upper_bound : None })) , Box :: new (LpExpression :: ConsInt (LpInteger { name : \"y\" . to_string () , lower_bound : None , upper_bound : None })))))";
  assert_eq!(full_exp_quoted.to_string(), full_exp_str);

  // a.equal(&b);
  let a_eq_b = LpConstraint( SubExpr( Box::new ( ConsInt ( LpInteger { name : "a" . to_string ( ) , lower_bound : None , upper_bound : None } ) ) , Box::new ( ConsInt ( LpInteger { name : "b" . to_string ( ) , lower_bound : None , upper_bound : None } ) ) ) , Constraint::Equal , LitVal(0f32));

  let quoted_a_eq_b = quote!(#a_eq_b);
  let a_eq_b_str = "LpConstraint (LpExpression :: SubExpr (Box :: new (LpExpression :: ConsInt (LpInteger { name : \"a\" . to_string () , lower_bound : None , upper_bound : None })) , Box :: new (LpExpression :: ConsInt (LpInteger { name : \"b\" . to_string () , lower_bound : None , upper_bound : None }))) , Constraint :: Equal , LpExpression :: LitVal (0f32))";
  assert_eq!(quoted_a_eq_b.to_string(), a_eq_b_str)
}
<|endoftext|>


<commit_before>extern crate edit_distance;

#[test]
fn simple() {
    assert_eq!(edit_distance::edit_distance("kitten", "sitting"), 3);
    assert_eq!(edit_distance::edit_distance("Tier", "Tor"), 2);
}

#[test]
fn same() {
    assert_eq!(edit_distance::edit_distance("kitten", "kitten"), 0);
}

#[test]
fn empty_a() {
    assert_eq!(edit_distance::edit_distance("", "kitten"), 6);
}

#[test]
fn empty_b() {
    assert_eq!(edit_distance::edit_distance("sitting", ""), 7);
}

#[test]
fn empty_both() {
    assert_eq!(edit_distance::edit_distance("", ""), 0);
}

#[test]
fn unicode_misc() {
    assert_eq!(edit_distance::edit_distance("üö", "uo"), 2);
}

#[test]
fn unicode_thai() {
    assert_eq!(edit_distance::edit_distance("ฎ ฏ ฐ", "a b c"), 3);
}

#[test]
fn unicode_misc_equal() {
    assert_eq!(edit_distance::edit_distance("☀☂☃☄", "☀☂☃☄"), 0);
}

extern crate quickcheck;
use quickcheck::quickcheck;

#[test]
fn at_least_size_difference_property() {
    fn at_least_size_difference(a: String, b: String) -> bool {
        let size_a = a.chars().count() as i32;
        let size_b = b.chars().count() as i32;
        let diff = (size_a - size_b).abs();

        edit_distance::edit_distance(&a, &b) >= diff
    }

    quickcheck(at_least_size_difference as fn(a: String, b: String) -> bool);
}

#[test]
fn at_most_length_of_longer_property() {
    fn at_most_size_of_longer(a: String, b: String) -> bool {
        let upper_bound = *[a.chars().count(),
                            b.chars().count()]
            .iter()
            .max()
            .unwrap() as i32;
        edit_distance::edit_distance(&a, &b) <= upper_bound
    }

    quickcheck(at_most_size_of_longer as fn(a: String, b: String) -> bool);
}
<commit_msg>Only zero iff both string are equal<commit_after>extern crate edit_distance;

#[test]
fn simple() {
    assert_eq!(edit_distance::edit_distance("kitten", "sitting"), 3);
    assert_eq!(edit_distance::edit_distance("Tier", "Tor"), 2);
}

#[test]
fn same() {
    assert_eq!(edit_distance::edit_distance("kitten", "kitten"), 0);
}

#[test]
fn empty_a() {
    assert_eq!(edit_distance::edit_distance("", "kitten"), 6);
}

#[test]
fn empty_b() {
    assert_eq!(edit_distance::edit_distance("sitting", ""), 7);
}

#[test]
fn empty_both() {
    assert_eq!(edit_distance::edit_distance("", ""), 0);
}

#[test]
fn unicode_misc() {
    assert_eq!(edit_distance::edit_distance("üö", "uo"), 2);
}

#[test]
fn unicode_thai() {
    assert_eq!(edit_distance::edit_distance("ฎ ฏ ฐ", "a b c"), 3);
}

#[test]
fn unicode_misc_equal() {
    assert_eq!(edit_distance::edit_distance("☀☂☃☄", "☀☂☃☄"), 0);
}

extern crate quickcheck;
use quickcheck::quickcheck;

#[test]
fn at_least_size_difference_property() {
    fn at_least_size_difference(a: String, b: String) -> bool {
        let size_a = a.chars().count() as i32;
        let size_b = b.chars().count() as i32;
        let diff = (size_a - size_b).abs();

        edit_distance::edit_distance(&a, &b) >= diff
    }

    quickcheck(at_least_size_difference as fn(a: String, b: String) -> bool);
}

#[test]
fn at_most_length_of_longer_property() {
    fn at_most_size_of_longer(a: String, b: String) -> bool {
        let upper_bound = *[a.chars().count(),
                            b.chars().count()]
            .iter()
            .max()
            .unwrap() as i32;
        edit_distance::edit_distance(&a, &b) <= upper_bound
    }

    quickcheck(at_most_size_of_longer as fn(a: String, b: String) -> bool);
}

#[test]
fn zero_iff_a_equals_b_property() {
    fn zero_iff_a_equals_b(a: String, b: String) -> bool {
        let d = edit_distance::edit_distance(&a, &b);

        if a == b {
            d == 0
        } else {
            d > 0
        }
    }

    quickcheck(zero_iff_a_equals_b as fn(a: String, b: String) -> bool);
}
<|endoftext|>


<commit_before>extern crate word2vec;
use word2vec::wordvectors::WordVector;

const PATH: &'static str = "vectors.bin";

#[test]
fn test_word_cosine()
{
	let model = WordVector::load_from_binary(PATH).unwrap();
	let result = model.cosine("winter", 10);
	match result {
		Some(res) => {
	    	assert_eq!(res.len(), 10);
	    	let only_words: Vec<&str> = res.iter().map(|x| x.0.as_ref()).collect();
	    	assert!(!only_words.contains(&"winter"))
		},
	   		None => assert!(false),
	}
}

#[test]
fn test_unexisting_word_cosine() {
    let model = WordVector::load_from_binary(PATH).unwrap();
    let result = model.cosine("somenotexistingword", 10);
    match result {
	    Some(_) => assert!(false),
	   	None => assert!(true),
	}
}

#[test]
fn test_word_analogy() {
    let model = WordVector::load_from_binary(PATH).unwrap();
    let mut pos = Vec::new();
	pos.push("woman");
	pos.push("king");
	let mut neg = Vec::new();
	neg.push("man");
	let result = model.analogy(pos, neg, 10);
	match result {
	    Some(res) => {
	        assert_eq!(res.len(), 10);
	    	let only_words: Vec<&str> = res.iter().map(|x| x.0.as_ref()).collect();
	    	assert!(!only_words.contains(&"woman"));
	    	assert!(!only_words.contains(&"king"));
	    	assert!(!only_words.contains(&"man"));
	    },
	   	None => assert!(false),
	}
}

#[test]
fn test_word_analogy_with_empty_params() {
    let model = WordVector::load_from_binary(PATH).unwrap();
	let result = model.analogy(Vec::new(), Vec::new(), 10);
	match result {
	    Some(_) => assert!(false),
	   	None => assert!(true),
	}
}
<commit_msg>add test<commit_after>extern crate word2vec;
use word2vec::wordvectors::WordVector;

const PATH: &'static str = "vectors.bin";

#[test]
fn test_word_cosine()
{
	let model = WordVector::load_from_binary(PATH).unwrap();
	let res = model.cosine("winter", 10).expect("word not found in vocabulary");
    assert_eq!(res.len(), 10);
    let only_words: Vec<&str> = res.iter().map(|x| x.0.as_ref()).collect();
    assert!(!only_words.contains(&"winter"))
}

#[test]
fn test_unexisting_word_cosine() {
    let model = WordVector::load_from_binary(PATH).unwrap();
    let result = model.cosine("somenotexistingword", 10);
    match result {
	    Some(_) => assert!(false),
	   	None => assert!(true),
	}
}

#[test]
fn test_word_analogy() {
    let model = WordVector::load_from_binary(PATH).unwrap();
    let mut pos = Vec::new();
	pos.push("woman");
	pos.push("king");
	let mut neg = Vec::new();
	neg.push("man");
	let res = model.analogy(pos, neg, 10).expect("couldn't find all of the given words");
    assert_eq!(res.len(), 10);
    let only_words: Vec<&str> = res.iter().map(|x| x.0.as_ref()).collect();
    assert!(!only_words.contains(&"woman"));
    assert!(!only_words.contains(&"king"));
    assert!(!only_words.contains(&"man"));
}

#[test]
fn test_word_analogy_with_empty_params() {
    let model = WordVector::load_from_binary(PATH).unwrap();
	let result = model.analogy(Vec::new(), Vec::new(), 10);
	match result {
	    Some(_) => assert!(false),
	   	None => assert!(true),
	}
}

#[test]
fn test_word_count_is_correctly_returned() {
    let v = WordVector::load_from_binary(PATH).unwrap();
    assert_eq!(v.word_count(), 71291);
}

<|endoftext|>


<commit_before>fn test_str(exe: &str, s: &str) {
    use std::process::{Command, Stdio};
    use std::io::Write;
    use std::str::from_utf8;
    let mut cmd = Command::new(exe)
        .stdin(Stdio::piped())
        .stderr(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    println!("started cmd");
    write!(cmd.stdin.as_mut().unwrap(), "{}", s).unwrap();
    println!("wrote to stdin");
    let res = cmd.wait_with_output().unwrap();
    println!("stdout: {}", from_utf8(&res.stdout).unwrap());
    println!("stderr: {}", from_utf8(&res.stderr).unwrap());
    println!("status: {:?}", res.status);
    assert!(res.status.success());
}

#[test]
fn run_read() {
    test_str("target/debug/examples/test_read", "the answer™: 42");
}

#[test]
fn run_read_simple() {
    test_str("target/debug/examples/test_read_simple", "99\n");
}

#[test]
fn run_scan_simple() {
    test_str("target/debug/examples/test_scan_simple", "42");
}

#[test]
fn run_scan() {
    test_str("target/debug/examples/test_scan", "99, 42\n66");
}
<commit_msg>Rustfmt<commit_after>fn test_str(exe: &str, s: &str) {
    use std::io::Write;
    use std::process::{Command, Stdio};
    use std::str::from_utf8;
    let mut cmd = Command::new(exe)
        .stdin(Stdio::piped())
        .stderr(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    println!("started cmd");
    write!(cmd.stdin.as_mut().unwrap(), "{}", s).unwrap();
    println!("wrote to stdin");
    let res = cmd.wait_with_output().unwrap();
    println!("stdout: {}", from_utf8(&res.stdout).unwrap());
    println!("stderr: {}", from_utf8(&res.stderr).unwrap());
    println!("status: {:?}", res.status);
    assert!(res.status.success());
}

#[test]
fn run_read() {
    test_str("target/debug/examples/test_read", "the answer™: 42");
}

#[test]
fn run_read_simple() {
    test_str("target/debug/examples/test_read_simple", "99\n");
}

#[test]
fn run_scan_simple() {
    test_str("target/debug/examples/test_scan_simple", "42");
}

#[test]
fn run_scan() {
    test_str("target/debug/examples/test_scan", "99, 42\n66");
}
<|endoftext|>


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

use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
use crate::dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods;
use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::conversions::{jsstring_to_str, ConversionResult, FromJSValConvertible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::document::AnimationFrameCallback;
use crate::dom::element::Element;
use crate::dom::globalscope::GlobalScope;
use crate::dom::node::{window_from_node, Node, ShadowIncluding};
use crate::dom::window::Window;
use crate::script_thread::Documents;
use devtools_traits::TimelineMarkerType;
use devtools_traits::{AutoMargins, CachedConsoleMessage, CachedConsoleMessageTypes};
use devtools_traits::{ComputedNodeLayout, ConsoleAPI, PageError};
use devtools_traits::{EvaluateJSReply, Modification, NodeInfo, TimelineMarker};
use ipc_channel::ipc::IpcSender;
use js::jsapi::JSAutoCompartment;
use js::jsval::UndefinedValue;
use js::rust::wrappers::ObjectClassName;
use msg::constellation_msg::PipelineId;
use std::ffi::CStr;
use std::str;
use uuid::Uuid;

#[allow(unsafe_code)]
pub fn handle_evaluate_js(global: &GlobalScope, eval: String, reply: IpcSender<EvaluateJSReply>) {
    // global.get_cx() returns a valid `JSContext` pointer, so this is safe.
    let result = unsafe {
        let cx = global.get_cx();
        let globalhandle = global.reflector().get_jsobject();
        let _ac = JSAutoCompartment::new(cx, globalhandle.get());
        rooted!(in(cx) let mut rval = UndefinedValue());
        global.evaluate_js_on_global_with_result(&eval, rval.handle_mut());

        if rval.is_undefined() {
            EvaluateJSReply::VoidValue
        } else if rval.is_boolean() {
            EvaluateJSReply::BooleanValue(rval.to_boolean())
        } else if rval.is_double() || rval.is_int32() {
            EvaluateJSReply::NumberValue(
                match FromJSValConvertible::from_jsval(cx, rval.handle(), ()) {
                    Ok(ConversionResult::Success(v)) => v,
                    _ => unreachable!(),
                },
            )
        } else if rval.is_string() {
            EvaluateJSReply::StringValue(String::from(jsstring_to_str(cx, rval.to_string())))
        } else if rval.is_null() {
            EvaluateJSReply::NullValue
        } else {
            assert!(rval.is_object());

            rooted!(in(cx) let obj = rval.to_object());
            let class_name = CStr::from_ptr(ObjectClassName(cx, obj.handle()));
            let class_name = str::from_utf8(class_name.to_bytes()).unwrap();

            EvaluateJSReply::ActorValue {
                class: class_name.to_owned(),
                uuid: Uuid::new_v4().to_string(),
            }
        }
    };
    reply.send(result).unwrap();
}

pub fn handle_get_root_node(
    documents: &Documents,
    pipeline: PipelineId,
    reply: IpcSender<Option<NodeInfo>>,
) {
    let info = documents
        .find_document(pipeline)
        .map(|document| document.upcast::<Node>().summarize());
    reply.send(info).unwrap();
}

pub fn handle_get_document_element(
    documents: &Documents,
    pipeline: PipelineId,
    reply: IpcSender<Option<NodeInfo>>,
) {
    let info = documents
        .find_document(pipeline)
        .and_then(|document| document.GetDocumentElement())
        .map(|element| element.upcast::<Node>().summarize());
    reply.send(info).unwrap();
}

fn find_node_by_unique_id(
    documents: &Documents,
    pipeline: PipelineId,
    node_id: &str,
) -> Option<DomRoot<Node>> {
    documents.find_document(pipeline).and_then(|document| {
        document
            .upcast::<Node>()
            .traverse_preorder(ShadowIncluding::No)
            .find(|candidate| candidate.unique_id() == node_id)
    })
}

pub fn handle_get_children(
    documents: &Documents,
    pipeline: PipelineId,
    node_id: String,
    reply: IpcSender<Option<Vec<NodeInfo>>>,
) {
    match find_node_by_unique_id(documents, pipeline, &*node_id) {
        None => return reply.send(None).unwrap(),
        Some(parent) => {
            let children = parent.children().map(|child| child.summarize()).collect();

            reply.send(Some(children)).unwrap();
        },
    };
}

pub fn handle_get_layout(
    documents: &Documents,
    pipeline: PipelineId,
    node_id: String,
    reply: IpcSender<Option<ComputedNodeLayout>>,
) {
    let node = match find_node_by_unique_id(documents, pipeline, &*node_id) {
        None => return reply.send(None).unwrap(),
        Some(found_node) => found_node,
    };

    let elem = node
        .downcast::<Element>()
        .expect("should be getting layout of element");
    let rect = elem.GetBoundingClientRect();
    let width = rect.Width() as f32;
    let height = rect.Height() as f32;

    let window = window_from_node(&*node);
    let elem = node
        .downcast::<Element>()
        .expect("should be getting layout of element");
    let computed_style = window.GetComputedStyle(elem, None);

    reply
        .send(Some(ComputedNodeLayout {
            display: String::from(computed_style.Display()),
            position: String::from(computed_style.Position()),
            zIndex: String::from(computed_style.ZIndex()),
            boxSizing: String::from(computed_style.BoxSizing()),
            autoMargins: determine_auto_margins(&window, &*node),
            marginTop: String::from(computed_style.MarginTop()),
            marginRight: String::from(computed_style.MarginRight()),
            marginBottom: String::from(computed_style.MarginBottom()),
            marginLeft: String::from(computed_style.MarginLeft()),
            borderTopWidth: String::from(computed_style.BorderTopWidth()),
            borderRightWidth: String::from(computed_style.BorderRightWidth()),
            borderBottomWidth: String::from(computed_style.BorderBottomWidth()),
            borderLeftWidth: String::from(computed_style.BorderLeftWidth()),
            paddingTop: String::from(computed_style.PaddingTop()),
            paddingRight: String::from(computed_style.PaddingRight()),
            paddingBottom: String::from(computed_style.PaddingBottom()),
            paddingLeft: String::from(computed_style.PaddingLeft()),
            width: width,
            height: height,
        }))
        .unwrap();
}

fn determine_auto_margins(window: &Window, node: &Node) -> AutoMargins {
    let style = window.style_query(node.to_trusted_node_address()).unwrap();
    let margin = style.get_margin();
    AutoMargins {
        top: margin.margin_top.is_auto(),
        right: margin.margin_right.is_auto(),
        bottom: margin.margin_bottom.is_auto(),
        left: margin.margin_left.is_auto(),
    }
}

pub fn handle_get_cached_messages(
    _pipeline_id: PipelineId,
    message_types: CachedConsoleMessageTypes,
    reply: IpcSender<Vec<CachedConsoleMessage>>,
) {
    // TODO: check the messageTypes against a global Cache for console messages and page exceptions
    let mut messages = Vec::new();
    if message_types.contains(CachedConsoleMessageTypes::PAGE_ERROR) {
        // TODO: make script error reporter pass all reported errors
        //      to devtools and cache them for returning here.
        let msg = PageError {
            type_: "PageError".to_owned(),
            errorMessage: "page error test".to_owned(),
            sourceName: String::new(),
            lineText: String::new(),
            lineNumber: 0,
            columnNumber: 0,
            category: String::new(),
            timeStamp: 0,
            error: false,
            warning: false,
            exception: false,
            strict: false,
            private: false,
        };
        messages.push(CachedConsoleMessage::PageError(msg));
    }
    if message_types.contains(CachedConsoleMessageTypes::CONSOLE_API) {
        // TODO: do for real
        let msg = ConsoleAPI {
            type_: "ConsoleAPI".to_owned(),
            level: "error".to_owned(),
            filename: "http://localhost/~mihai/mozilla/test.html".to_owned(),
            lineNumber: 0,
            functionName: String::new(),
            timeStamp: 0,
            private: false,
            arguments: vec!["console error test".to_owned()],
        };
        messages.push(CachedConsoleMessage::ConsoleAPI(msg));
    }
    reply.send(messages).unwrap();
}

pub fn handle_modify_attribute(
    documents: &Documents,
    pipeline: PipelineId,
    node_id: String,
    modifications: Vec<Modification>,
) {
    let node = match find_node_by_unique_id(documents, pipeline, &*node_id) {
        None => {
            return warn!(
                "node id {} for pipeline id {} is not found",
                &node_id, &pipeline
            );
        },
        Some(found_node) => found_node,
    };

    let elem = node
        .downcast::<Element>()
        .expect("should be getting layout of element");

    for modification in modifications {
        match modification.newValue {
            Some(string) => {
                let _ = elem.SetAttribute(
                    DOMString::from(modification.attributeName),
                    DOMString::from(string),
                );
            },
            None => elem.RemoveAttribute(DOMString::from(modification.attributeName)),
        }
    }
}

pub fn handle_wants_live_notifications(global: &GlobalScope, send_notifications: bool) {
    global.set_devtools_wants_updates(send_notifications);
}

pub fn handle_set_timeline_markers(
    documents: &Documents,
    pipeline: PipelineId,
    marker_types: Vec<TimelineMarkerType>,
    reply: IpcSender<Option<TimelineMarker>>,
) {
    match documents.find_window(pipeline) {
        None => reply.send(None).unwrap(),
        Some(window) => window.set_devtools_timeline_markers(marker_types, reply),
    }
}

pub fn handle_drop_timeline_markers(
    documents: &Documents,
    pipeline: PipelineId,
    marker_types: Vec<TimelineMarkerType>,
) {
    if let Some(window) = documents.find_window(pipeline) {
        window.drop_devtools_timeline_markers(marker_types);
    }
}

pub fn handle_request_animation_frame(documents: &Documents, id: PipelineId, actor_name: String) {
    if let Some(doc) = documents.find_document(id) {
        doc.request_animation_frame(AnimationFrameCallback::DevtoolsFramerateTick { actor_name });
    }
}

pub fn handle_reload(documents: &Documents, id: PipelineId) {
    if let Some(win) = documents.find_window(id) {
        win.Location().reload_without_origin_check();
    }
}
<commit_msg>Make devtools find node by unique id function include shadow trees<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
use crate::dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods;
use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::conversions::{jsstring_to_str, ConversionResult, FromJSValConvertible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::document::AnimationFrameCallback;
use crate::dom::element::Element;
use crate::dom::globalscope::GlobalScope;
use crate::dom::node::{window_from_node, Node, ShadowIncluding};
use crate::dom::window::Window;
use crate::script_thread::Documents;
use devtools_traits::TimelineMarkerType;
use devtools_traits::{AutoMargins, CachedConsoleMessage, CachedConsoleMessageTypes};
use devtools_traits::{ComputedNodeLayout, ConsoleAPI, PageError};
use devtools_traits::{EvaluateJSReply, Modification, NodeInfo, TimelineMarker};
use ipc_channel::ipc::IpcSender;
use js::jsapi::JSAutoCompartment;
use js::jsval::UndefinedValue;
use js::rust::wrappers::ObjectClassName;
use msg::constellation_msg::PipelineId;
use std::ffi::CStr;
use std::str;
use uuid::Uuid;

#[allow(unsafe_code)]
pub fn handle_evaluate_js(global: &GlobalScope, eval: String, reply: IpcSender<EvaluateJSReply>) {
    // global.get_cx() returns a valid `JSContext` pointer, so this is safe.
    let result = unsafe {
        let cx = global.get_cx();
        let globalhandle = global.reflector().get_jsobject();
        let _ac = JSAutoCompartment::new(cx, globalhandle.get());
        rooted!(in(cx) let mut rval = UndefinedValue());
        global.evaluate_js_on_global_with_result(&eval, rval.handle_mut());

        if rval.is_undefined() {
            EvaluateJSReply::VoidValue
        } else if rval.is_boolean() {
            EvaluateJSReply::BooleanValue(rval.to_boolean())
        } else if rval.is_double() || rval.is_int32() {
            EvaluateJSReply::NumberValue(
                match FromJSValConvertible::from_jsval(cx, rval.handle(), ()) {
                    Ok(ConversionResult::Success(v)) => v,
                    _ => unreachable!(),
                },
            )
        } else if rval.is_string() {
            EvaluateJSReply::StringValue(String::from(jsstring_to_str(cx, rval.to_string())))
        } else if rval.is_null() {
            EvaluateJSReply::NullValue
        } else {
            assert!(rval.is_object());

            rooted!(in(cx) let obj = rval.to_object());
            let class_name = CStr::from_ptr(ObjectClassName(cx, obj.handle()));
            let class_name = str::from_utf8(class_name.to_bytes()).unwrap();

            EvaluateJSReply::ActorValue {
                class: class_name.to_owned(),
                uuid: Uuid::new_v4().to_string(),
            }
        }
    };
    reply.send(result).unwrap();
}

pub fn handle_get_root_node(
    documents: &Documents,
    pipeline: PipelineId,
    reply: IpcSender<Option<NodeInfo>>,
) {
    let info = documents
        .find_document(pipeline)
        .map(|document| document.upcast::<Node>().summarize());
    reply.send(info).unwrap();
}

pub fn handle_get_document_element(
    documents: &Documents,
    pipeline: PipelineId,
    reply: IpcSender<Option<NodeInfo>>,
) {
    let info = documents
        .find_document(pipeline)
        .and_then(|document| document.GetDocumentElement())
        .map(|element| element.upcast::<Node>().summarize());
    reply.send(info).unwrap();
}

fn find_node_by_unique_id(
    documents: &Documents,
    pipeline: PipelineId,
    node_id: &str,
) -> Option<DomRoot<Node>> {
    documents.find_document(pipeline).and_then(|document| {
        document
            .upcast::<Node>()
            .traverse_preorder(ShadowIncluding::Yes)
            .find(|candidate| candidate.unique_id() == node_id)
    })
}

pub fn handle_get_children(
    documents: &Documents,
    pipeline: PipelineId,
    node_id: String,
    reply: IpcSender<Option<Vec<NodeInfo>>>,
) {
    match find_node_by_unique_id(documents, pipeline, &*node_id) {
        None => return reply.send(None).unwrap(),
        Some(parent) => {
            let children = parent.children().map(|child| child.summarize()).collect();

            reply.send(Some(children)).unwrap();
        },
    };
}

pub fn handle_get_layout(
    documents: &Documents,
    pipeline: PipelineId,
    node_id: String,
    reply: IpcSender<Option<ComputedNodeLayout>>,
) {
    let node = match find_node_by_unique_id(documents, pipeline, &*node_id) {
        None => return reply.send(None).unwrap(),
        Some(found_node) => found_node,
    };

    let elem = node
        .downcast::<Element>()
        .expect("should be getting layout of element");
    let rect = elem.GetBoundingClientRect();
    let width = rect.Width() as f32;
    let height = rect.Height() as f32;

    let window = window_from_node(&*node);
    let elem = node
        .downcast::<Element>()
        .expect("should be getting layout of element");
    let computed_style = window.GetComputedStyle(elem, None);

    reply
        .send(Some(ComputedNodeLayout {
            display: String::from(computed_style.Display()),
            position: String::from(computed_style.Position()),
            zIndex: String::from(computed_style.ZIndex()),
            boxSizing: String::from(computed_style.BoxSizing()),
            autoMargins: determine_auto_margins(&window, &*node),
            marginTop: String::from(computed_style.MarginTop()),
            marginRight: String::from(computed_style.MarginRight()),
            marginBottom: String::from(computed_style.MarginBottom()),
            marginLeft: String::from(computed_style.MarginLeft()),
            borderTopWidth: String::from(computed_style.BorderTopWidth()),
            borderRightWidth: String::from(computed_style.BorderRightWidth()),
            borderBottomWidth: String::from(computed_style.BorderBottomWidth()),
            borderLeftWidth: String::from(computed_style.BorderLeftWidth()),
            paddingTop: String::from(computed_style.PaddingTop()),
            paddingRight: String::from(computed_style.PaddingRight()),
            paddingBottom: String::from(computed_style.PaddingBottom()),
            paddingLeft: String::from(computed_style.PaddingLeft()),
            width: width,
            height: height,
        }))
        .unwrap();
}

fn determine_auto_margins(window: &Window, node: &Node) -> AutoMargins {
    let style = window.style_query(node.to_trusted_node_address()).unwrap();
    let margin = style.get_margin();
    AutoMargins {
        top: margin.margin_top.is_auto(),
        right: margin.margin_right.is_auto(),
        bottom: margin.margin_bottom.is_auto(),
        left: margin.margin_left.is_auto(),
    }
}

pub fn handle_get_cached_messages(
    _pipeline_id: PipelineId,
    message_types: CachedConsoleMessageTypes,
    reply: IpcSender<Vec<CachedConsoleMessage>>,
) {
    // TODO: check the messageTypes against a global Cache for console messages and page exceptions
    let mut messages = Vec::new();
    if message_types.contains(CachedConsoleMessageTypes::PAGE_ERROR) {
        // TODO: make script error reporter pass all reported errors
        //      to devtools and cache them for returning here.
        let msg = PageError {
            type_: "PageError".to_owned(),
            errorMessage: "page error test".to_owned(),
            sourceName: String::new(),
            lineText: String::new(),
            lineNumber: 0,
            columnNumber: 0,
            category: String::new(),
            timeStamp: 0,
            error: false,
            warning: false,
            exception: false,
            strict: false,
            private: false,
        };
        messages.push(CachedConsoleMessage::PageError(msg));
    }
    if message_types.contains(CachedConsoleMessageTypes::CONSOLE_API) {
        // TODO: do for real
        let msg = ConsoleAPI {
            type_: "ConsoleAPI".to_owned(),
            level: "error".to_owned(),
            filename: "http://localhost/~mihai/mozilla/test.html".to_owned(),
            lineNumber: 0,
            functionName: String::new(),
            timeStamp: 0,
            private: false,
            arguments: vec!["console error test".to_owned()],
        };
        messages.push(CachedConsoleMessage::ConsoleAPI(msg));
    }
    reply.send(messages).unwrap();
}

pub fn handle_modify_attribute(
    documents: &Documents,
    pipeline: PipelineId,
    node_id: String,
    modifications: Vec<Modification>,
) {
    let node = match find_node_by_unique_id(documents, pipeline, &*node_id) {
        None => {
            return warn!(
                "node id {} for pipeline id {} is not found",
                &node_id, &pipeline
            );
        },
        Some(found_node) => found_node,
    };

    let elem = node
        .downcast::<Element>()
        .expect("should be getting layout of element");

    for modification in modifications {
        match modification.newValue {
            Some(string) => {
                let _ = elem.SetAttribute(
                    DOMString::from(modification.attributeName),
                    DOMString::from(string),
                );
            },
            None => elem.RemoveAttribute(DOMString::from(modification.attributeName)),
        }
    }
}

pub fn handle_wants_live_notifications(global: &GlobalScope, send_notifications: bool) {
    global.set_devtools_wants_updates(send_notifications);
}

pub fn handle_set_timeline_markers(
    documents: &Documents,
    pipeline: PipelineId,
    marker_types: Vec<TimelineMarkerType>,
    reply: IpcSender<Option<TimelineMarker>>,
) {
    match documents.find_window(pipeline) {
        None => reply.send(None).unwrap(),
        Some(window) => window.set_devtools_timeline_markers(marker_types, reply),
    }
}

pub fn handle_drop_timeline_markers(
    documents: &Documents,
    pipeline: PipelineId,
    marker_types: Vec<TimelineMarkerType>,
) {
    if let Some(window) = documents.find_window(pipeline) {
        window.drop_devtools_timeline_markers(marker_types);
    }
}

pub fn handle_request_animation_frame(documents: &Documents, id: PipelineId, actor_name: String) {
    if let Some(doc) = documents.find_document(id) {
        doc.request_animation_frame(AnimationFrameCallback::DevtoolsFramerateTick { actor_name });
    }
}

pub fn handle_reload(documents: &Documents, id: PipelineId) {
    if let Some(win) = documents.find_window(id) {
        win.Location().reload_without_origin_check();
    }
}
<|endoftext|>


<commit_before>//! Implements the ODBC Environment
mod list_data_sources;
pub use self::list_data_sources::{DataSourceInfo, DriverInfo};
use super::{ffi, into_result, safe, try_into_option, DiagnosticRecord, GetDiagRec, Handle, Result};
use std;

/// Environment state used to represent that environment has been set to odbc version 3
pub type Version3 = safe::Odbc3;

/// Handle to an ODBC Environment
///
/// Creating an instance of this type is the first thing you do then using ODBC. The environment
/// must outlive all connections created with it.
pub struct Environment<V> {
    safe: safe::Environment<V>,
}

impl<V> Handle for Environment<V> {
    type To = ffi::Env;
    unsafe fn handle(&self) -> ffi::SQLHENV {
        self.safe.as_raw()
    }
}

impl<V: safe::Version> Environment<V> {
    /// Creates an ODBC Environment and declares specifaciton of `V` are used
    ///
    /// # Example
    /// ```
    /// use odbc::*;
    /// fn do_database_stuff() -> std::result::Result<(), Option<DiagnosticRecord>> {
    ///     let env : Environment<Version3> = Environment::new()?; // first thing to do
    ///     // ...
    ///     Ok(())
    /// }
    /// ```
    ///
    /// You can use the shorthand `create_environment_v3()` instead.
    pub fn new() -> std::result::Result<Environment<V>, Option<DiagnosticRecord>> {
        let safe = match safe::Environment::new() {
            safe::Success(v) => v,
            safe::Info(v) => {
                warn!("{}", v.get_diag_rec(1).unwrap());
                v
            }
            safe::Error(()) => return Err(None),
        };
        let safe = into_result(safe.declare_version())?;
        Ok(Environment { safe })
    }
}

unsafe impl<V> safe::Handle for Environment<V> {
    fn handle(&self) -> ffi::SQLHANDLE {
        self.safe.as_raw() as ffi::SQLHANDLE
    }

    fn handle_type() -> ffi::HandleType {
        ffi::SQL_HANDLE_ENV
    }
}

/// Creates an ODBC Environment and declares specifaciton of version 3.0 are used
///
/// # Example
/// ```
/// use odbc::*;
/// fn do_database_stuff() -> std::result::Result<(), Option<DiagnosticRecord>> {
///     let env = create_environment_v3()?; // first thing to do
///     // ...
///     Ok(())
/// }
/// ```
pub fn create_environment_v3()
    -> std::result::Result<Environment<Version3>, Option<DiagnosticRecord>>
{
    Environment::new()
}
<commit_msg>explain Result<_, Option<DiagRec>><commit_after>//! Implements the ODBC Environment
mod list_data_sources;
pub use self::list_data_sources::{DataSourceInfo, DriverInfo};
use super::{ffi, into_result, safe, try_into_option, DiagnosticRecord, GetDiagRec, Handle, Result};
use std;

/// Environment state used to represent that environment has been set to odbc version 3
pub type Version3 = safe::Odbc3;

/// Handle to an ODBC Environment
///
/// Creating an instance of this type is the first thing you do then using ODBC. The environment
/// must outlive all connections created with it.
pub struct Environment<V> {
    safe: safe::Environment<V>,
}

impl<V> Handle for Environment<V> {
    type To = ffi::Env;
    unsafe fn handle(&self) -> ffi::SQLHENV {
        self.safe.as_raw()
    }
}

impl<V: safe::Version> Environment<V> {
    /// Creates an ODBC Environment and declares specifaciton of `V` are used. You can use the
    /// shorthand `create_environment_v3()` instead.
    ///
    /// # Example
    /// ```
    /// use odbc::*;
    /// fn do_database_stuff() -> std::result::Result<(), Option<DiagnosticRecord>> {
    ///     let env : Environment<Version3> = Environment::new()?; // first thing to do
    ///     // ...
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Return
    ///
    /// While most functions in this crate return a `DiagnosticRecord` in the event of an Error the
    /// creation of an environment is special. Since `DiagnosticRecord`s are created using the
    /// environment, at least its allocation has to be successful to obtain one. If the allocation
    /// fails it is sadly not possible to receive further Diagnostics. Setting an unsupported version
    /// may however result in an ordinary `Some(DiagnosticRecord)`.
    /// ```
    pub fn new() -> std::result::Result<Environment<V>, Option<DiagnosticRecord>> {
        let safe = match safe::Environment::new() {
            safe::Success(v) => v,
            safe::Info(v) => {
                warn!("{}", v.get_diag_rec(1).unwrap());
                v
            }
            safe::Error(()) => return Err(None),
        };
        let safe = into_result(safe.declare_version())?;
        Ok(Environment { safe })
    }
}

unsafe impl<V> safe::Handle for Environment<V> {
    fn handle(&self) -> ffi::SQLHANDLE {
        self.safe.as_raw() as ffi::SQLHANDLE
    }

    fn handle_type() -> ffi::HandleType {
        ffi::SQL_HANDLE_ENV
    }
}

/// Creates an ODBC Environment and declares specifaciton of version 3.0 are used
///
/// # Example
/// ```
/// use odbc::*;
/// fn do_database_stuff() -> std::result::Result<(), Option<DiagnosticRecord>> {
///     let env = create_environment_v3()?; // first thing to do
///     // ...
///     Ok(())
/// }
/// ```
///
/// # Return
///
/// While most functions in this crate return a `DiagnosticRecord` in the event of an Error the
/// creation of an environment is special. Since `DiagnosticRecord`s are created using the
/// environment, at least its allocation has to be successful to obtain one. If the allocation
/// fails it is sadly not possible to receive further Diagnostics. Setting an unsupported version
/// may however result in an ordinary `Some(DiagnosticRecord)`.
pub fn create_environment_v3()
    -> std::result::Result<Environment<Version3>, Option<DiagnosticRecord>>
{
    Environment::new()
}
<|endoftext|>


<commit_before>use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

use crate::runtime::Handle;
use crate::task::{JoinError, JoinHandle, LocalSet};
use crate::util::IdleNotifiedSet;

/// A collection of tasks spawned on a Tokio runtime.
///
/// A `JoinSet` can be used to await the completion of some or all of the tasks
/// in the set. The set is not ordered, and the tasks will be returned in the
/// order they complete.
///
/// All of the tasks must have the same return type `T`.
///
/// When the `JoinSet` is dropped, all tasks in the `JoinSet` are immediately aborted.
///
/// **Note**: This is an [unstable API][unstable]. The public API of this type
/// may break in 1.x releases. See [the documentation on unstable
/// features][unstable] for details.
///
/// # Examples
///
/// Spawn multiple tasks and wait for them.
///
/// ```
/// use tokio::task::JoinSet;
///
/// #[tokio::main]
/// async fn main() {
///     let mut set = JoinSet::new();
///
///     for i in 0..10 {
///         set.spawn(async move { i });
///     }
///
///     let mut seen = [false; 10];
///     while let Some(res) = set.join_one().await.unwrap() {
///         seen[res] = true;
///     }
///
///     for i in 0..10 {
///         assert!(seen[i]);
///     }
/// }
/// ```
///
/// [unstable]: crate#unstable-features
pub struct JoinSet<T> {
    inner: IdleNotifiedSet<JoinHandle<T>>,
}

impl<T> JoinSet<T> {
    /// Create a new `JoinSet`.
    pub fn new() -> Self {
        Self {
            inner: IdleNotifiedSet::new(),
        }
    }

    /// Returns the number of tasks currently in the `JoinSet`.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns whether the `JoinSet` is empty.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }
}

impl<T: 'static> JoinSet<T> {
    /// Spawn the provided task on the `JoinSet`.
    ///
    /// # Panics
    ///
    /// This method panics if called outside of a Tokio runtime.
    pub fn spawn<F>(&mut self, task: F)
    where
        F: Future<Output = T>,
        F: Send + 'static,
        T: Send,
    {
        self.insert(crate::spawn(task));
    }

    /// Spawn the provided task on the provided runtime and store it in this `JoinSet`.
    pub fn spawn_on<F>(&mut self, task: F, handle: &Handle)
    where
        F: Future<Output = T>,
        F: Send + 'static,
        T: Send,
    {
        self.insert(handle.spawn(task));
    }

    /// Spawn the provided task on the current [`LocalSet`] and store it in this `JoinSet`.
    ///
    /// # Panics
    ///
    /// This method panics if it is called outside of a `LocalSet`.
    ///
    /// [`LocalSet`]: crate::task::LocalSet
    pub fn spawn_local<F>(&mut self, task: F)
    where
        F: Future<Output = T>,
        F: 'static,
    {
        self.insert(crate::task::spawn_local(task));
    }

    /// Spawn the provided task on the provided [`LocalSet`] and store it in this `JoinSet`.
    ///
    /// [`LocalSet`]: crate::task::LocalSet
    pub fn spawn_local_on<F>(&mut self, task: F, local_set: &LocalSet)
    where
        F: Future<Output = T>,
        F: 'static,
    {
        self.insert(local_set.spawn_local(task));
    }

    fn insert(&mut self, jh: JoinHandle<T>) {
        let mut entry = self.inner.insert_idle(jh);

        // Set the waker that is notified when the task completes.
        entry.with_value_and_context(|jh, ctx| jh.set_join_waker(ctx.waker()));
    }

    /// Waits until one of the tasks in the set completes and returns its output.
    ///
    /// Returns `None` if the set is empty.
    ///
    /// # Cancel Safety
    ///
    /// This method is cancel safe. If `join_one` is used as the event in a `tokio::select!`
    /// statement and some other branch completes first, it is guaranteed that no tasks were
    /// removed from this `JoinSet`.
    pub async fn join_one(&mut self) -> Result<Option<T>, JoinError> {
        crate::future::poll_fn(|cx| self.poll_join_one(cx)).await
    }

    /// Aborts all tasks and waits for them to finish shutting down.
    ///
    /// Calling this method is equivalent to calling [`abort_all`] and then calling [`join_one`] in
    /// a loop until it returns `Ok(None)`.
    ///
    /// This method ignores any panics in the tasks shutting down. When this call returns, the
    /// `JoinSet` will be empty.
    ///
    /// [`abort_all`]: fn@Self::abort_all
    /// [`join_one`]: fn@Self::join_one
    pub async fn shutdown(&mut self) {
        self.abort_all();
        while self.join_one().await.transpose().is_some() {}
    }

    /// Aborts all tasks on this `JoinSet`.
    ///
    /// This does not remove the tasks from the `JoinSet`. To wait for the tasks to complete
    /// cancellation, you should call `join_one` in a loop until the `JoinSet` is empty.
    pub fn abort_all(&mut self) {
        self.inner.for_each(|jh| jh.abort());
    }

    /// Removes all tasks from this `JoinSet` without aborting them.
    ///
    /// The tasks removed by this call will continue to run in the background even if the `JoinSet`
    /// is dropped.
    pub fn detach_all(&mut self) {
        self.inner.drain(drop);
    }

    /// Polls for one of the tasks in the set to complete.
    ///
    /// If this returns `Poll::Ready(Ok(Some(_)))` or `Poll::Ready(Err(_))`, then the task that
    /// completed is removed from the set.
    ///
    /// When the method returns `Poll::Pending`, the `Waker` in the provided `Context` is scheduled
    /// to receive a wakeup when a task in the `JoinSet` completes. Note that on multiple calls to
    /// `poll_join_one`, only the `Waker` from the `Context` passed to the most recent call is
    /// scheduled to receive a wakeup.
    ///
    /// # Returns
    ///
    /// This function returns:
    ///
    ///  * `Poll::Pending` if the `JoinSet` is not empty but there is no task whose output is
    ///     available right now.
    ///  * `Poll::Ready(Ok(Some(value)))` if one of the tasks in this `JoinSet` has completed. The
    ///    `value` is the return value of one of the tasks that completed.
    ///  * `Poll::Ready(Err(err))` if one of the tasks in this `JoinSet` has panicked or been
    ///     aborted.
    ///  * `Poll::Ready(Ok(None))` if the `JoinSet` is empty.
    ///
    /// Note that this method may return `Poll::Pending` even if one of the tasks has completed.
    /// This can happen if the [coop budget] is reached.
    ///
    /// [coop budget]: crate::task#cooperative-scheduling
    fn poll_join_one(&mut self, cx: &mut Context<'_>) -> Poll<Result<Option<T>, JoinError>> {
        // The call to `pop_notified` moves the entry to the `idle` list. It is moved back to
        // the `notified` list if the waker is notified in the `poll` call below.
        let mut entry = match self.inner.pop_notified(cx.waker()) {
            Some(entry) => entry,
            None => {
                if self.is_empty() {
                    return Poll::Ready(Ok(None));
                } else {
                    // The waker was set by `pop_notified`.
                    return Poll::Pending;
                }
            }
        };

        let res = entry.with_value_and_context(|jh, ctx| Pin::new(jh).poll(ctx));

        if let Poll::Ready(res) = res {
            entry.remove();
            Poll::Ready(Some(res).transpose())
        } else {
            // A JoinHandle generally won't emit a wakeup without being ready unless
            // the coop limit has been reached. We yield to the executor in this
            // case.
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    }
}

impl<T> Drop for JoinSet<T> {
    fn drop(&mut self) {
        self.inner.drain(|join_handle| join_handle.abort());
    }
}

impl<T> fmt::Debug for JoinSet<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("JoinSet").field("len", &self.len()).finish()
    }
}

impl<T> Default for JoinSet<T> {
    fn default() -> Self {
        Self::new()
    }
}
<commit_msg>task: fix missing doc(cfg(...)) attributes for `JoinSet` (#4531)<commit_after>use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

use crate::runtime::Handle;
use crate::task::{JoinError, JoinHandle, LocalSet};
use crate::util::IdleNotifiedSet;

/// A collection of tasks spawned on a Tokio runtime.
///
/// A `JoinSet` can be used to await the completion of some or all of the tasks
/// in the set. The set is not ordered, and the tasks will be returned in the
/// order they complete.
///
/// All of the tasks must have the same return type `T`.
///
/// When the `JoinSet` is dropped, all tasks in the `JoinSet` are immediately aborted.
///
/// **Note**: This is an [unstable API][unstable]. The public API of this type
/// may break in 1.x releases. See [the documentation on unstable
/// features][unstable] for details.
///
/// # Examples
///
/// Spawn multiple tasks and wait for them.
///
/// ```
/// use tokio::task::JoinSet;
///
/// #[tokio::main]
/// async fn main() {
///     let mut set = JoinSet::new();
///
///     for i in 0..10 {
///         set.spawn(async move { i });
///     }
///
///     let mut seen = [false; 10];
///     while let Some(res) = set.join_one().await.unwrap() {
///         seen[res] = true;
///     }
///
///     for i in 0..10 {
///         assert!(seen[i]);
///     }
/// }
/// ```
///
/// [unstable]: crate#unstable-features
#[cfg_attr(docsrs, doc(cfg(all(feature = "rt", tokio_unstable))))]
pub struct JoinSet<T> {
    inner: IdleNotifiedSet<JoinHandle<T>>,
}

impl<T> JoinSet<T> {
    /// Create a new `JoinSet`.
    pub fn new() -> Self {
        Self {
            inner: IdleNotifiedSet::new(),
        }
    }

    /// Returns the number of tasks currently in the `JoinSet`.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns whether the `JoinSet` is empty.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }
}

impl<T: 'static> JoinSet<T> {
    /// Spawn the provided task on the `JoinSet`.
    ///
    /// # Panics
    ///
    /// This method panics if called outside of a Tokio runtime.
    pub fn spawn<F>(&mut self, task: F)
    where
        F: Future<Output = T>,
        F: Send + 'static,
        T: Send,
    {
        self.insert(crate::spawn(task));
    }

    /// Spawn the provided task on the provided runtime and store it in this `JoinSet`.
    pub fn spawn_on<F>(&mut self, task: F, handle: &Handle)
    where
        F: Future<Output = T>,
        F: Send + 'static,
        T: Send,
    {
        self.insert(handle.spawn(task));
    }

    /// Spawn the provided task on the current [`LocalSet`] and store it in this `JoinSet`.
    ///
    /// # Panics
    ///
    /// This method panics if it is called outside of a `LocalSet`.
    ///
    /// [`LocalSet`]: crate::task::LocalSet
    pub fn spawn_local<F>(&mut self, task: F)
    where
        F: Future<Output = T>,
        F: 'static,
    {
        self.insert(crate::task::spawn_local(task));
    }

    /// Spawn the provided task on the provided [`LocalSet`] and store it in this `JoinSet`.
    ///
    /// [`LocalSet`]: crate::task::LocalSet
    pub fn spawn_local_on<F>(&mut self, task: F, local_set: &LocalSet)
    where
        F: Future<Output = T>,
        F: 'static,
    {
        self.insert(local_set.spawn_local(task));
    }

    fn insert(&mut self, jh: JoinHandle<T>) {
        let mut entry = self.inner.insert_idle(jh);

        // Set the waker that is notified when the task completes.
        entry.with_value_and_context(|jh, ctx| jh.set_join_waker(ctx.waker()));
    }

    /// Waits until one of the tasks in the set completes and returns its output.
    ///
    /// Returns `None` if the set is empty.
    ///
    /// # Cancel Safety
    ///
    /// This method is cancel safe. If `join_one` is used as the event in a `tokio::select!`
    /// statement and some other branch completes first, it is guaranteed that no tasks were
    /// removed from this `JoinSet`.
    pub async fn join_one(&mut self) -> Result<Option<T>, JoinError> {
        crate::future::poll_fn(|cx| self.poll_join_one(cx)).await
    }

    /// Aborts all tasks and waits for them to finish shutting down.
    ///
    /// Calling this method is equivalent to calling [`abort_all`] and then calling [`join_one`] in
    /// a loop until it returns `Ok(None)`.
    ///
    /// This method ignores any panics in the tasks shutting down. When this call returns, the
    /// `JoinSet` will be empty.
    ///
    /// [`abort_all`]: fn@Self::abort_all
    /// [`join_one`]: fn@Self::join_one
    pub async fn shutdown(&mut self) {
        self.abort_all();
        while self.join_one().await.transpose().is_some() {}
    }

    /// Aborts all tasks on this `JoinSet`.
    ///
    /// This does not remove the tasks from the `JoinSet`. To wait for the tasks to complete
    /// cancellation, you should call `join_one` in a loop until the `JoinSet` is empty.
    pub fn abort_all(&mut self) {
        self.inner.for_each(|jh| jh.abort());
    }

    /// Removes all tasks from this `JoinSet` without aborting them.
    ///
    /// The tasks removed by this call will continue to run in the background even if the `JoinSet`
    /// is dropped.
    pub fn detach_all(&mut self) {
        self.inner.drain(drop);
    }

    /// Polls for one of the tasks in the set to complete.
    ///
    /// If this returns `Poll::Ready(Ok(Some(_)))` or `Poll::Ready(Err(_))`, then the task that
    /// completed is removed from the set.
    ///
    /// When the method returns `Poll::Pending`, the `Waker` in the provided `Context` is scheduled
    /// to receive a wakeup when a task in the `JoinSet` completes. Note that on multiple calls to
    /// `poll_join_one`, only the `Waker` from the `Context` passed to the most recent call is
    /// scheduled to receive a wakeup.
    ///
    /// # Returns
    ///
    /// This function returns:
    ///
    ///  * `Poll::Pending` if the `JoinSet` is not empty but there is no task whose output is
    ///     available right now.
    ///  * `Poll::Ready(Ok(Some(value)))` if one of the tasks in this `JoinSet` has completed. The
    ///    `value` is the return value of one of the tasks that completed.
    ///  * `Poll::Ready(Err(err))` if one of the tasks in this `JoinSet` has panicked or been
    ///     aborted.
    ///  * `Poll::Ready(Ok(None))` if the `JoinSet` is empty.
    ///
    /// Note that this method may return `Poll::Pending` even if one of the tasks has completed.
    /// This can happen if the [coop budget] is reached.
    ///
    /// [coop budget]: crate::task#cooperative-scheduling
    fn poll_join_one(&mut self, cx: &mut Context<'_>) -> Poll<Result<Option<T>, JoinError>> {
        // The call to `pop_notified` moves the entry to the `idle` list. It is moved back to
        // the `notified` list if the waker is notified in the `poll` call below.
        let mut entry = match self.inner.pop_notified(cx.waker()) {
            Some(entry) => entry,
            None => {
                if self.is_empty() {
                    return Poll::Ready(Ok(None));
                } else {
                    // The waker was set by `pop_notified`.
                    return Poll::Pending;
                }
            }
        };

        let res = entry.with_value_and_context(|jh, ctx| Pin::new(jh).poll(ctx));

        if let Poll::Ready(res) = res {
            entry.remove();
            Poll::Ready(Some(res).transpose())
        } else {
            // A JoinHandle generally won't emit a wakeup without being ready unless
            // the coop limit has been reached. We yield to the executor in this
            // case.
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    }
}

impl<T> Drop for JoinSet<T> {
    fn drop(&mut self) {
        self.inner.drain(|join_handle| join_handle.abort());
    }
}

impl<T> fmt::Debug for JoinSet<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("JoinSet").field("len", &self.len()).finish()
    }
}

impl<T> Default for JoinSet<T> {
    fn default() -> Self {
        Self::new()
    }
}
<|endoftext|>