<commit_before>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Unix-specific extensions to primitives in the `std::fs` module.

#![stable(feature = "rust1", since = "1.0.0")]

use prelude::v1::*;

use fs::{self, Permissions, OpenOptions};
use io;
use mem;
use os::raw::c_long;
use os::unix::raw;
use path::Path;
use sys::platform;
use sys;
use sys_common::{FromInner, AsInner, AsInnerMut};

#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_READ: raw::mode_t = 0o400;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_WRITE: raw::mode_t = 0o200;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_EXECUTE: raw::mode_t = 0o100;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_RWX: raw::mode_t = 0o700;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_READ: raw::mode_t = 0o040;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_WRITE: raw::mode_t = 0o020;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_EXECUTE: raw::mode_t = 0o010;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_RWX: raw::mode_t = 0o070;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_READ: raw::mode_t = 0o004;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_WRITE: raw::mode_t = 0o002;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_EXECUTE: raw::mode_t = 0o001;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_RWX: raw::mode_t = 0o007;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_READ: raw::mode_t = 0o444;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_WRITE: raw::mode_t = 0o222;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_EXECUTE: raw::mode_t = 0o111;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_RWX: raw::mode_t = 0o777;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const SETUID: raw::mode_t = 0o4000;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const SETGID: raw::mode_t = 0o2000;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const STICKY_BIT: raw::mode_t = 0o1000;

/// Unix-specific extensions to `Permissions`
#[unstable(feature = "fs_ext",
           reason = "may want a more useful mode abstraction")]
pub trait PermissionsExt {
    fn mode(&self) -> raw::mode_t;
    fn set_mode(&mut self, mode: raw::mode_t);
    fn from_mode(mode: raw::mode_t) -> Self;
}

impl PermissionsExt for Permissions {
    fn mode(&self) -> raw::mode_t { self.as_inner().mode() }

    fn set_mode(&mut self, mode: raw::mode_t) {
        *self = FromInner::from_inner(FromInner::from_inner(mode));
    }

    fn from_mode(mode: raw::mode_t) -> Permissions {
        FromInner::from_inner(FromInner::from_inner(mode))
    }
}

/// Unix-specific extensions to `OpenOptions`
#[unstable(feature = "fs_ext",
           reason = "may want a more useful mode abstraction")]
pub trait OpenOptionsExt {
    /// Sets the mode bits that a new file will be created with.
    ///
    /// If a new file is created as part of a `File::open_opts` call then this
    /// specified `mode` will be used as the permission bits for the new file.
    fn mode(&mut self, mode: raw::mode_t) -> &mut Self;
}

impl OpenOptionsExt for OpenOptions {
    fn mode(&mut self, mode: raw::mode_t) -> &mut OpenOptions {
        self.as_inner_mut().mode(mode); self
    }
}

#[unstable(feature = "metadata_ext", reason = "recently added API")]
pub struct Metadata(sys::fs2::FileAttr);

#[unstable(feature = "metadata_ext", reason = "recently added API")]
pub trait MetadataExt {
    fn as_raw(&self) -> &Metadata;
}

impl MetadataExt for fs::Metadata {
    fn as_raw(&self) -> &Metadata {
        let inner: &sys::fs2::FileAttr = self.as_inner();
        unsafe { mem::transmute(inner) }
    }
}

impl AsInner<platform::raw::stat> for Metadata {
    fn as_inner(&self) -> &platform::raw::stat { self.0.as_inner() }
}

// Hm, why are there casts here to the returned type, shouldn't the types always
// be the same? Right you are! Turns out, however, on android at least the types
// in the raw `stat` structure are not the same as the types being returned. Who
// knew!
//
// As a result to make sure this compiles for all platforms we do the manual
// casts and rely on manual lowering to `stat` if the raw type is desired.
#[unstable(feature = "metadata_ext", reason = "recently added API")]
impl Metadata {
    pub fn dev(&self) -> raw::dev_t { self.0.raw().st_dev as raw::dev_t }
    pub fn ino(&self) -> raw::ino_t { self.0.raw().st_ino as raw::ino_t }
    pub fn mode(&self) -> raw::mode_t { self.0.raw().st_mode as raw::mode_t }
    pub fn nlink(&self) -> raw::nlink_t { self.0.raw().st_nlink as raw::nlink_t }
    pub fn uid(&self) -> raw::uid_t { self.0.raw().st_uid as raw::uid_t }
    pub fn gid(&self) -> raw::gid_t { self.0.raw().st_gid as raw::gid_t }
    pub fn rdev(&self) -> raw::dev_t { self.0.raw().st_rdev as raw::dev_t }
    pub fn size(&self) -> raw::off_t { self.0.raw().st_size as raw::off_t }
    pub fn atime(&self) -> raw::time_t { self.0.raw().st_atime }
    pub fn atime_nsec(&self) -> c_long { self.0.raw().st_atime }
    pub fn mtime(&self) -> raw::time_t { self.0.raw().st_mtime }
    pub fn mtime_nsec(&self) -> c_long { self.0.raw().st_mtime }
    pub fn ctime(&self) -> raw::time_t { self.0.raw().st_ctime }
    pub fn ctime_nsec(&self) -> c_long { self.0.raw().st_ctime }

    pub fn blksize(&self) -> raw::blksize_t {
        self.0.raw().st_blksize as raw::blksize_t
    }
    pub fn blocks(&self) -> raw::blkcnt_t {
        self.0.raw().st_blocks as raw::blkcnt_t
    }
}

#[unstable(feature = "dir_entry_ext", reason = "recently added API")]
pub trait DirEntryExt {
    fn ino(&self) -> raw::ino_t;
}

impl DirEntryExt for fs::DirEntry {
    fn ino(&self) -> raw::ino_t { self.as_inner().ino() }
}

/// Creates a new symbolic link on the filesystem.
///
/// The `dst` path will be a symbolic link pointing to the `src` path.
///
/// # Note
///
/// On Windows, you must specify whether a symbolic link points to a file
/// or directory.  Use `os::windows::fs::symlink_file` to create a
/// symbolic link to a file, or `os::windows::fs::symlink_dir` to create a
/// symbolic link to a directory.  Additionally, the process must have
/// `SeCreateSymbolicLinkPrivilege` in order to be able to create a
/// symbolic link.
///
/// # Examples
///
/// ```
/// use std::os::unix::fs;
///
/// # fn foo() -> std::io::Result<()> {
/// try!(fs::symlink("a.txt", "b.txt"));
/// # Ok(())
/// # }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()>
{
    sys::fs2::symlink(src.as_ref(), dst.as_ref())
}

#[unstable(feature = "dir_builder", reason = "recently added API")]
/// An extension trait for `fs::DirBuilder` for unix-specific options.
pub trait DirBuilderExt {
    /// Sets the mode to create new directories with. This option defaults to
    /// 0o777.
    fn mode(&mut self, mode: raw::mode_t) -> &mut Self;
}

impl DirBuilderExt for fs::DirBuilder {
    fn mode(&mut self, mode: raw::mode_t) -> &mut fs::DirBuilder {
        self.as_inner_mut().set_mode(mode);
        self
    }
}

<commit_msg>Rollup merge of #25079 - alexcrichton:fix-nsec, r=aturon<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Unix-specific extensions to primitives in the `std::fs` module.

#![stable(feature = "rust1", since = "1.0.0")]

use prelude::v1::*;

use fs::{self, Permissions, OpenOptions};
use io;
use mem;
use os::raw::c_long;
use os::unix::raw;
use path::Path;
use sys::platform;
use sys;
use sys_common::{FromInner, AsInner, AsInnerMut};

#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_READ: raw::mode_t = 0o400;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_WRITE: raw::mode_t = 0o200;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_EXECUTE: raw::mode_t = 0o100;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_RWX: raw::mode_t = 0o700;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_READ: raw::mode_t = 0o040;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_WRITE: raw::mode_t = 0o020;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_EXECUTE: raw::mode_t = 0o010;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_RWX: raw::mode_t = 0o070;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_READ: raw::mode_t = 0o004;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_WRITE: raw::mode_t = 0o002;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_EXECUTE: raw::mode_t = 0o001;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_RWX: raw::mode_t = 0o007;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_READ: raw::mode_t = 0o444;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_WRITE: raw::mode_t = 0o222;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_EXECUTE: raw::mode_t = 0o111;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_RWX: raw::mode_t = 0o777;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const SETUID: raw::mode_t = 0o4000;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const SETGID: raw::mode_t = 0o2000;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const STICKY_BIT: raw::mode_t = 0o1000;

/// Unix-specific extensions to `Permissions`
#[unstable(feature = "fs_ext",
           reason = "may want a more useful mode abstraction")]
pub trait PermissionsExt {
    fn mode(&self) -> raw::mode_t;
    fn set_mode(&mut self, mode: raw::mode_t);
    fn from_mode(mode: raw::mode_t) -> Self;
}

impl PermissionsExt for Permissions {
    fn mode(&self) -> raw::mode_t { self.as_inner().mode() }

    fn set_mode(&mut self, mode: raw::mode_t) {
        *self = FromInner::from_inner(FromInner::from_inner(mode));
    }

    fn from_mode(mode: raw::mode_t) -> Permissions {
        FromInner::from_inner(FromInner::from_inner(mode))
    }
}

/// Unix-specific extensions to `OpenOptions`
#[unstable(feature = "fs_ext",
           reason = "may want a more useful mode abstraction")]
pub trait OpenOptionsExt {
    /// Sets the mode bits that a new file will be created with.
    ///
    /// If a new file is created as part of a `File::open_opts` call then this
    /// specified `mode` will be used as the permission bits for the new file.
    fn mode(&mut self, mode: raw::mode_t) -> &mut Self;
}

impl OpenOptionsExt for OpenOptions {
    fn mode(&mut self, mode: raw::mode_t) -> &mut OpenOptions {
        self.as_inner_mut().mode(mode); self
    }
}

#[unstable(feature = "metadata_ext", reason = "recently added API")]
pub struct Metadata(sys::fs2::FileAttr);

#[unstable(feature = "metadata_ext", reason = "recently added API")]
pub trait MetadataExt {
    fn as_raw(&self) -> &Metadata;
}

impl MetadataExt for fs::Metadata {
    fn as_raw(&self) -> &Metadata {
        let inner: &sys::fs2::FileAttr = self.as_inner();
        unsafe { mem::transmute(inner) }
    }
}

impl AsInner<platform::raw::stat> for Metadata {
    fn as_inner(&self) -> &platform::raw::stat { self.0.as_inner() }
}

// Hm, why are there casts here to the returned type, shouldn't the types always
// be the same? Right you are! Turns out, however, on android at least the types
// in the raw `stat` structure are not the same as the types being returned. Who
// knew!
//
// As a result to make sure this compiles for all platforms we do the manual
// casts and rely on manual lowering to `stat` if the raw type is desired.
#[unstable(feature = "metadata_ext", reason = "recently added API")]
impl Metadata {
    pub fn dev(&self) -> raw::dev_t { self.0.raw().st_dev as raw::dev_t }
    pub fn ino(&self) -> raw::ino_t { self.0.raw().st_ino as raw::ino_t }
    pub fn mode(&self) -> raw::mode_t { self.0.raw().st_mode as raw::mode_t }
    pub fn nlink(&self) -> raw::nlink_t { self.0.raw().st_nlink as raw::nlink_t }
    pub fn uid(&self) -> raw::uid_t { self.0.raw().st_uid as raw::uid_t }
    pub fn gid(&self) -> raw::gid_t { self.0.raw().st_gid as raw::gid_t }
    pub fn rdev(&self) -> raw::dev_t { self.0.raw().st_rdev as raw::dev_t }
    pub fn size(&self) -> raw::off_t { self.0.raw().st_size as raw::off_t }
    pub fn atime(&self) -> raw::time_t { self.0.raw().st_atime }
    pub fn atime_nsec(&self) -> c_long { self.0.raw().st_atime_nsec as c_long }
    pub fn mtime(&self) -> raw::time_t { self.0.raw().st_mtime }
    pub fn mtime_nsec(&self) -> c_long { self.0.raw().st_mtime_nsec as c_long }
    pub fn ctime(&self) -> raw::time_t { self.0.raw().st_ctime }
    pub fn ctime_nsec(&self) -> c_long { self.0.raw().st_ctime_nsec as c_long }

    pub fn blksize(&self) -> raw::blksize_t {
        self.0.raw().st_blksize as raw::blksize_t
    }
    pub fn blocks(&self) -> raw::blkcnt_t {
        self.0.raw().st_blocks as raw::blkcnt_t
    }
}

#[unstable(feature = "dir_entry_ext", reason = "recently added API")]
pub trait DirEntryExt {
    fn ino(&self) -> raw::ino_t;
}

impl DirEntryExt for fs::DirEntry {
    fn ino(&self) -> raw::ino_t { self.as_inner().ino() }
}

/// Creates a new symbolic link on the filesystem.
///
/// The `dst` path will be a symbolic link pointing to the `src` path.
///
/// # Note
///
/// On Windows, you must specify whether a symbolic link points to a file
/// or directory.  Use `os::windows::fs::symlink_file` to create a
/// symbolic link to a file, or `os::windows::fs::symlink_dir` to create a
/// symbolic link to a directory.  Additionally, the process must have
/// `SeCreateSymbolicLinkPrivilege` in order to be able to create a
/// symbolic link.
///
/// # Examples
///
/// ```
/// use std::os::unix::fs;
///
/// # fn foo() -> std::io::Result<()> {
/// try!(fs::symlink("a.txt", "b.txt"));
/// # Ok(())
/// # }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()>
{
    sys::fs2::symlink(src.as_ref(), dst.as_ref())
}

#[unstable(feature = "dir_builder", reason = "recently added API")]
/// An extension trait for `fs::DirBuilder` for unix-specific options.
pub trait DirBuilderExt {
    /// Sets the mode to create new directories with. This option defaults to
    /// 0o777.
    fn mode(&mut self, mode: raw::mode_t) -> &mut Self;
}

impl DirBuilderExt for fs::DirBuilder {
    fn mode(&mut self, mode: raw::mode_t) -> &mut fs::DirBuilder {
        self.as_inner_mut().set_mode(mode);
        self
    }
}

<|endoftext|>


<commit_before>// An attribute to hide warnings for unused code.
#![allow(dead_code)]

// Create an `enum` to classify someone. Note how both names
// and type information together specify the variant:
// `Skinny != Fat` and `Height(i32) != Weight(i32)`. Each
// is different and independent.
enum Person {
    // An `enum` may either be `unit-like`,
    Skinny,
    Fat,
    // like tuple structs,
    Height(i32),
    Weight(i32),
    // or like structures.
    Info { name: String, height: i32 }
}

// A function which takes a `Person` enum as an argument and
// returns nothing.
fn inspect(p: Person) {
    // Usage of an `enum` must cover all cases (irrefutable)
    // so a `match` is used to branch over it.
    match p {
        Person::Skinny    => println!("Is skinny!"),
        Person::Fat       => println!("Is fat!"),
        // Destructure `i` from inside the `enum`.
        Person::Height(i) => println!("Has a height of {}.", i),
        Person::Weight(i) => println!("Has a weight of {}.", i),
        // Destructure `Info` into `name` and `height`.
        Person::Info { name, height } => {
            println!("{} is {} tall!", name, height);
        },
    }
}

fn main() {
    let person = Person::Height(18);
    let danny  = Person::Weight(10);
    // `to_owned()` creates an owned `String` from a string slice.
    let dave   = Person::Info { name: "Dave".to_owned(), height: 72 };
    let john   = Person::Fat;
    let larry  = Person::Skinny;

    inspect(person);
    inspect(danny);
    inspect(dave);
    inspect(john);
    inspect(larry);
}
<commit_msg>Diversifying enum person examples – custom_types/enum.html<commit_after>// An attribute to hide warnings for unused code.
#![allow(dead_code)]

// Create an `enum` to classify someone. Note how both names
// and type information together specify the variant:
// `Engineer != Scientist` and `Height(i32) != Weight(i32)`. Each
// is different and independent.
enum Person {
    // An `enum` may either be `unit-like`,
    Engineer,
    Scientist,
    // like tuple structs,
    Height(i32),
    Weight(i32),
    // or like structures.
    Info { name: String, height: i32 }
}

// A function which takes a `Person` enum as an argument and
// returns nothing.
fn inspect(p: Person) {
    // Usage of an `enum` must cover all cases (irrefutable)
    // so a `match` is used to branch over it.
    match p {
        Person::Engineer  => println!("Is an engineer!"),
        Person::Scientist => println!("Is a scientist!"),
        // Destructure `i` from inside the `enum`.
        Person::Height(i) => println!("Has a height of {}.", i),
        Person::Weight(i) => println!("Has a weight of {}.", i),
        // Destructure `Info` into `name` and `height`.
        Person::Info { name, height } => {
            println!("{} is {} tall!", name, height);
        },
    }
}

fn main() {
    let person   = Person::Height(18);
    let amira    = Person::Weight(10);
    // `to_owned()` creates an owned `String` from a string slice.
    let dave     = Person::Info { name: "Dave".to_owned(), height: 72 };
    let rebecca  = Person::Scientist;
    let rohan    = Person::Engineer;

    inspect(person);
    inspect(amira);
    inspect(dave);
    inspect(rebecca);
    inspect(rohan);
}
<|endoftext|>


<commit_before>extern crate toml;
extern crate serde;

use serde::ser::Serialize;

const EXAMPLE: &str = "\
[example]
array = [
    \"item 1\",
    \"item 2\",
]
text = '''
this is the first line
this is the second line
'''
";

#[test]
fn test_pretty() {
    let value: toml::Value = toml::from_str(EXAMPLE).unwrap();
    let mut result = String::with_capacity(128);
    value.serialize(&mut toml::Serializer::pretty(&mut result)).unwrap();
    println!("example:\n{}", EXAMPLE);
    println!("result:\n{}", result);
    assert_eq!(EXAMPLE, &result);
}
<commit_msg>fix for rust 1.15<commit_after>extern crate toml;
extern crate serde;

use serde::ser::Serialize;

const EXAMPLE: &'static str = "\
[example]
array = [
    \"item 1\",
    \"item 2\",
]
text = '''
this is the first line
this is the second line
'''
";

#[test]
fn test_pretty() {
    let value: toml::Value = toml::from_str(EXAMPLE).unwrap();
    let mut result = String::with_capacity(128);
    value.serialize(&mut toml::Serializer::pretty(&mut result)).unwrap();
    println!("example:\n{}", EXAMPLE);
    println!("result:\n{}", result);
    assert_eq!(EXAMPLE, &result);
}
<|endoftext|>


<commit_before>use bifrost::membership::member::MemberService;
use bifrost::membership::server::Membership;
use bifrost::raft;
use bifrost::raft::client::RaftClient;
use bifrost::raft::state_machine::master as sm_master;
use bifrost::rpc;
use bifrost::rpc::Server;
use bifrost::utils::fut_exec::wait;
use dovahkiin::types::custom_types::id::Id;
use dovahkiin::types::custom_types::map::Map;
use dovahkiin::types::type_id_of;
use futures::prelude::*;
use itertools::Itertools;
use neb::client;
use neb::ram::cell::Cell;
use neb::ram::schema::Field;
use neb::ram::schema::LocalSchemasCache;
use neb::ram::schema::Schema;
use neb::ram::types::*;
use neb::server::*;
use parking_lot::deadlock;
use rayon::iter::IntoParallelRefIterator;
use rayon::prelude::*;
use std::env;
use std::rc::Rc;
use std::sync::Arc;
use std::thread;
use std::time::Duration;

#[test]
pub fn init() {
    NebServer::new_from_opts(
        &ServerOptions {
            chunk_count: 1,
            memory_size: 16 * 1024,
            backup_storage: None,
            wal_storage: None,
        },
        &String::from("127.0.0.1:5100"),
        &String::from("test"),
    );
}

#[test]
pub fn smoke_test() {
    const DATA: &'static str = "DATA";
    let num = env::var("NEB_KV_SMOKE_TEST_ITEMS")
        .unwrap_or("1000".to_string())
        .parse::<u64>()
        .unwrap();
    env_logger::init();
    let server_addr = String::from("127.0.0.1:5300");
    let server_group = String::from("smoke_test");
    let server = NebServer::new_from_opts(
        &ServerOptions {
            chunk_count: 1,
            memory_size: 512 * 1024 * 1024,
            backup_storage: None,
            wal_storage: None,
        },
        &server_addr,
        &server_group,
    );
    let schema_id = 123;
    let schema = Schema {
        id: schema_id,
        name: String::from("schema"),
        key_field: None,
        str_key_field: None,
        is_dynamic: false,
        fields: Field::new(
            "*",
            0,
            false,
            false,
            Some(vec![Field::new(
                DATA,
                type_id_of(Type::U64),
                false,
                false,
                None,
            )]),
        ),
    };

    let client =
        Arc::new(client::AsyncClient::new(&server.rpc, &vec![server_addr], &server_group).unwrap());
    wait(client.new_schema_with_id(schema));

    (0..num).collect::<Vec<_>>().into_iter().for_each(|i| {
        let client_clone = client.clone();
        // intense upsert, half delete
        let id = Id::new(0, i / 2);
        let mut value = Value::Map(Map::new());
        value[DATA] = Value::U64(i);
        let cell = Cell::new_with_id(schema_id, &id, value);
        wait(client_clone.upsert_cell(cell));

        // read
        let read_cell = wait(client_clone.read_cell(id)).unwrap().unwrap();
        assert_eq!(*(read_cell.data[DATA].U64().unwrap()), i);

        if i % 2 == 0 {
            wait(client_clone.remove_cell(id));
        }
    });

    (0..num).collect::<Vec<_>>().into_iter().for_each(|i| {
        let id = Id::new(0, i);
        let mut value = Value::Map(Map::new());
        value[DATA] = Value::U64(i * 2);
        let cell = Cell::new_with_id(schema_id, &id, value);
        wait(client.upsert_cell(cell));

        // verify
        let read_cell = wait(client.read_cell(id)).unwrap().unwrap();
        assert_eq!(*(read_cell.data[DATA].U64().unwrap()), i * 2);
    });
}

#[test]
pub fn smoke_test_parallel() {
    const DATA: &'static str = "DATA";
    let num = env::var("NEB_KV_SMOKE_TEST_ITEMS")
        .unwrap_or("1000".to_string())
        .parse::<u64>()
        .unwrap();
    env_logger::init();
    let server_addr = String::from("127.0.0.1:5300");
    let server_group = String::from("smoke_parallel_test");
    let server = NebServer::new_from_opts(
        &ServerOptions {
            chunk_count: 1,
            memory_size: 512 * 1024 * 1024,
            backup_storage: None,
            wal_storage: None,
        },
        &server_addr,
        &server_group,
    );
    let schema_id = 123;
    let schema = Schema {
        id: schema_id,
        name: String::from("schema"),
        key_field: None,
        str_key_field: None,
        is_dynamic: false,
        fields: Field::new(
            "*",
            0,
            false,
            false,
            Some(vec![Field::new(
                DATA,
                type_id_of(Type::U64),
                false,
                false,
                None,
            )]),
        ),
    };

    let client =
        Arc::new(client::AsyncClient::new(&server.rpc, &vec![server_addr], &server_group).unwrap());
    wait(client.new_schema_with_id(schema));

    // Create a background thread which checks for deadlocks every 10s
    thread::Builder::new()
        .name("deadlock checker".to_string())
        .spawn(move || loop {
            thread::sleep(Duration::from_secs(1));
            let deadlocks = deadlock::check_deadlock();
            if deadlocks.is_empty() {
                continue;
            }

            error!("{} deadlocks detected", deadlocks.len());
            for (i, threads) in deadlocks.iter().enumerate() {
                error!("Deadlock #{}", i);
                for t in threads {
                    error!("Thread Id {:#?}", t.thread_id());
                    error!("{:#?}", t.backtrace());
                }
            }
            panic!();
        });

    (0..num).collect::<Vec<_>>().into_par_iter().for_each(|i| {
        let client_clone = client.clone();
        // intense upsert, half delete
        let id = Id::new(0, i);
        let mut value = Value::Map(Map::new());
        value[DATA] = Value::U64(i);
        let cell = Cell::new_with_id(schema_id, &id, value);
        wait(client_clone.upsert_cell(cell));

        // read
        let read_cell = wait(client_clone.read_cell(id)).unwrap().unwrap();
        assert_eq!(*(read_cell.data[DATA].U64().unwrap()), i);

        if i % 2 == 0 {
            wait(client_clone.remove_cell(id));
        }
    });

    (0..num).collect::<Vec<_>>().into_par_iter().for_each(|i| {
        if i % 2 == 0 { return }
        let id = Id::new(0, i);
        let mut value = Value::Map(Map::new());
        value[DATA] = Value::U64(i * 2);
        let cell = Cell::new_with_id(schema_id, &id, value);
        wait(client.upsert_cell(cell));

        // verify
        let read_cell = wait(client.read_cell(id)).unwrap().unwrap();
        assert_eq!(*(read_cell.data[DATA].U64().unwrap()), i * 2);
    });
}
<commit_msg>diferent port for server tests<commit_after>use bifrost::membership::member::MemberService;
use bifrost::membership::server::Membership;
use bifrost::raft;
use bifrost::raft::client::RaftClient;
use bifrost::raft::state_machine::master as sm_master;
use bifrost::rpc;
use bifrost::rpc::Server;
use bifrost::utils::fut_exec::wait;
use dovahkiin::types::custom_types::id::Id;
use dovahkiin::types::custom_types::map::Map;
use dovahkiin::types::type_id_of;
use futures::prelude::*;
use itertools::Itertools;
use neb::client;
use neb::ram::cell::Cell;
use neb::ram::schema::Field;
use neb::ram::schema::LocalSchemasCache;
use neb::ram::schema::Schema;
use neb::ram::types::*;
use neb::server::*;
use parking_lot::deadlock;
use rayon::iter::IntoParallelRefIterator;
use rayon::prelude::*;
use std::env;
use std::rc::Rc;
use std::sync::Arc;
use std::thread;
use std::time::Duration;

#[test]
pub fn init() {
    NebServer::new_from_opts(
        &ServerOptions {
            chunk_count: 1,
            memory_size: 16 * 1024,
            backup_storage: None,
            wal_storage: None,
        },
        &String::from("127.0.0.1:5100"),
        &String::from("test"),
    );
}

#[test]
pub fn smoke_test() {
    const DATA: &'static str = "DATA";
    let num = env::var("NEB_KV_SMOKE_TEST_ITEMS")
        .unwrap_or("1000".to_string())
        .parse::<u64>()
        .unwrap();
    env_logger::init();
    let server_addr = String::from("127.0.0.1:5300");
    let server_group = String::from("smoke_test");
    let server = NebServer::new_from_opts(
        &ServerOptions {
            chunk_count: 1,
            memory_size: 512 * 1024 * 1024,
            backup_storage: None,
            wal_storage: None,
        },
        &server_addr,
        &server_group,
    );
    let schema_id = 123;
    let schema = Schema {
        id: schema_id,
        name: String::from("schema"),
        key_field: None,
        str_key_field: None,
        is_dynamic: false,
        fields: Field::new(
            "*",
            0,
            false,
            false,
            Some(vec![Field::new(
                DATA,
                type_id_of(Type::U64),
                false,
                false,
                None,
            )]),
        ),
    };

    let client =
        Arc::new(client::AsyncClient::new(&server.rpc, &vec![server_addr], &server_group).unwrap());
    wait(client.new_schema_with_id(schema));

    (0..num).collect::<Vec<_>>().into_iter().for_each(|i| {
        let client_clone = client.clone();
        // intense upsert, half delete
        let id = Id::new(0, i / 2);
        let mut value = Value::Map(Map::new());
        value[DATA] = Value::U64(i);
        let cell = Cell::new_with_id(schema_id, &id, value);
        wait(client_clone.upsert_cell(cell));

        // read
        let read_cell = wait(client_clone.read_cell(id)).unwrap().unwrap();
        assert_eq!(*(read_cell.data[DATA].U64().unwrap()), i);

        if i % 2 == 0 {
            wait(client_clone.remove_cell(id));
        }
    });

    (0..num).collect::<Vec<_>>().into_iter().for_each(|i| {
        let id = Id::new(0, i);
        let mut value = Value::Map(Map::new());
        value[DATA] = Value::U64(i * 2);
        let cell = Cell::new_with_id(schema_id, &id, value);
        wait(client.upsert_cell(cell));

        // verify
        let read_cell = wait(client.read_cell(id)).unwrap().unwrap();
        assert_eq!(*(read_cell.data[DATA].U64().unwrap()), i * 2);
    });
}

#[test]
pub fn smoke_test_parallel() {
    const DATA: &'static str = "DATA";
    let num = env::var("NEB_KV_SMOKE_TEST_ITEMS")
        .unwrap_or("1000".to_string())
        .parse::<u64>()
        .unwrap();
    env_logger::init();
    let server_addr = String::from("127.0.0.1:5301");
    let server_group = String::from("smoke_parallel_test");
    let server = NebServer::new_from_opts(
        &ServerOptions {
            chunk_count: 1,
            memory_size: 512 * 1024 * 1024,
            backup_storage: None,
            wal_storage: None,
        },
        &server_addr,
        &server_group,
    );
    let schema_id = 123;
    let schema = Schema {
        id: schema_id,
        name: String::from("schema"),
        key_field: None,
        str_key_field: None,
        is_dynamic: false,
        fields: Field::new(
            "*",
            0,
            false,
            false,
            Some(vec![Field::new(
                DATA,
                type_id_of(Type::U64),
                false,
                false,
                None,
            )]),
        ),
    };

    let client =
        Arc::new(client::AsyncClient::new(&server.rpc, &vec![server_addr], &server_group).unwrap());
    wait(client.new_schema_with_id(schema));

    // Create a background thread which checks for deadlocks every 10s
    thread::Builder::new()
        .name("deadlock checker".to_string())
        .spawn(move || loop {
            thread::sleep(Duration::from_secs(1));
            let deadlocks = deadlock::check_deadlock();
            if deadlocks.is_empty() {
                continue;
            }

            error!("{} deadlocks detected", deadlocks.len());
            for (i, threads) in deadlocks.iter().enumerate() {
                error!("Deadlock #{}", i);
                for t in threads {
                    error!("Thread Id {:#?}", t.thread_id());
                    error!("{:#?}", t.backtrace());
                }
            }
            panic!();
        });

    (0..num).collect::<Vec<_>>().into_par_iter().for_each(|i| {
        let client_clone = client.clone();
        // intense upsert, half delete
        let id = Id::new(0, i);
        let mut value = Value::Map(Map::new());
        value[DATA] = Value::U64(i);
        let cell = Cell::new_with_id(schema_id, &id, value);
        wait(client_clone.upsert_cell(cell));

        // read
        let read_cell = wait(client_clone.read_cell(id)).unwrap().unwrap();
        assert_eq!(*(read_cell.data[DATA].U64().unwrap()), i);

        if i % 2 == 0 {
            wait(client_clone.remove_cell(id));
        }
    });

    (0..num).collect::<Vec<_>>().into_par_iter().for_each(|i| {
        if i % 2 == 0 { return }
        let id = Id::new(0, i);
        let mut value = Value::Map(Map::new());
        value[DATA] = Value::U64(i * 2);
        let cell = Cell::new_with_id(schema_id, &id, value);
        wait(client.upsert_cell(cell));

        // verify
        let read_cell = wait(client.read_cell(id)).unwrap().unwrap();
        assert_eq!(*(read_cell.data[DATA].U64().unwrap()), i * 2);
    });
}
<|endoftext|>


<commit_before>extern crate sdl2;

fn main() -> Result<(), String> {
    // This is required for certain controllers to work on Windows without the
    // video subsystem enabled:
    sdl2::hint::set("SDL_JOYSTICK_THREAD", "1");

    let sdl_context = sdl2::init()?;
    let game_controller_subsystem = sdl_context.game_controller()?;

    let available = game_controller_subsystem
        .num_joysticks()
        .map_err(|e| format!("can't enumerate joysticks: {}", e))?;

    println!("{} joysticks available", available);

    // Iterate over all available joysticks and look for game controllers.
    let mut controller = (0..available)
        .find_map(|id| {
            if !game_controller_subsystem.is_game_controller(id) {
                println!("{} is not a game controller", id);
                return None;
            }

            println!("Attempting to open controller {}", id);

            match game_controller_subsystem.open(id) {
                Ok(c) => {
                    // We managed to find and open a game controller,
                    // exit the loop
                    println!("Success: opened \"{}\"", c.name());
                    Some(c)
                }
                Err(e) => {
                    println!("failed: {:?}", e);
                    None
                }
            }
        })
        .expect("Couldn't open any controller");

    println!("Controller mapping: {}", controller.mapping());

    let (mut lo_freq, mut hi_freq) = (0, 0);

    for event in sdl_context.event_pump()?.wait_iter() {
        use sdl2::controller::Axis;
        use sdl2::event::Event;

        match event {
            Event::ControllerAxisMotion {
                axis: Axis::TriggerLeft,
                value: val,
                ..
            } => {
                // Trigger axes go from 0 to 32767, so this should be okay
                lo_freq = (val as u16) * 2;
                match controller.set_rumble(lo_freq, hi_freq, 15000) {
                    Ok(()) => println!("Set rumble to ({}, {})", lo_freq, hi_freq),
                    Err(e) => println!(
                        "Error setting rumble to ({}, {}): {:?}",
                        lo_freq, hi_freq, e
                    ),
                }
            }
            Event::ControllerAxisMotion {
                axis: Axis::TriggerRight,
                value: val,
                ..
            } => {
                // Trigger axes go from 0 to 32767, so this should be okay
                hi_freq = (val as u16) * 2;
                match controller.set_rumble(lo_freq, hi_freq, 15000) {
                    Ok(()) => println!("Set rumble to ({}, {})", lo_freq, hi_freq),
                    Err(e) => println!(
                        "Error setting rumble to ({}, {}): {:?}",
                        lo_freq, hi_freq, e
                    ),
                }
            }
            Event::ControllerAxisMotion {
                axis, value: val, ..
            } => {
                // Axis motion is an absolute value in the range
                // [-32768, 32767]. Let's simulate a very rough dead
                // zone to ignore spurious events.
                let dead_zone = 10_000;
                if val > dead_zone || val < -dead_zone {
                    println!("Axis {:?} moved to {}", axis, val);
                }
            }
            Event::ControllerButtonDown { button, .. } => println!("Button {:?} down", button),
            Event::ControllerButtonUp { button, .. } => println!("Button {:?} up", button),
            Event::ControllerTouchpadDown {
                touchpad,
                finger,
                x,
                y,
                ..
            } => println!("Touchpad {touchpad} down finger:{finger} x:{x} y:{y}"),
            Event::ControllerTouchpadMotion {
                touchpad,
                finger,
                x,
                y,
                ..
            } => println!("Touchpad {touchpad} move finger:{finger} x:{x} y:{y}"),
            Event::ControllerTouchpadUp {
                touchpad,
                finger,
                x,
                y,
                ..
            } => println!("Touchpad {touchpad} up   finger:{finger} x:{x} y:{y}"),
            Event::Quit { .. } => break,
            _ => (),
        }
    }

    Ok(())
}
<commit_msg>Make the fmt check pass<commit_after>extern crate sdl2;

fn main() -> Result<(), String> {
    // This is required for certain controllers to work on Windows without the
    // video subsystem enabled:
    sdl2::hint::set("SDL_JOYSTICK_THREAD", "1");

    let sdl_context = sdl2::init()?;
    let game_controller_subsystem = sdl_context.game_controller()?;

    let available = game_controller_subsystem
        .num_joysticks()
        .map_err(|e| format!("can't enumerate joysticks: {}", e))?;

    println!("{} joysticks available", available);

    // Iterate over all available joysticks and look for game controllers.
    let mut controller = (0..available)
        .find_map(|id| {
            if !game_controller_subsystem.is_game_controller(id) {
                println!("{} is not a game controller", id);
                return None;
            }

            println!("Attempting to open controller {}", id);

            match game_controller_subsystem.open(id) {
                Ok(c) => {
                    // We managed to find and open a game controller,
                    // exit the loop
                    println!("Success: opened \"{}\"", c.name());
                    Some(c)
                }
                Err(e) => {
                    println!("failed: {:?}", e);
                    None
                }
            }
        })
        .expect("Couldn't open any controller");

    println!("Controller mapping: {}", controller.mapping());

    let (mut lo_freq, mut hi_freq) = (0, 0);

    for event in sdl_context.event_pump()?.wait_iter() {
        use sdl2::controller::Axis;
        use sdl2::event::Event;

        match event {
            Event::ControllerAxisMotion {
                axis: Axis::TriggerLeft,
                value: val,
                ..
            } => {
                // Trigger axes go from 0 to 32767, so this should be okay
                lo_freq = (val as u16) * 2;
                match controller.set_rumble(lo_freq, hi_freq, 15000) {
                    Ok(()) => println!("Set rumble to ({}, {})", lo_freq, hi_freq),
                    Err(e) => println!(
                        "Error setting rumble to ({}, {}): {:?}",
                        lo_freq, hi_freq, e
                    ),
                }
            }
            Event::ControllerAxisMotion {
                axis: Axis::TriggerRight,
                value: val,
                ..
            } => {
                // Trigger axes go from 0 to 32767, so this should be okay
                hi_freq = (val as u16) * 2;
                match controller.set_rumble(lo_freq, hi_freq, 15000) {
                    Ok(()) => println!("Set rumble to ({}, {})", lo_freq, hi_freq),
                    Err(e) => println!(
                        "Error setting rumble to ({}, {}): {:?}",
                        lo_freq, hi_freq, e
                    ),
                }
            }
            Event::ControllerAxisMotion {
                axis, value: val, ..
            } => {
                // Axis motion is an absolute value in the range
                // [-32768, 32767]. Let's simulate a very rough dead
                // zone to ignore spurious events.
                let dead_zone = 10_000;
                if val > dead_zone || val < -dead_zone {
                    println!("Axis {:?} moved to {}", axis, val);
                }
            }
            Event::ControllerButtonDown { button, .. } => println!("Button {:?} down", button),
            Event::ControllerButtonUp { button, .. } => println!("Button {:?} up", button),
            Event::ControllerTouchpadDown {
                touchpad,
                finger,
                x,
                y,
                ..
            } => println!("Touchpad {touchpad} down finger:{finger} x:{x} y:{y}"),
            Event::ControllerTouchpadMotion {
                touchpad,
                finger,
                x,
                y,
                ..
            } => println!("Touchpad {touchpad} move finger:{finger} x:{x} y:{y}"),
            Event::ControllerTouchpadUp {
                touchpad,
                finger,
                x,
                y,
                ..
            } => println!("Touchpad {touchpad} up   finger:{finger} x:{x} y:{y}"),
            Event::Quit { .. } => break,
            _ => (),
        }
    }

    Ok(())
}
<|endoftext|>


<commit_before>extern crate itertools;

use itertools::Itertools;

#[test]
fn tuples() {
    let v = [1, 2, 3, 4, 5];
    let mut iter = v.iter().cloned().tuples();
    assert_eq!(Some((1,)), iter.next());
    assert_eq!(Some((2,)), iter.next());
    assert_eq!(Some((3,)), iter.next());
    assert_eq!(Some((4,)), iter.next());
    assert_eq!(Some((5,)), iter.next());
    assert_eq!(None, iter.next());
    assert_eq!(None, iter.into_buffer().next());

    let mut iter = v.iter().cloned().tuples();
    assert_eq!(Some((1, 2)), iter.next());
    assert_eq!(Some((3, 4)), iter.next());
    assert_eq!(None, iter.next());
    itertools::assert_equal(vec![5], iter.into_buffer());

    let mut iter = v.iter().cloned().tuples();
    assert_eq!(Some((1, 2, 3)), iter.next());
    assert_eq!(None, iter.next());
    itertools::assert_equal(vec![4, 5], iter.into_buffer());

    let mut iter = v.iter().cloned().tuples();
    assert_eq!(Some((1, 2, 3, 4)), iter.next());
    assert_eq!(None, iter.next());
    itertools::assert_equal(vec![5], iter.into_buffer());
}

#[test]
fn tuple_windows() {
    let v = [1, 2, 3, 4, 5];

    let mut iter = v.iter().cloned().tuple_windows();
    assert_eq!(Some((1,)), iter.next());
    assert_eq!(Some((2,)), iter.next());
    assert_eq!(Some((3,)), iter.next());

    let mut iter = v.iter().cloned().tuple_windows();
    assert_eq!(Some((1, 2)), iter.next());
    assert_eq!(Some((2, 3)), iter.next());
    assert_eq!(Some((3, 4)), iter.next());
    assert_eq!(Some((4, 5)), iter.next());
    assert_eq!(None, iter.next());

    let mut iter = v.iter().cloned().tuple_windows();
    assert_eq!(Some((1, 2, 3)), iter.next());
    assert_eq!(Some((2, 3, 4)), iter.next());
    assert_eq!(Some((3, 4, 5)), iter.next());
    assert_eq!(None, iter.next());

    let mut iter = v.iter().cloned().tuple_windows();
    assert_eq!(Some((1, 2, 3, 4)), iter.next());
    assert_eq!(Some((2, 3, 4, 5)), iter.next());
    assert_eq!(None, iter.next());

    let v = [1, 2, 3];
    let mut iter = v.iter().cloned().tuple_windows::<(_, _, _, _)>();
    assert_eq!(None, iter.next());
}
<commit_msg>Add test for .next_tuple()<commit_after>extern crate itertools;

use itertools::Itertools;

#[test]
fn tuples() {
    let v = [1, 2, 3, 4, 5];
    let mut iter = v.iter().cloned().tuples();
    assert_eq!(Some((1,)), iter.next());
    assert_eq!(Some((2,)), iter.next());
    assert_eq!(Some((3,)), iter.next());
    assert_eq!(Some((4,)), iter.next());
    assert_eq!(Some((5,)), iter.next());
    assert_eq!(None, iter.next());
    assert_eq!(None, iter.into_buffer().next());

    let mut iter = v.iter().cloned().tuples();
    assert_eq!(Some((1, 2)), iter.next());
    assert_eq!(Some((3, 4)), iter.next());
    assert_eq!(None, iter.next());
    itertools::assert_equal(vec![5], iter.into_buffer());

    let mut iter = v.iter().cloned().tuples();
    assert_eq!(Some((1, 2, 3)), iter.next());
    assert_eq!(None, iter.next());
    itertools::assert_equal(vec![4, 5], iter.into_buffer());

    let mut iter = v.iter().cloned().tuples();
    assert_eq!(Some((1, 2, 3, 4)), iter.next());
    assert_eq!(None, iter.next());
    itertools::assert_equal(vec![5], iter.into_buffer());
}

#[test]
fn tuple_windows() {
    let v = [1, 2, 3, 4, 5];

    let mut iter = v.iter().cloned().tuple_windows();
    assert_eq!(Some((1,)), iter.next());
    assert_eq!(Some((2,)), iter.next());
    assert_eq!(Some((3,)), iter.next());

    let mut iter = v.iter().cloned().tuple_windows();
    assert_eq!(Some((1, 2)), iter.next());
    assert_eq!(Some((2, 3)), iter.next());
    assert_eq!(Some((3, 4)), iter.next());
    assert_eq!(Some((4, 5)), iter.next());
    assert_eq!(None, iter.next());

    let mut iter = v.iter().cloned().tuple_windows();
    assert_eq!(Some((1, 2, 3)), iter.next());
    assert_eq!(Some((2, 3, 4)), iter.next());
    assert_eq!(Some((3, 4, 5)), iter.next());
    assert_eq!(None, iter.next());

    let mut iter = v.iter().cloned().tuple_windows();
    assert_eq!(Some((1, 2, 3, 4)), iter.next());
    assert_eq!(Some((2, 3, 4, 5)), iter.next());
    assert_eq!(None, iter.next());

    let v = [1, 2, 3];
    let mut iter = v.iter().cloned().tuple_windows::<(_, _, _, _)>();
    assert_eq!(None, iter.next());
}

#[test]
fn next_tuple() {
    let v = [1, 2, 3, 4, 5];
    let mut iter = v.iter();
    assert_eq!(iter.next_tuple().map(|(&x, &y)| (x, y)), Some((1, 2)));
    assert_eq!(iter.next_tuple().map(|(&x, &y)| (x, y)), Some((3, 4)));
    assert_eq!(iter.next_tuple::<(_, _)>(), None);
}
<|endoftext|>


<commit_before>//! Utilities for translating from codespan types into Language Server Protocol (LSP) types

use codespan::{
    ByteIndex, ByteOffset, ColumnIndex, FileId, Files, LineIndex, LineIndexOutOfBoundsError,
    LocationError, RawIndex, RawOffset, Span, SpanOutOfBoundsError,
};
use codespan_reporting::{Diagnostic, Severity};
use lsp_types as lsp;
use std::error;
use url::Url;

#[derive(derive_more::Display, Debug, PartialEq)]
pub enum Error {
    #[display(fmt = "Unable to correlate filename `{}` to url", _0)]
    UnableToCorrelateFilename(String),
    #[display(fmt = "Column out of bounds - given: {}, max: {}", given, max)]
    ColumnOutOfBounds {
        given: ColumnIndex,
        max: ColumnIndex,
    },
    Location(LocationError),
    LineIndexOutOfBounds(LineIndexOutOfBoundsError),
    SpanOutOfBounds(SpanOutOfBoundsError),
}

impl From<LocationError> for Error {
    fn from(e: LocationError) -> Error {
        Error::Location(e)
    }
}

impl From<LineIndexOutOfBoundsError> for Error {
    fn from(e: LineIndexOutOfBoundsError) -> Error {
        Error::LineIndexOutOfBounds(e)
    }
}

impl From<SpanOutOfBoundsError> for Error {
    fn from(e: SpanOutOfBoundsError) -> Error {
        Error::SpanOutOfBounds(e)
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Error::UnableToCorrelateFilename(_) | Error::ColumnOutOfBounds { .. } => None,
            Error::Location(error) => Some(error),
            Error::LineIndexOutOfBounds(error) => Some(error),
            Error::SpanOutOfBounds(error) => Some(error),
        }
    }
}

fn location_to_position(
    line_str: &str,
    line: LineIndex,
    column: ColumnIndex,
    byte_index: ByteIndex,
) -> Result<lsp::Position, Error> {
    if column.to_usize() > line_str.len() {
        let max = ColumnIndex(line_str.len() as RawIndex);
        let given = column;

        Err(Error::ColumnOutOfBounds { given, max })
    } else if !line_str.is_char_boundary(column.to_usize()) {
        let given = byte_index;

        Err(LocationError::InvalidCharBoundary { given }.into())
    } else {
        let line_utf16 = line_str[..column.to_usize()].encode_utf16();
        let character = line_utf16.count() as u64;
        let line = line.to_usize() as u64;

        Ok(lsp::Position { line, character })
    }
}

pub fn byte_index_to_position(
    files: &Files,
    file_id: FileId,
    byte_index: ByteIndex,
) -> Result<lsp::Position, Error> {
    let location = files.location(file_id, byte_index)?;
    let line_span = files.line_span(file_id, location.line)?;
    let line_str = files.source_slice(file_id, line_span)?;
    let column = ColumnIndex::from((byte_index - line_span.start()).0 as RawIndex);

    location_to_position(line_str, location.line, column, byte_index)
}

pub fn byte_span_to_range(files: &Files, file_id: FileId, span: Span) -> Result<lsp::Range, Error> {
    Ok(lsp::Range {
        start: byte_index_to_position(files, file_id, span.start())?,
        end: byte_index_to_position(files, file_id, span.end())?,
    })
}

pub fn character_to_line_offset(line: &str, character: u64) -> Result<ByteOffset, Error> {
    let line_len = ByteOffset::from(line.len() as RawOffset);
    let mut character_offset = 0;

    let mut chars = line.chars();
    while let Some(ch) = chars.next() {
        if character_offset == character {
            let chars_off = ByteOffset::from_str_len_utf8(chars.as_str());
            let ch_off = ByteOffset::from_char_len_utf8(ch);

            return Ok(line_len - chars_off - ch_off);
        }

        character_offset += ch.len_utf16() as u64;
    }

    // Handle positions after the last character on the line
    if character_offset == character {
        Ok(line_len)
    } else {
        Err(Error::ColumnOutOfBounds {
            given: ColumnIndex(character_offset as RawIndex),
            max: ColumnIndex(line.len() as RawIndex),
        })
    }
}

pub fn position_to_byte_index(
    files: &Files,
    file_id: FileId,
    position: &lsp::Position,
) -> Result<ByteIndex, Error> {
    let line_span = files.line_span(file_id, position.line as RawIndex)?;
    let source = files.source_slice(file_id, line_span)?;
    let byte_offset = character_to_line_offset(source, position.character)?;

    Ok(line_span.start() + byte_offset)
}

pub fn range_to_byte_span(
    files: &Files,
    file_id: FileId,
    range: &lsp::Range,
) -> Result<Span, Error> {
    Ok(Span::new(
        position_to_byte_index(files, file_id, &range.start)?,
        position_to_byte_index(files, file_id, &range.end)?,
    ))
}

pub fn make_lsp_severity(severity: Severity) -> lsp::DiagnosticSeverity {
    match severity {
        Severity::Error | Severity::Bug => lsp::DiagnosticSeverity::Error,
        Severity::Warning => lsp::DiagnosticSeverity::Warning,
        Severity::Note => lsp::DiagnosticSeverity::Information,
        Severity::Help => lsp::DiagnosticSeverity::Hint,
    }
}

/// Translates a `codespan_reporting::Diagnostic` to a
/// `languageserver_types::Diagnostic`.
///
/// Since the language client requires `Url`s to locate the diagnostics,
/// `correlate_file_url` is necessary to resolve codespan `FileName`s
///
/// `code` and `file` are left empty by this function
pub fn make_lsp_diagnostic(
    files: &Files,
    diagnostic: Diagnostic,
    mut correlate_file_url: impl FnMut(FileId, &str) -> Result<Url, ()>,
) -> Result<lsp::Diagnostic, Error> {
    // We need a position for the primary error so take the span from the first primary label
    let primary_file_id = diagnostic.primary_label.file_span.id;
    let primary_span = diagnostic.primary_label.file_span.span;
    let primary_label_range = byte_span_to_range(files, primary_file_id, primary_span)?;

    let related_information = diagnostic
        .secondary_labels
        .into_iter()
        .map(|label| {
            let file_id = label.file_span.id;
            let range = byte_span_to_range(files, file_id, label.file_span.span)?;
            let uri = correlate_file_url(file_id, files.name(file_id))
                .map_err(|()| Error::UnableToCorrelateFilename(files.name(file_id).to_owned()))?;

            Ok(lsp::DiagnosticRelatedInformation {
                location: lsp::Location { uri, range },
                message: label.message,
            })
        })
        .collect::<Result<Vec<_>, Error>>()?;

    Ok(lsp::Diagnostic {
        message: diagnostic.message,
        range: primary_label_range,
        severity: Some(make_lsp_severity(diagnostic.severity)),
        related_information: if related_information.is_empty() {
            None
        } else {
            Some(related_information)
        },
        ..lsp::Diagnostic::default()
    })
}

#[cfg(test)]
mod tests {
    use codespan::Location;

    use super::*;

    #[test]
    fn position() {
        let text = r#"
let test = 2
let test1 = ""
test
"#;
        let mut files = Files::new();
        let file_id = files.add("test", text);
        let pos = position_to_byte_index(
            &files,
            file_id,
            &lsp::Position {
                line: 3,
                character: 2,
            },
        )
        .unwrap();
        assert_eq!(Location::new(3, 2), files.location(file_id, pos).unwrap());
    }

    // The protocol specifies that each `character` in position is a UTF-16 character.
    // This means that `å` and `ä` here counts as 1 while `𐐀` counts as 2.
    const UNICODE: &str = "åä t𐐀b";

    #[test]
    fn unicode_get_byte_index() {
        let mut files = Files::new();
        let file_id = files.add("unicode", UNICODE);

        let result = position_to_byte_index(
            &files,
            file_id,
            &lsp::Position {
                line: 0,
                character: 3,
            },
        );
        assert_eq!(result, Ok(ByteIndex::from(5)));

        let result = position_to_byte_index(
            &files,
            file_id,
            &lsp::Position {
                line: 0,
                character: 6,
            },
        );
        assert_eq!(result, Ok(ByteIndex::from(10)));
    }

    #[test]
    fn unicode_get_position() {
        let mut files = Files::new();
        let file_id = files.add("unicode", UNICODE);

        let result = byte_index_to_position(&files, file_id, ByteIndex::from(5));
        assert_eq!(
            result,
            Ok(lsp::Position {
                line: 0,
                character: 3,
            })
        );

        let result = byte_index_to_position(&files, file_id, ByteIndex::from(10));
        assert_eq!(
            result,
            Ok(lsp::Position {
                line: 0,
                character: 6,
            })
        );
    }
}
<commit_msg>Output source and code in LSP diagnostic<commit_after>//! Utilities for translating from codespan types into Language Server Protocol (LSP) types

use codespan::{
    ByteIndex, ByteOffset, ColumnIndex, FileId, Files, LineIndex, LineIndexOutOfBoundsError,
    LocationError, RawIndex, RawOffset, Span, SpanOutOfBoundsError,
};
use codespan_reporting::{Diagnostic, Severity};
use lsp_types as lsp;
use std::error;
use url::Url;

#[derive(derive_more::Display, Debug, PartialEq)]
pub enum Error {
    #[display(fmt = "Unable to correlate filename `{}` to url", _0)]
    UnableToCorrelateFilename(String),
    #[display(fmt = "Column out of bounds - given: {}, max: {}", given, max)]
    ColumnOutOfBounds {
        given: ColumnIndex,
        max: ColumnIndex,
    },
    Location(LocationError),
    LineIndexOutOfBounds(LineIndexOutOfBoundsError),
    SpanOutOfBounds(SpanOutOfBoundsError),
}

impl From<LocationError> for Error {
    fn from(e: LocationError) -> Error {
        Error::Location(e)
    }
}

impl From<LineIndexOutOfBoundsError> for Error {
    fn from(e: LineIndexOutOfBoundsError) -> Error {
        Error::LineIndexOutOfBounds(e)
    }
}

impl From<SpanOutOfBoundsError> for Error {
    fn from(e: SpanOutOfBoundsError) -> Error {
        Error::SpanOutOfBounds(e)
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Error::UnableToCorrelateFilename(_) | Error::ColumnOutOfBounds { .. } => None,
            Error::Location(error) => Some(error),
            Error::LineIndexOutOfBounds(error) => Some(error),
            Error::SpanOutOfBounds(error) => Some(error),
        }
    }
}

fn location_to_position(
    line_str: &str,
    line: LineIndex,
    column: ColumnIndex,
    byte_index: ByteIndex,
) -> Result<lsp::Position, Error> {
    if column.to_usize() > line_str.len() {
        let max = ColumnIndex(line_str.len() as RawIndex);
        let given = column;

        Err(Error::ColumnOutOfBounds { given, max })
    } else if !line_str.is_char_boundary(column.to_usize()) {
        let given = byte_index;

        Err(LocationError::InvalidCharBoundary { given }.into())
    } else {
        let line_utf16 = line_str[..column.to_usize()].encode_utf16();
        let character = line_utf16.count() as u64;
        let line = line.to_usize() as u64;

        Ok(lsp::Position { line, character })
    }
}

pub fn byte_index_to_position(
    files: &Files,
    file_id: FileId,
    byte_index: ByteIndex,
) -> Result<lsp::Position, Error> {
    let location = files.location(file_id, byte_index)?;
    let line_span = files.line_span(file_id, location.line)?;
    let line_str = files.source_slice(file_id, line_span)?;
    let column = ColumnIndex::from((byte_index - line_span.start()).0 as RawIndex);

    location_to_position(line_str, location.line, column, byte_index)
}

pub fn byte_span_to_range(files: &Files, file_id: FileId, span: Span) -> Result<lsp::Range, Error> {
    Ok(lsp::Range {
        start: byte_index_to_position(files, file_id, span.start())?,
        end: byte_index_to_position(files, file_id, span.end())?,
    })
}

pub fn character_to_line_offset(line: &str, character: u64) -> Result<ByteOffset, Error> {
    let line_len = ByteOffset::from(line.len() as RawOffset);
    let mut character_offset = 0;

    let mut chars = line.chars();
    while let Some(ch) = chars.next() {
        if character_offset == character {
            let chars_off = ByteOffset::from_str_len_utf8(chars.as_str());
            let ch_off = ByteOffset::from_char_len_utf8(ch);

            return Ok(line_len - chars_off - ch_off);
        }

        character_offset += ch.len_utf16() as u64;
    }

    // Handle positions after the last character on the line
    if character_offset == character {
        Ok(line_len)
    } else {
        Err(Error::ColumnOutOfBounds {
            given: ColumnIndex(character_offset as RawIndex),
            max: ColumnIndex(line.len() as RawIndex),
        })
    }
}

pub fn position_to_byte_index(
    files: &Files,
    file_id: FileId,
    position: &lsp::Position,
) -> Result<ByteIndex, Error> {
    let line_span = files.line_span(file_id, position.line as RawIndex)?;
    let source = files.source_slice(file_id, line_span)?;
    let byte_offset = character_to_line_offset(source, position.character)?;

    Ok(line_span.start() + byte_offset)
}

pub fn range_to_byte_span(
    files: &Files,
    file_id: FileId,
    range: &lsp::Range,
) -> Result<Span, Error> {
    Ok(Span::new(
        position_to_byte_index(files, file_id, &range.start)?,
        position_to_byte_index(files, file_id, &range.end)?,
    ))
}

pub fn make_lsp_severity(severity: Severity) -> lsp::DiagnosticSeverity {
    match severity {
        Severity::Error | Severity::Bug => lsp::DiagnosticSeverity::Error,
        Severity::Warning => lsp::DiagnosticSeverity::Warning,
        Severity::Note => lsp::DiagnosticSeverity::Information,
        Severity::Help => lsp::DiagnosticSeverity::Hint,
    }
}

/// Translates a `codespan_reporting::Diagnostic` to a
/// `languageserver_types::Diagnostic`.
///
/// Since the language client requires `Url`s to locate the diagnostics,
/// `correlate_file_url` is necessary to resolve codespan `FileName`s
///
/// `code` and `file` are left empty by this function
pub fn make_lsp_diagnostic(
    files: &Files,
    source: impl Into<Option<String>>,
    diagnostic: Diagnostic,
    mut correlate_file_url: impl FnMut(FileId, &str) -> Result<Url, ()>,
) -> Result<lsp::Diagnostic, Error> {
    // We need a position for the primary error so take the span from the first primary label
    let primary_file_id = diagnostic.primary_label.file_span.id;
    let primary_span = diagnostic.primary_label.file_span.span;
    let primary_label_range = byte_span_to_range(files, primary_file_id, primary_span)?;

    let related_information = diagnostic
        .secondary_labels
        .into_iter()
        .map(|label| {
            let file_id = label.file_span.id;
            let range = byte_span_to_range(files, file_id, label.file_span.span)?;
            let uri = correlate_file_url(file_id, files.name(file_id))
                .map_err(|()| Error::UnableToCorrelateFilename(files.name(file_id).to_owned()))?;

            Ok(lsp::DiagnosticRelatedInformation {
                location: lsp::Location { uri, range },
                message: label.message,
            })
        })
        .collect::<Result<Vec<_>, Error>>()?;

    Ok(lsp::Diagnostic {
        range: primary_label_range,
        code: diagnostic.code.map(lsp::NumberOrString::String),
        source: source.into(),
        severity: Some(make_lsp_severity(diagnostic.severity)),
        message: diagnostic.message,
        related_information: if related_information.is_empty() {
            None
        } else {
            Some(related_information)
        },
    })
}

#[cfg(test)]
mod tests {
    use codespan::Location;

    use super::*;

    #[test]
    fn position() {
        let text = r#"
let test = 2
let test1 = ""
test
"#;
        let mut files = Files::new();
        let file_id = files.add("test", text);
        let pos = position_to_byte_index(
            &files,
            file_id,
            &lsp::Position {
                line: 3,
                character: 2,
            },
        )
        .unwrap();
        assert_eq!(Location::new(3, 2), files.location(file_id, pos).unwrap());
    }

    // The protocol specifies that each `character` in position is a UTF-16 character.
    // This means that `å` and `ä` here counts as 1 while `𐐀` counts as 2.
    const UNICODE: &str = "åä t𐐀b";

    #[test]
    fn unicode_get_byte_index() {
        let mut files = Files::new();
        let file_id = files.add("unicode", UNICODE);

        let result = position_to_byte_index(
            &files,
            file_id,
            &lsp::Position {
                line: 0,
                character: 3,
            },
        );
        assert_eq!(result, Ok(ByteIndex::from(5)));

        let result = position_to_byte_index(
            &files,
            file_id,
            &lsp::Position {
                line: 0,
                character: 6,
            },
        );
        assert_eq!(result, Ok(ByteIndex::from(10)));
    }

    #[test]
    fn unicode_get_position() {
        let mut files = Files::new();
        let file_id = files.add("unicode", UNICODE);

        let result = byte_index_to_position(&files, file_id, ByteIndex::from(5));
        assert_eq!(
            result,
            Ok(lsp::Position {
                line: 0,
                character: 3,
            })
        );

        let result = byte_index_to_position(&files, file_id, ByteIndex::from(10));
        assert_eq!(
            result,
            Ok(lsp::Position {
                line: 0,
                character: 6,
            })
        );
    }
}
<|endoftext|>


<commit_before>use crate::loom::thread::LocalKey;

use std::cell::Cell;
use std::marker;

/// Set a reference as a thread-local
#[macro_export]
macro_rules! scoped_thread_local {
    ($(#[$attrs:meta])* $vis:vis static $name:ident: $ty:ty) => (
        $(#[$attrs])*
        $vis static $name: $crate::macros::scoped_tls::ScopedKey<$ty>
            = $crate::macros::scoped_tls::ScopedKey {
                inner: {
                    thread_local!(static FOO: ::std::cell::Cell<*const ()> = {
                        std::cell::Cell::new(::std::ptr::null())
                    });
                    &FOO
                },
                _marker: ::std::marker::PhantomData,
            };
    )
}

/// Type representing a thread local storage key corresponding to a reference
/// to the type parameter `T`.
pub(crate) struct ScopedKey<T> {
    #[doc(hidden)]
    pub(crate) inner: &'static LocalKey<Cell<*const ()>>,
    #[doc(hidden)]
    pub(crate) _marker: marker::PhantomData<T>,
}

unsafe impl<T> Sync for ScopedKey<T> {}

impl<T> ScopedKey<T> {
    /// Inserts a value into this scoped thread local storage slot for a
    /// duration of a closure.
    pub(crate) fn set<F, R>(&'static self, t: &T, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        struct Reset {
            key: &'static LocalKey<Cell<*const ()>>,
            val: *const (),
        }

        impl Drop for Reset {
            fn drop(&mut self) {
                self.key.with(|c| c.set(self.val));
            }
        }

        let prev = self.inner.with(|c| {
            let prev = c.get();
            c.set(t as *const _ as *const ());
            prev
        });

        let _reset = Reset {
            key: self.inner,
            val: prev,
        };

        f()
    }

    /// Gets a value out of this scoped variable.
    pub(crate) fn with<F, R>(&'static self, f: F) -> R
    where
        F: FnOnce(Option<&T>) -> R,
    {
        let val = self.inner.with(|c| c.get());

        if val.is_null() {
            f(None)
        } else {
            unsafe { f(Some(&*(val as *const T))) }
        }
    }
}
<commit_msg>macros: `scoped_thread_local` should be private (#2470)<commit_after>use crate::loom::thread::LocalKey;

use std::cell::Cell;
use std::marker;

/// Set a reference as a thread-local
macro_rules! scoped_thread_local {
    ($(#[$attrs:meta])* $vis:vis static $name:ident: $ty:ty) => (
        $(#[$attrs])*
        $vis static $name: $crate::macros::scoped_tls::ScopedKey<$ty>
            = $crate::macros::scoped_tls::ScopedKey {
                inner: {
                    thread_local!(static FOO: ::std::cell::Cell<*const ()> = {
                        std::cell::Cell::new(::std::ptr::null())
                    });
                    &FOO
                },
                _marker: ::std::marker::PhantomData,
            };
    )
}

/// Type representing a thread local storage key corresponding to a reference
/// to the type parameter `T`.
pub(crate) struct ScopedKey<T> {
    #[doc(hidden)]
    pub(crate) inner: &'static LocalKey<Cell<*const ()>>,
    #[doc(hidden)]
    pub(crate) _marker: marker::PhantomData<T>,
}

unsafe impl<T> Sync for ScopedKey<T> {}

impl<T> ScopedKey<T> {
    /// Inserts a value into this scoped thread local storage slot for a
    /// duration of a closure.
    pub(crate) fn set<F, R>(&'static self, t: &T, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        struct Reset {
            key: &'static LocalKey<Cell<*const ()>>,
            val: *const (),
        }

        impl Drop for Reset {
            fn drop(&mut self) {
                self.key.with(|c| c.set(self.val));
            }
        }

        let prev = self.inner.with(|c| {
            let prev = c.get();
            c.set(t as *const _ as *const ());
            prev
        });

        let _reset = Reset {
            key: self.inner,
            val: prev,
        };

        f()
    }

    /// Gets a value out of this scoped variable.
    pub(crate) fn with<F, R>(&'static self, f: F) -> R
    where
        F: FnOnce(Option<&T>) -> R,
    {
        let val = self.inner.with(|c| c.get());

        if val.is_null() {
            f(None)
        } else {
            unsafe { f(Some(&*(val as *const T))) }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Format datetimes for interoperability<commit_after><|endoftext|>


<commit_before>extern crate anduin;
extern crate winit;//TODO: no 3rd party crates in tests

use anduin::logic::{Actable, lcm, Application};
use anduin::core;
use anduin::input::{InputProcessor, Key};
use anduin::graphics::Drawable;
use anduin::audio::{music, sound, PlaybackController};
use std::thread::sleep;
use std::time::Duration;

fn create_test_app() {
    let mut application = Application::new("Anduin", "desktop", Some(5));
    println!("application created");
    let game_loop = lcm::GameLoop::new();
    println!("game_loop created");
    application.input.add_input_processor(Box::new(anduin::InputProcessorStuct{}));
    println!("add_input_processor finished");
    game_loop.run(&mut application);
    println!("game_loop runned");
    application.exit();
}

#[test]
fn play_sound() {
    let music = music::Music::new("resources/music.ogg");
    let sound = sound::Sound::new("resources/shot.wav");
    music.play();
    sound.play();
    sleep(Duration::from_millis(5000));
}

#[test]
fn create_game_loop() {
    let game_loop = lcm::GameLoop::new();
    println!("Loop is created {:?}", game_loop);
}

#[test]
fn create_simple_scene() {
    let scene = core::scene::Stage {root: core::scene::Node::new("Root Node")};
    println!("Simple scene is created {:?}", scene);
}

fn create_simple_game()
{
    let scene = core::scene::Stage {
        root: core::scene::Node::build("Root Node", Actor{}, Control{}, Image{})
    };
    scene.update();
}

struct Actor {

}
struct Image {

}
struct Control {

}

impl Actable for Actor {
    fn update(&self) {
        println!("Update self");
    }
}

impl Drawable for Image {
    fn draw(&self) {
        println!("Draw self");
    }
}

impl InputProcessor for Control {
        fn key_down(&self, key: Key)
        {
            println!("Keypushed down: {:?}", key)
        }
    	fn key_up(&self, key: Key)
        {
            println!("Keypushed up: {:?}", key)
        }
}

/*
Simple game TC
Game game = new Game(width, height, title);
Screen menu_screen = new Screen(title);
Button new_game = new Button();
ButtonActionHandler start_game = new ButtonActionHandler(new_game);
Stage main_stage = new Stage(new Viewport(new Camera()));
main_stage.add(Ball{radius, Mesh{material, color}});
main_stage.add(Line{vec![{x1,y1}, {x2,y2}]});
*/
<commit_msg>Test gitlab integration with github<commit_after>extern crate anduin;
extern crate winit;//TODO: no 3rd party crates in tests

use anduin::logic::{Actable, lcm, Application};
use anduin::core;
use anduin::input::{InputProcessor, Key};
use anduin::graphics::Drawable;
use anduin::audio::{music, sound, PlaybackController};
use std::thread::sleep;
use std::time::Duration;

fn create_test_app() {
    let mut application = Application::new("Anduin", "desktop", Some(5));
    println!("application created");
    let game_loop = lcm::GameLoop::new();
    println!("game_loop created");
    application.input.add_input_processor(Box::new(anduin::InputProcessorStuct{}));
    println!("add_input_processor finished");
    game_loop.run(&mut application);
    println!("game_loop runned");
    application.exit();
}

#[test]
fn play_sound() {
    let music = music::Music::new("resources/music.ogg");
    let sound = sound::Sound::new("resources/shot.wav");
    music.play();
    sound.play();
    sleep(Duration::from_millis(5000));
}

#[test]
fn create_game_loop() {
    let game_loop = lcm::GameLoop::new();
    println!("Loop is created {:?}", game_loop);
}

#[test]
fn create_simple_scene() {
    let scene = core::scene::Stage {root: core::scene::Node::new("Root Node")};
    println!("Simple scene is created {:?}", scene);
}

fn create_simple_game()
{
    let scene = core::scene::Stage {
        root: core::scene::Node::build("Root Node", Actor{}, Control{}, Image{})
    };
    scene.update();
}

struct Actor {

}
struct Image {

}
struct Control {

}

impl Actable for Actor {
    fn update(&self) {
        println!("Updating self");
    }
}

impl Drawable for Image {
    fn draw(&self) {
        println!("Drawing self");
    }
}

impl InputProcessor for Control {
        fn key_down(&self, key: Key)
        {
            println!("Keypushed down: {:?}", key)
        }
    	fn key_up(&self, key: Key)
        {
            println!("Keypushed up: {:?}", key)
        }
}

/*
Simple game TC
Game game = new Game(width, height, title);
Screen menu_screen = new Screen(title);
Button new_game = new Button();
ButtonActionHandler start_game = new ButtonActionHandler(new_game);
Stage main_stage = new Stage(new Viewport(new Camera()));
main_stage.add(Ball{radius, Mesh{material, color}});
main_stage.add(Line{vec![{x1,y1}, {x2,y2}]});
*/
<|endoftext|>


<commit_before>extern crate exonum;
extern crate exonum_time;
#[macro_use]
extern crate exonum_testkit;
#[macro_use]
extern crate pretty_assertions;

use std::time::{SystemTime, Duration, UNIX_EPOCH};

use exonum::helpers::{Height, ValidatorId};
use exonum::crypto::gen_keypair;

use exonum_time::{TimeService, TimeSchema, TxTime, Time, TimeProvider};
use exonum_testkit::{TestKitBuilder, TestNode};

#[test]
fn test_exonum_time_service() {
    let mut testkit = TestKitBuilder::validator()
        .with_validators(3)
        .with_service(TimeService::new())
        .create();

    let validators = testkit.network().validators().to_vec();

    // Validators time, that is saved in storage, look like this:
    // number | 0    | 1    | 2    |
    // time   | None | None | None |
    //
    // Time, that is saved in storage, is None

    let validators_time_test: Vec<Option<Time>> = vec![None, None, None];

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);
    let validators_time_storage = schema.validators_time();

    for (num, validator) in validators.iter().enumerate() {
        let pub_key = &validator.public_keys().service_key;
        assert_eq!(
            validators_time_test[num],
            validators_time_storage.get(pub_key)
        );
    }
    assert_eq!(schema.time().get(), None);

    // Add first transaction 'tx0' from first validator with time 'time0'.
    // After that validators time look like this:
    // number | 0       | 0    | 0    |
    // time   | 'time0' | None | None |
    //
    // Time, that is saved in storage, does not change.

    let time0 = SystemTime::now();
    let tx0 = {
        let (pub_key, sec_key) = validators[0].service_keypair();
        TxTime::new(time0, pub_key, sec_key)
    };
    testkit.create_block_with_transactions(txvec![tx0.clone()]);

    let validators_time_test: Vec<Option<Time>> = vec![Some(Time::new(time0)), None, None];
    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);
    let validators_time_storage = schema.validators_time();

    for (num, validator) in validators.iter().enumerate() {
        let pub_key = &validator.public_keys().service_key;
        assert_eq!(
            validators_time_test[num],
            validators_time_storage.get(pub_key)
        );
    }
    assert_eq!(schema.time().get(), None);

    // Add second transaction 'tx1' from second validator with time 'time1' = 'time0' + 10 sec.
    // After that validators time look like this:
    // number | 0       | 1       | 2    |
    // time   | 'time0' | 'time1' | None |
    //
    // In sorted order: 'time1' >= 'time0'
    // Time, that is saved in storage, does not change.

    let time1 = time0 + Duration::new(10, 0);
    let tx1 = {
        let (pub_key, sec_key) = validators[1].service_keypair();
        TxTime::new(time1, pub_key, sec_key)
    };
    testkit.create_block_with_transactions(txvec![tx1.clone()]);

    let validators_time_test: Vec<Option<Time>> =
        vec![Some(Time::new(time0)), Some(Time::new(time1)), None];

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);
    let validators_time_storage = schema.validators_time();

    for (num, validator) in validators.iter().enumerate() {
        let pub_key = &validator.public_keys().service_key;
        assert_eq!(
            validators_time_test[num],
            validators_time_storage.get(pub_key)
        );
    }
    assert_eq!(schema.time().get(), None);

    // Add third transaction 'tx2' from third validator with time 'time2' = 'time1' + 10 sec.
    // After that validators time look like this:
    // number | 0       | 1       | 2       |
    // time   | 'time0' | 'time1' | 'time2' |
    //
    // In sorted order: 'time2' >= 'time1' >= 'time0'
    // Time, that is saved in storage, will have the value 'time1'.

    let time2 = time1 + Duration::new(10, 0);
    let tx2 = {
        let (pub_key, sec_key) = validators[2].service_keypair();
        TxTime::new(time2, pub_key, sec_key)
    };
    testkit.create_block_with_transactions(txvec![tx2.clone()]);

    let validators_time_test: Vec<Option<Time>> = vec![
        Some(Time::new(time0)),
        Some(Time::new(time1)),
        Some(Time::new(time2)),
    ];

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);
    let validators_time_storage = schema.validators_time();

    for (num, validator) in validators.iter().enumerate() {
        let pub_key = &validator.public_keys().service_key;
        assert_eq!(
            validators_time_test[num],
            validators_time_storage.get(pub_key)
        );
    }
    assert_eq!(schema.time().get(), Some(Time::new(time1)));
}

// A struct that provides the node with the current time.
#[derive(Debug)]
struct MyTimeProvider;
impl TimeProvider for MyTimeProvider {
    fn current_time(&self) -> SystemTime {
        UNIX_EPOCH
    }
}

#[test]
fn test_mock_provider() {
    // Create a simple testkit network.
    let mut testkit = TestKitBuilder::validator()
        .with_service(TimeService::with_provider(
            Box::new(MyTimeProvider) as Box<TimeProvider>,
        ))
        .create();

    // Get the validator public key.
    let validator_public_key = &testkit.network().validators().to_vec()[0]
        .public_keys()
        .service_key;

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);

    // Check that the blockchain does not contain time.
    assert_eq!(schema.time().get(), None);
    // Check that the time for the validator is unknown.
    assert_eq!(schema.validators_time().get(validator_public_key), None);

    // Create two blocks.
    testkit.create_blocks_until(Height(2));

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);

    // Check that the time in the blockchain and for the validator has been updated.
    assert_eq!(schema.time().get(), Some(Time::new(UNIX_EPOCH)));
    assert_eq!(
        schema.validators_time().get(validator_public_key),
        Some(Time::new(UNIX_EPOCH))
    );
}

#[test]
fn test_selected_time_less_than_time_in_storage() {
    let mut testkit = TestKitBuilder::validator()
        .with_validators(1)
        .with_service(TimeService::new())
        .create();

    let validators = testkit.network().validators().to_vec();

    let (pub_key_0, _) = validators[0].service_keypair();

    let cfg_change_height = Height(5);
    let new_cfg = {
        let mut cfg = testkit.configuration_change_proposal();
        cfg.set_validators(vec![TestNode::new_validator(ValidatorId(0))]);
        cfg.set_actual_from(cfg_change_height);
        cfg
    };
    testkit.commit_configuration_change(new_cfg);
    testkit.create_blocks_until(cfg_change_height.previous());

    let validators = testkit.network().validators().to_vec();
    let (pub_key_1, sec_key_1) = validators[0].service_keypair();

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);

    assert!(schema.time().get().is_some());
    assert!(schema.validators_time().get(pub_key_0).is_some());
    assert!(schema.validators_time().get(pub_key_1).is_none());
    assert_eq!(schema.time().get(), schema.validators_time().get(pub_key_0));

    if let Some(time_in_storage) = schema.time().get() {
        let time_tx = time_in_storage.time() - Duration::new(10, 0);
        let tx = {
            TxTime::new(time_tx, pub_key_1, sec_key_1)
        };
        testkit.create_block_with_transactions(txvec![tx.clone()]);
    }

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);
    assert!(schema.time().get().is_some());
    assert!(schema.validators_time().get(pub_key_0).is_some());
    assert!(schema.validators_time().get(pub_key_1).is_some());
    assert_eq!(schema.time().get(), schema.validators_time().get(pub_key_0));
}

#[test]
fn test_creating_transaction_is_not_validator() {
    let mut testkit = TestKitBuilder::validator()
        .with_validators(1)
        .with_service(TimeService::new())
        .create();

    let (pub_key, sec_key) = gen_keypair();
    let tx = TxTime::new(SystemTime::now(), &pub_key, &sec_key);
    testkit.create_block_with_transactions(txvec![tx.clone()]);

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);
    assert!(schema.time().get().is_none());
    assert!(schema.validators_time().get(&pub_key).is_none());
}

#[test]
fn test_transaction_time_less_than_validator_time_in_storage() {
    let mut testkit = TestKitBuilder::validator()
        .with_validators(1)
        .with_service(TimeService::new())
        .create();

    let validator = &testkit.network().validators().to_vec()[0];
    let (pub_key, sec_key) = validator.service_keypair();

    let time0 = SystemTime::now();
    let tx0 = TxTime::new(time0, pub_key, sec_key);

    testkit.create_block_with_transactions(txvec![tx0.clone()]);

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);

    assert_eq!(schema.time().get(), Some(Time::new(time0)));
    assert_eq!(
        schema.validators_time().get(pub_key),
        Some(Time::new(time0))
    );

    let time1 = time0 - Duration::new(10, 0);
    let tx1 = TxTime::new(time1, pub_key, sec_key);

    testkit.create_block_with_transactions(txvec![tx1.clone()]);

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);

    assert_eq!(schema.time().get(), Some(Time::new(time0)));
    assert_eq!(
        schema.validators_time().get(pub_key),
        Some(Time::new(time0))
    );
}
<commit_msg>Fix test_exonum_time_service()<commit_after>extern crate exonum;
extern crate exonum_time;
#[macro_use]
extern crate exonum_testkit;
#[macro_use]
extern crate pretty_assertions;

use std::time::{SystemTime, Duration, UNIX_EPOCH};

use exonum::helpers::{Height, ValidatorId};
use exonum::crypto::gen_keypair;

use exonum_time::{TimeService, TimeSchema, TxTime, Time, TimeProvider};
use exonum_testkit::{TestKitBuilder, TestNode};

#[test]
fn test_exonum_time_service() {
    let mut testkit = TestKitBuilder::validator()
        .with_validators(3)
        .with_service(TimeService::new())
        .create();

    let validators = testkit.network().validators().to_vec();

    // Validators time, that is saved in storage, look like this:
    // number | 0    | 1    | 2    |
    // time   | None | None | None |
    //
    // Time, that is saved in storage, is None

    let validators_time_test: Vec<Option<Time>> = vec![None, None, None];

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);
    let validators_time_storage = schema.validators_time();

    for (num, validator) in validators.iter().enumerate() {
        let pub_key = &validator.public_keys().service_key;
        assert_eq!(
            validators_time_test[num],
            validators_time_storage.get(pub_key)
        );
    }
    assert_eq!(schema.time().get(), None);

    // Add first transaction 'tx0' from first validator with time 'time0'.
    // After that validators time look like this:
    // number | 0       | 0    | 0    |
    // time   | 'time0' | None | None |
    //
    // Time, that is saved in storage, will have the value 'time0'.

    let time0 = SystemTime::now();
    let tx0 = {
        let (pub_key, sec_key) = validators[0].service_keypair();
        TxTime::new(time0, pub_key, sec_key)
    };
    testkit.create_block_with_transactions(txvec![tx0.clone()]);

    let validators_time_test: Vec<Option<Time>> = vec![Some(Time::new(time0)), None, None];
    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);
    let validators_time_storage = schema.validators_time();

    for (num, validator) in validators.iter().enumerate() {
        let pub_key = &validator.public_keys().service_key;
        assert_eq!(
            validators_time_test[num],
            validators_time_storage.get(pub_key)
        );
    }
    assert_eq!(schema.time().get(), Some(Time::new(time0)));

    // Add second transaction 'tx1' from second validator with time 'time1' = 'time0' + 10 sec.
    // After that validators time look like this:
    // number | 0       | 1       | 2    |
    // time   | 'time0' | 'time1' | None |
    //
    // In sorted order: 'time1' >= 'time0'
    // Time, that is saved in storage, will have the value 'time1'.

    let time1 = time0 + Duration::new(10, 0);
    let tx1 = {
        let (pub_key, sec_key) = validators[1].service_keypair();
        TxTime::new(time1, pub_key, sec_key)
    };
    testkit.create_block_with_transactions(txvec![tx1.clone()]);

    let validators_time_test: Vec<Option<Time>> =
        vec![Some(Time::new(time0)), Some(Time::new(time1)), None];

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);
    let validators_time_storage = schema.validators_time();

    for (num, validator) in validators.iter().enumerate() {
        let pub_key = &validator.public_keys().service_key;
        assert_eq!(
            validators_time_test[num],
            validators_time_storage.get(pub_key)
        );
    }
    assert_eq!(schema.time().get(), Some(Time::new(time1)));

    // Add third transaction 'tx2' from third validator with time 'time2' = 'time1' + 10 sec.
    // After that validators time look like this:
    // number | 0       | 1       | 2       |
    // time   | 'time0' | 'time1' | 'time2' |
    //
    // In sorted order: 'time2' >= 'time1' >= 'time0'
    // Time, that is saved in storage, will have the value 'time2'.

    let time2 = time1 + Duration::new(10, 0);
    let tx2 = {
        let (pub_key, sec_key) = validators[2].service_keypair();
        TxTime::new(time2, pub_key, sec_key)
    };
    testkit.create_block_with_transactions(txvec![tx2.clone()]);

    let validators_time_test: Vec<Option<Time>> = vec![
        Some(Time::new(time0)),
        Some(Time::new(time1)),
        Some(Time::new(time2)),
    ];

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);
    let validators_time_storage = schema.validators_time();

    for (num, validator) in validators.iter().enumerate() {
        let pub_key = &validator.public_keys().service_key;
        assert_eq!(
            validators_time_test[num],
            validators_time_storage.get(pub_key)
        );
    }
    assert_eq!(schema.time().get(), Some(Time::new(time2)));
}

// A struct that provides the node with the current time.
#[derive(Debug)]
struct MyTimeProvider;
impl TimeProvider for MyTimeProvider {
    fn current_time(&self) -> SystemTime {
        UNIX_EPOCH
    }
}

#[test]
fn test_mock_provider() {
    // Create a simple testkit network.
    let mut testkit = TestKitBuilder::validator()
        .with_service(TimeService::with_provider(
            Box::new(MyTimeProvider) as Box<TimeProvider>,
        ))
        .create();

    // Get the validator public key.
    let validator_public_key = &testkit.network().validators().to_vec()[0]
        .public_keys()
        .service_key;

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);

    // Check that the blockchain does not contain time.
    assert_eq!(schema.time().get(), None);
    // Check that the time for the validator is unknown.
    assert_eq!(schema.validators_time().get(validator_public_key), None);

    // Create two blocks.
    testkit.create_blocks_until(Height(2));

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);

    // Check that the time in the blockchain and for the validator has been updated.
    assert_eq!(schema.time().get(), Some(Time::new(UNIX_EPOCH)));
    assert_eq!(
        schema.validators_time().get(validator_public_key),
        Some(Time::new(UNIX_EPOCH))
    );
}

#[test]
fn test_selected_time_less_than_time_in_storage() {
    let mut testkit = TestKitBuilder::validator()
        .with_validators(1)
        .with_service(TimeService::new())
        .create();

    let validators = testkit.network().validators().to_vec();

    let (pub_key_0, _) = validators[0].service_keypair();

    let cfg_change_height = Height(5);
    let new_cfg = {
        let mut cfg = testkit.configuration_change_proposal();
        cfg.set_validators(vec![TestNode::new_validator(ValidatorId(0))]);
        cfg.set_actual_from(cfg_change_height);
        cfg
    };
    testkit.commit_configuration_change(new_cfg);
    testkit.create_blocks_until(cfg_change_height.previous());

    let validators = testkit.network().validators().to_vec();
    let (pub_key_1, sec_key_1) = validators[0].service_keypair();

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);

    assert!(schema.time().get().is_some());
    assert!(schema.validators_time().get(pub_key_0).is_some());
    assert!(schema.validators_time().get(pub_key_1).is_none());
    assert_eq!(schema.time().get(), schema.validators_time().get(pub_key_0));

    if let Some(time_in_storage) = schema.time().get() {
        let time_tx = time_in_storage.time() - Duration::new(10, 0);
        let tx = {
            TxTime::new(time_tx, pub_key_1, sec_key_1)
        };
        testkit.create_block_with_transactions(txvec![tx.clone()]);
    }

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);
    assert!(schema.time().get().is_some());
    assert!(schema.validators_time().get(pub_key_0).is_some());
    assert!(schema.validators_time().get(pub_key_1).is_some());
    assert_eq!(schema.time().get(), schema.validators_time().get(pub_key_0));
}

#[test]
fn test_creating_transaction_is_not_validator() {
    let mut testkit = TestKitBuilder::validator()
        .with_validators(1)
        .with_service(TimeService::new())
        .create();

    let (pub_key, sec_key) = gen_keypair();
    let tx = TxTime::new(SystemTime::now(), &pub_key, &sec_key);
    testkit.create_block_with_transactions(txvec![tx.clone()]);

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);
    assert!(schema.time().get().is_none());
    assert!(schema.validators_time().get(&pub_key).is_none());
}

#[test]
fn test_transaction_time_less_than_validator_time_in_storage() {
    let mut testkit = TestKitBuilder::validator()
        .with_validators(1)
        .with_service(TimeService::new())
        .create();

    let validator = &testkit.network().validators().to_vec()[0];
    let (pub_key, sec_key) = validator.service_keypair();

    let time0 = SystemTime::now();
    let tx0 = TxTime::new(time0, pub_key, sec_key);

    testkit.create_block_with_transactions(txvec![tx0.clone()]);

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);

    assert_eq!(schema.time().get(), Some(Time::new(time0)));
    assert_eq!(
        schema.validators_time().get(pub_key),
        Some(Time::new(time0))
    );

    let time1 = time0 - Duration::new(10, 0);
    let tx1 = TxTime::new(time1, pub_key, sec_key);

    testkit.create_block_with_transactions(txvec![tx1.clone()]);

    let snapshot = testkit.snapshot();
    let schema = TimeSchema::new(snapshot);

    assert_eq!(schema.time().get(), Some(Time::new(time0)));
    assert_eq!(
        schema.validators_time().get(pub_key),
        Some(Time::new(time0))
    );
}
<|endoftext|>


<commit_before><commit_msg>Add method to pass through io streams<commit_after><|endoftext|>