<commit_before>/**
 * At the moment, this is a partial hashmap implementation, not yet fit for
 * use, but useful as a stress test for rustboot.
 */

type hashfn[K] = fn(&K) -> uint;
type eqfn[K] = fn(&K, &K) -> bool;

state type hashmap[K, V] = state obj {
                                 fn size() -> uint;
                                 fn insert(&K key, &V val) -> bool;
                                 fn contains_key(&K key) -> bool;
                                 fn get(&K key) -> V;
                                 fn find(&K key) -> option.t[V];
                                 fn remove(&K key) -> option.t[V];
                                 fn rehash();
                                 iter items() -> @tup(K,V);
};

fn mk_hashmap[K, V](&hashfn[K] hasher, &eqfn[K] eqer) -> hashmap[K, V] {

    let uint initial_capacity = 32u; // 2^5
    let util.rational load_factor = rec(num=3, den=4);

    tag bucket[K, V] {
        nil;
        deleted;
        some(K, V);
    }

    fn make_buckets[K, V](uint nbkts) -> vec[mutable bucket[K, V]] {
        ret _vec.init_elt_mut[bucket[K, V]](nil[K, V], nbkts);
    }

    // Derive two hash functions from the one given by taking the upper
    // half and lower half of the uint bits.  Our bucket probing
    // sequence is then defined by
    //
    //   hash(key, i) := hashl(key) + i * hashr(key)   for i = 0, 1, 2, ...
    //
    // Tearing the hash function apart this way is kosher in practice
    // as, assuming 32-bit uints, the table would have to be at 2^32
    // buckets before the resulting pair of hash functions no longer
    // probes all buckets for a fixed key.  Note that hashr is made to
    // output odd numbers (hence coprime to the number of nbkts, which
    // is always a power of 2), so that all buckets are probed for a
    // fixed key.

    fn hashl(uint n, uint nbkts) -> uint {
        ret (n >>> 16u);
    }

    fn hashr(uint n, uint nbkts) -> uint {
        ret ((((~ 0u) >>> 16u) & n) * 2u + 1u);
    }

    fn hash(uint h, uint nbkts, uint i) -> uint {
        ret (hashl(h, nbkts) + i * hashr(h, nbkts)) % nbkts;
    }

    /**
     * We attempt to never call this with a full table.  If we do, it
     * will fail.
     */
    fn insert_common[K, V](&hashfn[K] hasher,
                                  &eqfn[K] eqer,
                                  vec[mutable bucket[K, V]] bkts,
                                  uint nbkts,
                                  &K key,
                                  &V val)
        -> bool
        {
            let uint i = 0u;
            let uint h = hasher(key);
            while (i < nbkts) {
                let uint j = hash(h, nbkts, i);
                alt (bkts.(j)) {
                    case (some[K, V](?k, _)) {
                        if (eqer(key, k)) {
                            bkts.(j) = some[K, V](k, val);
                            ret false;
                        }
                        i += 1u;
                    }
                    case (_) {
                        bkts.(j) = some[K, V](key, val);
                        ret true;
                    }
                }
            }
            fail; // full table
        }

    fn find_common[K, V](&hashfn[K] hasher,
                         &eqfn[K] eqer,
                         vec[mutable bucket[K, V]] bkts,
                         uint nbkts,
                         &K key)
        -> option.t[V]
        {
            let uint i = 0u;
            let uint h = hasher(key);
            while (i < nbkts) {
                let uint j = (hash(h, nbkts, i));
                alt (bkts.(j)) {
                    case (some[K, V](?k, ?v)) {
                        if (eqer(key, k)) {
                            ret option.some[V](v);
                        }
                    }
                    case (nil[K, V]) {
                        ret option.none[V];
                    }
                    case (deleted[K, V]) { }
                }
                i += 1u;
            }
            ret option.none[V];
        }

   fn rehash[K, V](&hashfn[K] hasher,
                          &eqfn[K] eqer,
                          vec[mutable bucket[K, V]] oldbkts, uint noldbkts,
                          vec[mutable bucket[K, V]] newbkts, uint nnewbkts)
        {
            for (bucket[K, V] b in oldbkts) {
                alt (b) {
                    case (some[K, V](?k, ?v)) {
                        insert_common[K, V](hasher, eqer, newbkts,
                                            nnewbkts, k, v);
                    }
                    case (_) { }
                }
            }
        }

    state obj hashmap[K, V](hashfn[K] hasher,
                            eqfn[K] eqer,
                            mutable vec[mutable bucket[K, V]] bkts,
                            mutable uint nbkts,
                            mutable uint nelts,
                            util.rational lf)
        {
            fn size() -> uint { ret nelts; }

            fn insert(&K key, &V val) -> bool {
                let util.rational load = rec(num=(nelts + 1u) as int,
                                             den=nbkts as int);
                if (!util.rational_leq(load, lf)) {
                    let uint nnewbkts = _uint.next_power_of_two(nbkts + 1u);
                    let vec[mutable bucket[K, V]] newbkts =
                        make_buckets[K, V](nnewbkts);
                    rehash[K, V](hasher, eqer, bkts, nbkts,
                                 newbkts, nnewbkts);
                    bkts = newbkts;
                    nbkts = nnewbkts;
                }

                if (insert_common[K, V](hasher, eqer, bkts,
                                        nbkts, key, val)) {
                    nelts += 1u;
                    ret true;
                }
                ret false;
            }

            fn contains_key(&K key) -> bool {
                alt (find_common[K, V](hasher, eqer, bkts, nbkts, key)) {
                    case (option.some[V](_)) { ret true; }
                    case (_) { ret false; }
                }
                fail;   // FIXME: remove me when exhaustiveness checking works
            }

            fn get(&K key) -> V {
                alt (find_common[K, V](hasher, eqer, bkts, nbkts, key)) {
                    case (option.some[V](?val)) { ret val; }
                    case (_) { fail; }
                }
                fail;   // FIXME: remove me when exhaustiveness checking works
            }

            fn find(&K key) -> option.t[V] {
                // FIXME: should be 'be' but parametric tail-calls don't
                // work at the moment.
                ret find_common[K, V](hasher, eqer, bkts, nbkts, key);
            }

            fn remove(&K key) -> option.t[V] {
                let uint i = 0u;
                let uint h = hasher(key);
                while (i < nbkts) {
                    let uint j = (hash(h, nbkts, i));
                    alt (bkts.(j)) {
                        case (some[K, V](?k, ?v)) {
                            if (eqer(key, k)) {
                                bkts.(j) = deleted[K, V];
                                nelts -= 1u;
                                ret option.some[V](v);
                            }
                        }
                        case (deleted[K, V]) { }
                        case (nil[K, V]) {
                            ret option.none[V];
                        }
                    }
                    i += 1u;
                }
                ret option.none[V];
            }

            fn rehash() {
                let vec[mutable bucket[K, V]] newbkts =
                    make_buckets[K, V](nbkts);
                rehash[K, V](hasher, eqer, bkts, nbkts, newbkts, nbkts);
                bkts = newbkts;
            }

            iter items() -> @tup(K,V) {
                for (bucket[K,V] b in bkts) {
                    alt (b) {
                        case(some[K,V](?k,?v)) {
                            put @tup(k,v);
                        }
                        case (_) { }
                    }
                }
            }
        }

    let vec[mutable bucket[K, V]] bkts =
        make_buckets[K, V](initial_capacity);

    ret hashmap[K, V](hasher, eqer, bkts, initial_capacity, 0u, load_factor);
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>Skip likely-zero initial probe, speed up map.rs.<commit_after>/**
 * At the moment, this is a partial hashmap implementation, not yet fit for
 * use, but useful as a stress test for rustboot.
 */

type hashfn[K] = fn(&K) -> uint;
type eqfn[K] = fn(&K, &K) -> bool;

state type hashmap[K, V] = state obj {
                                 fn size() -> uint;
                                 fn insert(&K key, &V val) -> bool;
                                 fn contains_key(&K key) -> bool;
                                 fn get(&K key) -> V;
                                 fn find(&K key) -> option.t[V];
                                 fn remove(&K key) -> option.t[V];
                                 fn rehash();
                                 iter items() -> @tup(K,V);
};

fn mk_hashmap[K, V](&hashfn[K] hasher, &eqfn[K] eqer) -> hashmap[K, V] {

    let uint initial_capacity = 32u; // 2^5
    let util.rational load_factor = rec(num=3, den=4);

    tag bucket[K, V] {
        nil;
        deleted;
        some(K, V);
    }

    fn make_buckets[K, V](uint nbkts) -> vec[mutable bucket[K, V]] {
        ret _vec.init_elt_mut[bucket[K, V]](nil[K, V], nbkts);
    }

    // Derive two hash functions from the one given by taking the upper
    // half and lower half of the uint bits.  Our bucket probing
    // sequence is then defined by
    //
    //   hash(key, i) := hashl(key) * i + hashr(key)   for i = 0, 1, 2, ...
    //
    // Tearing the hash function apart this way is kosher in practice
    // as, assuming 32-bit uints, the table would have to be at 2^32
    // buckets before the resulting pair of hash functions no longer
    // probes all buckets for a fixed key.  Note that hashl is made to
    // output odd numbers (hence coprime to the number of nbkts, which
    // is always a power of 2), so that all buckets are probed for a
    // fixed key.

    fn hashl(uint n, uint nbkts) -> uint {
        ret ((n >>> 16u) * 2u + 1u);
    }

    fn hashr(uint n, uint nbkts) -> uint {
        ret (0x0000_ffff_u & n);
    }

    fn hash(uint h, uint nbkts, uint i) -> uint {
        ret (hashl(h, nbkts) * i + hashr(h, nbkts)) % nbkts;
    }

    /**
     * We attempt to never call this with a full table.  If we do, it
     * will fail.
     */
    fn insert_common[K, V](&hashfn[K] hasher,
                                  &eqfn[K] eqer,
                                  vec[mutable bucket[K, V]] bkts,
                                  uint nbkts,
                                  &K key,
                                  &V val)
        -> bool
        {
            let uint i = 0u;
            let uint h = hasher(key);
            while (i < nbkts) {
                let uint j = hash(h, nbkts, i);
                alt (bkts.(j)) {
                    case (some[K, V](?k, _)) {
                        if (eqer(key, k)) {
                            bkts.(j) = some[K, V](k, val);
                            ret false;
                        }
                        i += 1u;
                    }
                    case (_) {
                        bkts.(j) = some[K, V](key, val);
                        ret true;
                    }
                }
            }
            fail; // full table
        }

    fn find_common[K, V](&hashfn[K] hasher,
                         &eqfn[K] eqer,
                         vec[mutable bucket[K, V]] bkts,
                         uint nbkts,
                         &K key)
        -> option.t[V]
        {
            let uint i = 0u;
            let uint h = hasher(key);
            while (i < nbkts) {
                let uint j = (hash(h, nbkts, i));
                alt (bkts.(j)) {
                    case (some[K, V](?k, ?v)) {
                        if (eqer(key, k)) {
                            ret option.some[V](v);
                        }
                    }
                    case (nil[K, V]) {
                        ret option.none[V];
                    }
                    case (deleted[K, V]) { }
                }
                i += 1u;
            }
            ret option.none[V];
        }

   fn rehash[K, V](&hashfn[K] hasher,
                          &eqfn[K] eqer,
                          vec[mutable bucket[K, V]] oldbkts, uint noldbkts,
                          vec[mutable bucket[K, V]] newbkts, uint nnewbkts)
        {
            for (bucket[K, V] b in oldbkts) {
                alt (b) {
                    case (some[K, V](?k, ?v)) {
                        insert_common[K, V](hasher, eqer, newbkts,
                                            nnewbkts, k, v);
                    }
                    case (_) { }
                }
            }
        }

    state obj hashmap[K, V](hashfn[K] hasher,
                            eqfn[K] eqer,
                            mutable vec[mutable bucket[K, V]] bkts,
                            mutable uint nbkts,
                            mutable uint nelts,
                            util.rational lf)
        {
            fn size() -> uint { ret nelts; }

            fn insert(&K key, &V val) -> bool {
                let util.rational load = rec(num=(nelts + 1u) as int,
                                             den=nbkts as int);
                if (!util.rational_leq(load, lf)) {
                    let uint nnewbkts = _uint.next_power_of_two(nbkts + 1u);
                    let vec[mutable bucket[K, V]] newbkts =
                        make_buckets[K, V](nnewbkts);
                    rehash[K, V](hasher, eqer, bkts, nbkts,
                                 newbkts, nnewbkts);
                    bkts = newbkts;
                    nbkts = nnewbkts;
                }

                if (insert_common[K, V](hasher, eqer, bkts,
                                        nbkts, key, val)) {
                    nelts += 1u;
                    ret true;
                }
                ret false;
            }

            fn contains_key(&K key) -> bool {
                alt (find_common[K, V](hasher, eqer, bkts, nbkts, key)) {
                    case (option.some[V](_)) { ret true; }
                    case (_) { ret false; }
                }
                fail;   // FIXME: remove me when exhaustiveness checking works
            }

            fn get(&K key) -> V {
                alt (find_common[K, V](hasher, eqer, bkts, nbkts, key)) {
                    case (option.some[V](?val)) { ret val; }
                    case (_) { fail; }
                }
                fail;   // FIXME: remove me when exhaustiveness checking works
            }

            fn find(&K key) -> option.t[V] {
                // FIXME: should be 'be' but parametric tail-calls don't
                // work at the moment.
                ret find_common[K, V](hasher, eqer, bkts, nbkts, key);
            }

            fn remove(&K key) -> option.t[V] {
                let uint i = 0u;
                let uint h = hasher(key);
                while (i < nbkts) {
                    let uint j = (hash(h, nbkts, i));
                    alt (bkts.(j)) {
                        case (some[K, V](?k, ?v)) {
                            if (eqer(key, k)) {
                                bkts.(j) = deleted[K, V];
                                nelts -= 1u;
                                ret option.some[V](v);
                            }
                        }
                        case (deleted[K, V]) { }
                        case (nil[K, V]) {
                            ret option.none[V];
                        }
                    }
                    i += 1u;
                }
                ret option.none[V];
            }

            fn rehash() {
                let vec[mutable bucket[K, V]] newbkts =
                    make_buckets[K, V](nbkts);
                rehash[K, V](hasher, eqer, bkts, nbkts, newbkts, nbkts);
                bkts = newbkts;
            }

            iter items() -> @tup(K,V) {
                for (bucket[K,V] b in bkts) {
                    alt (b) {
                        case(some[K,V](?k,?v)) {
                            put @tup(k,v);
                        }
                        case (_) { }
                    }
                }
            }
        }

    let vec[mutable bucket[K, V]] bkts =
        make_buckets[K, V](initial_capacity);

    ret hashmap[K, V](hasher, eqer, bkts, initial_capacity, 0u, load_factor);
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|endoftext|>


<commit_before><commit_msg>Sync with the specification<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: a tag can contain ascii digits<commit_after><|endoftext|>


<commit_before><commit_msg>Rem - a tool for setting reminders<commit_after>#![deny(warnings)]

extern crate coreutils;

use std::env::args;
use std::io::{self, Write};
use std::process::exit;
use std::thread::sleep;
use std::time::Duration;

use coreutils::extra::OptionalExt;

static HELP: &'static str = r#"
    NAME
        rem - set a count-down.
    SYNOPSIS
        rem [-h | --help] [-m N | --minutes N] [-H N | --hours N] [-s N | --seconds N] [-M N | --milliseconds N] [-n | --len]
    DESCRIPTION
        This utility lets you set a count-down with a progress bar. The options can be given in combination, adding together the durations given.
    OPTIONS
        -h
        --help
            Print this manual page.
        -m N
        --minutes N
            Wait N minutes.
        -H N
        --hours N
            Wait N hours.
        -s N
        --seconds N
            Wait N seconds.
        -M N
        --milliseconds N
            Wait N milliseconds.
        -n
        --len
            Length of the progress bar.
    AUTHOR
        This program was written by Ticki for Redox OS. Bugs, issues, or feature requests should be reported in the Github repository, 'redox-os/extrautils'.
    COPYRIGHT
        Copyright (c) 2016 Ticki

        Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

        The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"#;

fn main() {
    let mut args = args().skip(1);
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    let mut stderr = io::stderr();

    let mut ms = 0u64;
    let mut len = 20;

    // Loop over the arguments.
    loop {
        let arg = if let Some(x) = args.next() {
            x
        } else {
            break;
        };

        match arg.as_str() {
            "-h" | "--help" => {
                // Print help.
                stdout.write(HELP.as_bytes()).try(&mut stderr);
                return;
            },
            "-n" | "--len" => len = args.next().fail("no number after -n.", &mut stderr).parse().try(&mut stderr),
            t => {
                // Find number input.
                let num: u64 = args.next().unwrap_or_else(|| {
                    stderr.write(b"error: incorrectly formatted number.\
                                   Please input a positive integer.").try(&mut stderr);
                    stderr.flush().try(&mut stderr);
                    exit(1);
                }).parse().try(&mut stderr);
                ms += num * match t {
                    "-m" | "--minutes" => 1000 * 60,
                    "-H" | "--hours" => 1000 * 60 * 60,
                    "-s" | "--seconds" => 1000,
                    "-M" | "--milliseconds" => 1,
                    _ => {
                        // Unknown argument.
                        stderr.write(b"error: unknown argument, ").try(&mut stderr);
                        stderr.write(t.as_bytes()).try(&mut stderr);
                        stderr.write(b".\n").try(&mut stderr);
                        stderr.flush().try(&mut stderr);
                        exit(1);
                    },

                };
            },
        }
    }

    // Hide the cursor.
    stdout.write(b"\x1b[?25l").try(&mut stderr);
    // Draw the empty progress bar.
    for _ in 0..len + 1 {
        stdout.write(b" ").try(&mut stderr);
    }
    stdout.write(b"]").try(&mut stderr);

    stdout.write(b"\r[").try(&mut stderr);

    // As time goes, update the progress bar.
    for _ in 0..len {
        stdout.write(b"#").try(&mut stderr);
        stdout.flush().try(&mut stderr);
        // Sleep.
        sleep(Duration::from_millis(ms / len));
    }

    // Show the cursor again.
    stdout.write(b"\x1b[?25h").try(&mut stderr);
    stdout.write(b"\n").try(&mut stderr);
}
<|endoftext|>


<commit_before><commit_msg>Add some simple should_parse tests<commit_after>//! This module contains some simple tests where we can write strings which we

extern crate syn;

macro_rules! should_parse {
    ($name:ident, { $($in:tt)* }) => {
        #[test]
        fn $name() {
            // Make sure we can parse the file!
            syn::parse_file(stringify!($($in)*)).unwrap();
        }
    }
}

should_parse!(generic_associated_type, {
    impl Foo {
        type Item<'a> = &'a i32;
        fn foo<'a>(&'a self) -> Self::Item<'a> {}
    }
});

should_parse!(const_generics_use, {
    type X = Foo<5>;
    type Y = Foo<"foo">;
    type Z = Foo<X>;
    type W = Foo<{ X + 10 }>;
});
<|endoftext|>


<commit_before>//! Enviroment data

use alloc::boxed::Box;

use fs::File;
use path::{Path, PathBuf};
use io::Result;
use string::{String, ToString};
use vec::Vec;

use system::error::{Error, ENOENT};
use system::syscall::sys_chdir;

static mut _args: *mut Vec<&'static str> = 0 as *mut Vec<&'static str>;

pub struct Args {
    i: usize
}

impl Iterator for Args {
    //Yes, this is supposed to be String, do not change it!
    //Only change it if https://doc.rust-lang.org/std/env/struct.Args.html changes from String
    type Item = String;
    fn next(&mut self) -> Option<String> {
        if let Some(arg) = unsafe { (*_args).get(self.i) } {
            self.i += 1;
            Some(arg.to_string())
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = if self.i <= unsafe { (*_args).len() } {
            unsafe { (*_args).len() - self.i }
        } else {
            0
        };
        (len, Some(len))
    }
}

impl ExactSizeIterator for Args {}

/// Arguments
pub fn args() -> Args {
    Args {
        i: 0
    }
}

/// Initialize arguments
pub unsafe fn args_init(args: Vec<&'static str>) {
    _args = Box::into_raw(box args);
}

/// Destroy arguments
pub unsafe fn args_destroy() {
    if _args as usize > 0 {
        drop(Box::from_raw(_args));
    }
}

/// Method to return the current directory
/// If the current directory cannot be found, None will be returned
pub fn current_dir() -> Result<PathBuf> {
    // Return the current path
    match File::open("./") {
        Ok(file) => {
            match file.path() {
                Ok(path) => Ok(path),
                Err(err) => Err(err),
            }
        }
        Err(err) => Err(err),
    }
}

/// Set the current directory
pub fn set_current_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let file_result = if path.as_ref().inner.is_empty() || path.as_ref().inner.ends_with('/') {
        File::open(&path.as_ref().inner)
    } else {
        File::open(&(path.as_ref().inner.to_string() + "/"))
    };

    match file_result {
        Ok(file) => {
            match file.path() {
                Ok(path) => {
                    if let Some(path_str) = path.to_str() {
                        let path_c = path_str.to_string() + "\0";
                        match Error::demux(unsafe { sys_chdir(path_c.as_ptr()) }) {
                            Ok(_) => Ok(()),
                            Err(err) => Err(err),
                        }
                    } else {
                        Err(Error::new(ENOENT))
                    }
                }
                Err(err) => Err(err),
            }
        }
        Err(err) => Err(err),
    }
}

// TODO: Fully implement `env::var()`
pub fn var(_key: &str) -> Result<String> {
    Ok("This is code filler".to_string())
}
<commit_msg>Method to return the path from a custom location<commit_after>//! Enviroment data

use alloc::boxed::Box;

use fs::File;
use path::{Path, PathBuf};
use io::Result;
use string::{String, ToString};
use vec::Vec;

use system::error::{Error, ENOENT};
use system::syscall::sys_chdir;

static mut _args: *mut Vec<&'static str> = 0 as *mut Vec<&'static str>;

pub struct Args {
    i: usize
}

impl Iterator for Args {
    //Yes, this is supposed to be String, do not change it!
    //Only change it if https://doc.rust-lang.org/std/env/struct.Args.html changes from String
    type Item = String;
    fn next(&mut self) -> Option<String> {
        if let Some(arg) = unsafe { (*_args).get(self.i) } {
            self.i += 1;
            Some(arg.to_string())
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = if self.i <= unsafe { (*_args).len() } {
            unsafe { (*_args).len() - self.i }
        } else {
            0
        };
        (len, Some(len))
    }
}

impl ExactSizeIterator for Args {}

/// Arguments
pub fn args() -> Args {
    Args {
        i: 0
    }
}

/// Initialize arguments
pub unsafe fn args_init(args: Vec<&'static str>) {
    _args = Box::into_raw(box args);
}

/// Destroy arguments
pub unsafe fn args_destroy() {
    if _args as usize > 0 {
        drop(Box::from_raw(_args));
    }
}

/// Private function to get the path from a custom location
/// If the custom directory cannot be found, None will be returned
fn get_path_from(location : &str) -> Result<PathBuf> {
    match File::open(dir) {
        Ok(file) => {
            match file.path() {
                Ok(path) => Ok(path),
                Err(err) => Err(err),
            }
        }
        Err(err) => Err(err),
    }
}

/// Set the current directory
pub fn set_current_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let file_result = if path.as_ref().inner.is_empty() || path.as_ref().inner.ends_with('/') {
        File::open(&path.as_ref().inner)
    } else {
        File::open(&(path.as_ref().inner.to_string() + "/"))
    };

    match file_result {
        Ok(file) => {
            match file.path() {
                Ok(path) => {
                    if let Some(path_str) = path.to_str() {
                        let path_c = path_str.to_string() + "\0";
                        match Error::demux(unsafe { sys_chdir(path_c.as_ptr()) }) {
                            Ok(_) => Ok(()),
                            Err(err) => Err(err),
                        }
                    } else {
                        Err(Error::new(ENOENT))
                    }
                }
                Err(err) => Err(err),
            }
        }
        Err(err) => Err(err),
    }
}

// TODO: Fully implement `env::var()`
pub fn var(_key: &str) -> Result<String> {
    Ok("This is code filler".to_string())
}
<|endoftext|>


<commit_before><commit_msg>Cleanup warnings.<commit_after><|endoftext|>


<commit_before><commit_msg>Add column and row mirroring.<commit_after><|endoftext|>


<commit_before><commit_msg>We have SOUND<commit_after><|endoftext|>


<commit_before><commit_msg>blank message<commit_after><|endoftext|>


<commit_before><commit_msg>Finishing up the chapter 9 with trait and impl.<commit_after><|endoftext|>


<commit_before><commit_msg>Mandelbrot benchmark.<commit_after>#![feature(test)]

extern crate simd;
extern crate test;

use test::black_box as bb;
use test::Bencher as B;
use simd::{f32x4, u32x4};

fn naive(c_x: f32, c_y: f32, max_iter: u32) -> u32 {
    let mut x = c_x;
    let mut y = c_y;
    let mut count = 0;
    while count < max_iter {
        let xy = x * y;
        let xx = x * x;
        let yy = y * y;
        let sum = xx + yy;
        if sum > 4.0 {
            break
        }
        count += 1;
        x = xx - yy + c_x;
        y = xy * 2.0 + c_y;
    }
    count
}

fn simd4(c_x: f32x4, c_y: f32x4, max_iter: u32) -> u32x4 {
    let mut x = c_x;
    let mut y = c_y;

    let mut count = u32x4::splat(0);
    for _ in 0..max_iter {
        let xy = x * y;
        let xx = x * x;
        let yy = y * y;
        let sum = xx + yy;
        let mask = sum.lt(f32x4::splat(4.0));

        if !mask.any() { break }
        count = count + mask.to_i().select(u32x4::splat(1), u32x4::splat(0));

        x = xx - yy + c_x;
        y = xy + xy + c_y;
    }
    count
}

const SCALE: f32 = 3.0 / 100.0;
const N: u32 = 100;
#[bench]
fn mandel_naive(b: &mut B) {
    b.iter(|| {
        for j in 0..100 {
            let y = -1.5 + (j as f32) * SCALE;
            for i in 0..100 {
                let x = -2.2 + (i as f32) * SCALE;
                bb(naive(x, y, N));
            }
        }
    })
}
#[bench]
fn mandel_simd4(b: &mut B) {
    let tweak = u32x4::new(0, 1, 2, 3);
    b.iter(|| {
        for j in 0..100 {
            let y = f32x4::splat(-1.5) + f32x4::splat(SCALE) * u32x4::splat(j).to_f32();
            for i in 0..25 {
                let i = u32x4::splat(i * 4) + tweak;
                let x = f32x4::splat(-2.2) + f32x4::splat(SCALE) * i.to_f32();
                bb(simd4(x, y, N));
            }
        }
    })
}
<|endoftext|>


<commit_before><commit_msg>A working pooled connection<commit_after><|endoftext|>


<commit_before><commit_msg>Basic implementation of `FloatDuration` and `GameClock`.<commit_after>use std::time;
use std::ops;

use chrono;
use chrono::{Timelike};

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct FloatDuration {
    secs: f64,
}

impl FloatDuration {
    pub fn new(secs: f64) -> FloatDuration {
        FloatDuration {secs}
    }

    pub fn days(days: f64) -> FloatDuration {
        FloatDuration {secs: days * (3600.0 * 24.0)}
    }
    pub fn hours(hours: f64) -> FloatDuration {
        FloatDuration {secs: hours * 3600.0}
    }
    pub fn minutes(mins: f64) -> FloatDuration {
        FloatDuration {secs: mins * 60.0}
    }
    pub fn seconds(secs: f64) -> FloatDuration {
        FloatDuration {secs}
    }
    pub fn milliseconds(millis: f64) -> FloatDuration {
        FloatDuration {secs: millis / 1000.0}
    }
    pub fn microseconds(micros: f64) -> FloatDuration {
        FloatDuration {secs: micros / 1.0e6}
    }
    pub fn nanoseconds(nanos: f64) -> FloatDuration {
        FloatDuration {secs: nanos / 1.0e9}
    }

    pub fn as_days(&self) -> f64 {
        self.secs / (3600.0*24.0)
    }
    pub fn as_hours(&self) -> f64 {
        self.secs / 3600.0
    }
    pub fn as_minutes(&self) -> f64 {
        self.secs / 60.0
    }
    pub fn as_seconds(&self) -> f64 {
        self.secs
    }
    pub fn as_milliseconds(&self) -> f64 {
        self.secs * 1.0e3
    }
    pub fn as_microseconds(&self) -> f64 {
        self.secs * 1.0e6
    }
    pub fn as_nanoseconds(&self) -> f64 {
        self.secs * 1.0e9
    }

    pub fn as_std(&self) -> Option<time::Duration> {
        if self.secs.is_sign_negative() {
            None
        } else {
            let seconds = self.secs.trunc();
            let nanos = self.secs.fract() * 1e9;

            Some(time::Duration::new(seconds as u64, nanos as u32))
        }
    }

    pub fn from_std(duration: time::Duration) -> FloatDuration {
        return FloatDuration::seconds(
            (duration.as_secs() as f64) * (duration.subsec_nanos() as f64)/1.0e-9);
    }
}

impl ops::Neg for FloatDuration {
    type Output = FloatDuration;

    fn neg(self) -> FloatDuration {
        FloatDuration {secs: -self.secs}
    }
}

impl ops::Add<FloatDuration> for FloatDuration {
    type Output = FloatDuration;

    fn add(self, rhs: FloatDuration) -> FloatDuration {
        FloatDuration {secs: self.secs + rhs.secs}
    }
}
impl ops::Sub<FloatDuration> for FloatDuration {
    type Output = FloatDuration;

    fn sub(self, rhs: FloatDuration) -> FloatDuration {
        FloatDuration {secs: self.secs - rhs.secs}
    }
}

impl ops::Mul<f64> for FloatDuration {
    type Output = FloatDuration;

    fn mul(self, rhs: f64) -> FloatDuration {
        FloatDuration {secs: self.secs * rhs}
    }
}
impl ops::Div<f64> for FloatDuration {
    type Output = FloatDuration;

    fn div(self, rhs: f64) -> FloatDuration {
        FloatDuration {secs: self.secs / rhs}
    }
}

impl ops::AddAssign<FloatDuration> for FloatDuration {
    fn add_assign(&mut self, rhs: FloatDuration) {
        self.secs += rhs.secs;
    }
}
impl ops::SubAssign<FloatDuration> for FloatDuration {
    fn sub_assign(&mut self, rhs: FloatDuration) {
        self.secs -= rhs.secs;
    }
}

impl ops::MulAssign<f64> for FloatDuration {
    fn mul_assign(&mut self, rhs: f64) {
        self.secs *= rhs;
    }
}
impl ops::DivAssign<f64> for FloatDuration {
    fn div_assign(&mut self, rhs: f64) {
        self.secs /= rhs;
    }
}
<|endoftext|>


<commit_before><commit_msg>Added files via upload<commit_after>//
//
use std::env;

#[cfg(unix)]
fn is_executable() {
   println!("is unix");
   }
#[cfg(windows)]
fn is_executable() {
   println!("is windows");
   }

pub fn pargs() {
    for (key,value) in env::vars_os() {
    println!("{:?}: {:?}", key, value);
    }
}

fn main() {
pargs();
is_executable();
println!("Hallo Test1");
}

#[test]
fn test1_its_really_works() {
}
<|endoftext|>


<commit_before>// FIXME: With recursive object types, we could implement binary methods like
//        union, intersection, and difference. At that point, we could write
//        an optimizing version of this module that produces a different obj
//        for the case where nbits <= 32.

// FIXME: Almost all the functions in this module should be state fns, but the
//        effect system isn't currently working correctly.
state type t = rec(vec[mutable uint] storage, uint nbits);

// FIXME: this should be a constant once they work
fn uint_bits() -> uint {
    ret 32u + ((1u << 32u) >> 27u);
}

fn create(uint nbits, bool init) -> t {
    auto elt;
    if (init) {
        elt = ~0u;
    } else {
        elt = 0u;
    }

    auto storage = vec::init_elt_mut[uint](elt, nbits / uint_bits() + 1u);
    ret rec(storage = storage, nbits = nbits);
}

fn process(&fn(uint, uint) -> uint op, &t v0, &t v1) -> bool {
    auto len = vec::len(v1.storage);

    assert (vec::len(v0.storage) == len);
    assert (v0.nbits == v1.nbits);

    auto changed = false;

    for each (uint i in uint::range(0u, len)) {
        auto w0 = v0.storage.(i);
        auto w1 = v1.storage.(i);

        auto w = op(w0, w1);
        if (w0 != w) {
            changed = true;
            v0.storage.(i) = w;
        }
    }

    ret changed;
}

fn lor(uint w0, uint w1) -> uint {
    ret w0 | w1;
}

fn union(&t v0, &t v1) -> bool {
    auto sub = lor;
    ret process(sub, v0, v1);
}

fn land(uint w0, uint w1) -> uint {
    ret w0 & w1;
}

fn intersect(&t v0, &t v1) -> bool {
    auto sub = land;
    ret process(sub, v0, v1);
}

fn right(uint w0, uint w1) -> uint {
    ret w1;
}

fn copy(&t v0, t v1) -> bool {
    auto sub = right;
    ret process(sub, v0, v1);
}

fn clone(t v) -> t {
    auto storage = vec::init_elt_mut[uint](0u, v.nbits / uint_bits() + 1u);
    auto len = vec::len(v.storage);
    for each (uint i in uint::range(0u, len)) {
        storage.(i) = v.storage.(i);
    }
    ret rec(storage = storage, nbits = v.nbits);
}

fn get(&t v, uint i) -> bool {
    assert (i < v.nbits);

    auto bits = uint_bits();

    auto w = i / bits;
    auto b = i % bits;
    auto x = 1u & (v.storage.(w) >> b);
    ret x == 1u;
}

fn equal(&t v0, &t v1) -> bool {
    // FIXME: when we can break or return from inside an iterator loop,
    //        we can eliminate this painful while-loop
    auto len = vec::len(v1.storage);
    auto i = 0u;
    while (i < len) {
        if (v0.storage.(i) != v1.storage.(i)) {
            ret false;
        }
        i = i + 1u;
    }
    ret true;
}

fn clear(&t v) {
    for each (uint i in uint::range(0u, vec::len(v.storage))) {
        v.storage.(i) = 0u;
    }
}

fn set_all(&t v) {
    for each (uint i in uint::range(0u, v.nbits)) {
        set(v, i, true);
    }
}

fn invert(&t v) {
    for each (uint i in uint::range(0u, vec::len(v.storage))) {
        v.storage.(i) = ~v.storage.(i);
    }
}

/* v0 = v0 - v1 */
fn difference(&t v0, &t v1) -> bool {
    invert(v1);
    auto b = intersect(v0, v1);
    invert(v1);
    ret b;
}

fn set(&t v, uint i, bool x) {
    assert (i < v.nbits);

    auto bits = uint_bits();

    auto w = i / bits;
    auto b = i % bits;
    auto w0 = v.storage.(w);
    auto flag = 1u << b;
    if (x) {
        v.storage.(w) = v.storage.(w) | flag;
    } else {
        v.storage.(w) = v.storage.(w) & ~flag;
    }
}

/* true if all bits are 1 */
fn is_true(&t v) -> bool {
    for (uint i in to_vec(v)) {
        if (i != 1u) {
            ret false;
        }
    }

    ret true;
}

/* true if all bits are non-1 */
fn is_false(&t v) -> bool {
    for (uint i in to_vec(v)) {
        if (i == 1u) {
            ret false;
        }
    }

    ret true;
}

fn init_to_vec(t v, uint i) -> uint {
    if (get(v, i)) {
        ret 1u;
    } else {
        ret 0u;
    }
}

fn to_vec(&t v) -> vec[uint] {
    auto sub = bind init_to_vec(v, _);
    ret vec::init_fn[uint](sub, v.nbits);
}

fn to_str(&t v) -> str {
    auto res = "";

    for (uint i in bitv::to_vec(v)) {
        if (i == 1u) {
            res += "1";
        }
        else {
            res += "0";
        }
    }

    ret res;
}

// FIXME: can we just use structural equality on to_vec?
fn eq_vec(&t v0, &vec[uint] v1) -> bool {
    assert (v0.nbits == vec::len[uint](v1));
    auto len = v0.nbits;
    auto i = 0u;
    while (i < len) {
        auto w0 = get(v0, i);
        auto w1 = v1.(i);
        if ((!w0 && w1 != 0u) || (w0 && w1 == 0u)) {
            ret false;
        }
        i = i + 1u;
    }
    ret true;
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<commit_msg>stdlib: Export only what's needed from std::bitv<commit_after>export t;
export create;
export union;
export intersect;
export copy;
export clone;
export get;
export equal;
export clear;
export set_all;
export invert;
export difference;
export set;
export is_true;
export is_false;
export to_vec;
export to_str;
export eq_vec;

// FIXME: With recursive object types, we could implement binary methods like
//        union, intersection, and difference. At that point, we could write
//        an optimizing version of this module that produces a different obj
//        for the case where nbits <= 32.

// FIXME: Almost all the functions in this module should be state fns, but the
//        effect system isn't currently working correctly.
state type t = rec(vec[mutable uint] storage, uint nbits);

// FIXME: this should be a constant once they work
fn uint_bits() -> uint {
    ret 32u + ((1u << 32u) >> 27u);
}

fn create(uint nbits, bool init) -> t {
    auto elt;
    if (init) {
        elt = ~0u;
    } else {
        elt = 0u;
    }

    auto storage = vec::init_elt_mut[uint](elt, nbits / uint_bits() + 1u);
    ret rec(storage = storage, nbits = nbits);
}

fn process(&fn(uint, uint) -> uint op, &t v0, &t v1) -> bool {
    auto len = vec::len(v1.storage);

    assert (vec::len(v0.storage) == len);
    assert (v0.nbits == v1.nbits);

    auto changed = false;

    for each (uint i in uint::range(0u, len)) {
        auto w0 = v0.storage.(i);
        auto w1 = v1.storage.(i);

        auto w = op(w0, w1);
        if (w0 != w) {
            changed = true;
            v0.storage.(i) = w;
        }
    }

    ret changed;
}

fn lor(uint w0, uint w1) -> uint {
    ret w0 | w1;
}

fn union(&t v0, &t v1) -> bool {
    auto sub = lor;
    ret process(sub, v0, v1);
}

fn land(uint w0, uint w1) -> uint {
    ret w0 & w1;
}

fn intersect(&t v0, &t v1) -> bool {
    auto sub = land;
    ret process(sub, v0, v1);
}

fn right(uint w0, uint w1) -> uint {
    ret w1;
}

fn copy(&t v0, t v1) -> bool {
    auto sub = right;
    ret process(sub, v0, v1);
}

fn clone(t v) -> t {
    auto storage = vec::init_elt_mut[uint](0u, v.nbits / uint_bits() + 1u);
    auto len = vec::len(v.storage);
    for each (uint i in uint::range(0u, len)) {
        storage.(i) = v.storage.(i);
    }
    ret rec(storage = storage, nbits = v.nbits);
}

fn get(&t v, uint i) -> bool {
    assert (i < v.nbits);

    auto bits = uint_bits();

    auto w = i / bits;
    auto b = i % bits;
    auto x = 1u & (v.storage.(w) >> b);
    ret x == 1u;
}

fn equal(&t v0, &t v1) -> bool {
    // FIXME: when we can break or return from inside an iterator loop,
    //        we can eliminate this painful while-loop
    auto len = vec::len(v1.storage);
    auto i = 0u;
    while (i < len) {
        if (v0.storage.(i) != v1.storage.(i)) {
            ret false;
        }
        i = i + 1u;
    }
    ret true;
}

fn clear(&t v) {
    for each (uint i in uint::range(0u, vec::len(v.storage))) {
        v.storage.(i) = 0u;
    }
}

fn set_all(&t v) {
    for each (uint i in uint::range(0u, v.nbits)) {
        set(v, i, true);
    }
}

fn invert(&t v) {
    for each (uint i in uint::range(0u, vec::len(v.storage))) {
        v.storage.(i) = ~v.storage.(i);
    }
}

/* v0 = v0 - v1 */
fn difference(&t v0, &t v1) -> bool {
    invert(v1);
    auto b = intersect(v0, v1);
    invert(v1);
    ret b;
}

fn set(&t v, uint i, bool x) {
    assert (i < v.nbits);

    auto bits = uint_bits();

    auto w = i / bits;
    auto b = i % bits;
    auto w0 = v.storage.(w);
    auto flag = 1u << b;
    if (x) {
        v.storage.(w) = v.storage.(w) | flag;
    } else {
        v.storage.(w) = v.storage.(w) & ~flag;
    }
}

/* true if all bits are 1 */
fn is_true(&t v) -> bool {
    for (uint i in to_vec(v)) {
        if (i != 1u) {
            ret false;
        }
    }

    ret true;
}

/* true if all bits are non-1 */
fn is_false(&t v) -> bool {
    for (uint i in to_vec(v)) {
        if (i == 1u) {
            ret false;
        }
    }

    ret true;
}

fn init_to_vec(t v, uint i) -> uint {
    if (get(v, i)) {
        ret 1u;
    } else {
        ret 0u;
    }
}

fn to_vec(&t v) -> vec[uint] {
    auto sub = bind init_to_vec(v, _);
    ret vec::init_fn[uint](sub, v.nbits);
}

fn to_str(&t v) -> str {
    auto res = "";

    for (uint i in bitv::to_vec(v)) {
        if (i == 1u) {
            res += "1";
        }
        else {
            res += "0";
        }
    }

    ret res;
}

// FIXME: can we just use structural equality on to_vec?
fn eq_vec(&t v0, &vec[uint] v1) -> bool {
    assert (v0.nbits == vec::len[uint](v1));
    auto len = v0.nbits;
    auto i = 0u;
    while (i < len) {
        auto w0 = get(v0, i);
        auto w1 = v1.(i);
        if ((!w0 && w1 != 0u) || (w0 && w1 == 0u)) {
            ret false;
        }
        i = i + 1u;
    }
    ret true;
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<|endoftext|>


<commit_before><commit_msg>Fix GT/LT/GTEQ/LTEQ handling to not compare bools<commit_after><|endoftext|>


<commit_before>extern crate ncurses;
use ncurses::*;

pub fn draw(buf:&Vec<u8>, cursorpos:usize, cols:usize, mode:usize, command:&String, cursorstate:usize, screenoffset:usize) {
    erase();

    let screenheight : usize = getmaxy(stdscr) as usize;

    let mut rows = buf.len() / cols;
    if rows >= screenheight-1 { // Last line reserved for Status/Commands/etc (Like in vim)
        rows = screenheight-2;
    }

    for z in 0 .. rows+1 {
        printw(&format!("{:08X}: ", get_line(cols, screenoffset, z))); // 8 hex digits (4GB/cols or 0.25GB@cols=SPALTEN)
        printw(" "); // Additional space between line number and hex
        for s in 0 .. cols {
            let pos:usize = get_pos(cols, screenoffset, z, s);
            if pos < buf.len() {

                color_left_nibble_cond(true, pos==cursorpos, cursorstate);
                printw(&format!("{:01X}", buf[pos]>>4) );
                color_left_nibble_cond(false, pos==cursorpos, cursorstate);

                color_right_nibble_cond(true, pos==cursorpos, cursorstate);
                printw(&format!("{:01X}", buf[pos]&0x0F) );
                color_right_nibble_cond(false, pos==cursorpos, cursorstate);

                printw(" ");
            } else
            if pos == buf.len() {

                color_left_nibble_cond(true, pos==cursorpos, cursorstate);
                printw("-");
                color_left_nibble_cond(false, pos==cursorpos, cursorstate);

                color_right_nibble_cond(true, pos==cursorpos, cursorstate);
                printw("-");
                color_right_nibble_cond(false, pos==cursorpos, cursorstate);

                printw(" ");
            } else {
                printw("-- ");
            }
        }
        printw(" "); // Additional space between hex and ascii
        for s in 0 .. cols {
            let pos:usize = get_pos(cols, screenoffset, z, s);
            color_ascii_cond(true, pos==cursorpos, cursorstate);
            if pos < buf.len() {
                if let c @ 32...126 = buf[pos] {
                    if c as char == '%' {
                        printw("%%"); // '%' needs to be escaped by a '%' in ncurses
                    } else {
                        printw(&format!("{}", c as char) );
                    }
                }
                else {printw(&format!(".") );}
            }
            color_ascii_cond(false, pos==cursorpos, cursorstate);
        }
        printw("\n");
    }
    for _ in 0 .. screenheight-rows-2 { // TODO: check if "rows" is better
        printw("\n"); // Put the cursor on last line of terminal
    }
    if mode == 2 {
        printw(":"); // Indicate that a command can be typed in
    }
    if mode == 3 {
        printw("insert"); // Indicate that insert mode is active
    }
    if mode == 4 {
        printw("/"); // indicate that the search mode is active
    }
    printw(&format!("{}", command));
}

fn get_line(cols:usize, screenoffset:usize, z:usize) -> usize {
    return z*cols+screenoffset*cols;
}
fn get_pos(cols:usize, screenoffset:usize, z:usize, s:usize) -> usize {
    return z*cols+screenoffset*cols+s;
}

fn color_left_nibble(color:bool, cursorstate:usize) {
    if color {
        if cursorstate == 0 {attron(COLOR_PAIR(1) | A_STANDOUT());}
        else if cursorstate == 2 {attron(A_UNDERLINE());}
    } else {
        if cursorstate == 0 {attroff(COLOR_PAIR(1) | A_STANDOUT());}
        else if cursorstate == 2 {attroff(A_UNDERLINE());}
    }
}
fn color_left_nibble_cond(color:bool, condition:bool, cursorstate:usize) {
    if condition { color_left_nibble(color, cursorstate); }
}

fn color_right_nibble(color:bool, cursorstate:usize) {
    if color {
        if cursorstate == 1 {attron(COLOR_PAIR(1) | A_STANDOUT());}
        else if cursorstate == 2 {attron(A_UNDERLINE());}
    } else {
        if cursorstate == 1 {attroff(COLOR_PAIR(1) | A_STANDOUT());}
        else if cursorstate == 2 {attroff(A_UNDERLINE());}
    }
}
fn color_right_nibble_cond(color:bool, condition:bool, cursorstate:usize) {
    if condition { color_right_nibble(color, cursorstate); }
}

fn color_ascii(color:bool, cursorstate:usize) {
    if color {
        if cursorstate == 2 {attron(COLOR_PAIR(1) | A_STANDOUT());}
        else {attron(A_UNDERLINE());}
    } else {
        if cursorstate == 2 {attroff(COLOR_PAIR(1) | A_STANDOUT());}
        else {attroff(A_UNDERLINE());}
    }
}
fn color_ascii_cond(color:bool, condition:bool, cursorstate:usize) {
    if condition { color_ascii(color, cursorstate); }
}
<commit_msg>Pad ascii with spaces<commit_after>extern crate ncurses;
use ncurses::*;

pub fn draw(buf:&Vec<u8>, cursorpos:usize, cols:usize, mode:usize, command:&String, cursorstate:usize, screenoffset:usize) {
    erase();

    let screenheight : usize = getmaxy(stdscr) as usize;

    let mut rows = buf.len() / cols;
    if rows >= screenheight-1 { // Last line reserved for Status/Commands/etc (Like in vim)
        rows = screenheight-2;
    }

    for z in 0 .. rows+1 {
        printw(&format!("{:08X}: ", get_line(cols, screenoffset, z))); // 8 hex digits (4GB/cols or 0.25GB@cols=SPALTEN)
        printw(" "); // Additional space between line number and hex
        for s in 0 .. cols {
            let pos:usize = get_pos(cols, screenoffset, z, s);
            if pos < buf.len() {

                color_left_nibble_cond(true, pos==cursorpos, cursorstate);
                printw(&format!("{:01X}", buf[pos]>>4) );
                color_left_nibble_cond(false, pos==cursorpos, cursorstate);

                color_right_nibble_cond(true, pos==cursorpos, cursorstate);
                printw(&format!("{:01X}", buf[pos]&0x0F) );
                color_right_nibble_cond(false, pos==cursorpos, cursorstate);

                printw(" ");
            } else
            if pos == buf.len() {

                color_left_nibble_cond(true, pos==cursorpos, cursorstate);
                printw("-");
                color_left_nibble_cond(false, pos==cursorpos, cursorstate);

                color_right_nibble_cond(true, pos==cursorpos, cursorstate);
                printw("-");
                color_right_nibble_cond(false, pos==cursorpos, cursorstate);

                printw(" ");
            } else {
                printw("-- ");
            }
        }
        printw(" "); // Additional space between hex and ascii
        for s in 0 .. cols {
            let pos:usize = get_pos(cols, screenoffset, z, s);
            color_ascii_cond(true, pos==cursorpos, cursorstate);
            if pos < buf.len() {
                if let c @ 32...126 = buf[pos] {
                    if c as char == '%' {
                        printw("%%"); // '%' needs to be escaped by a '%' in ncurses
                    } else {
                        printw(&format!("{}", c as char) );
                    }
                }
                else {printw(&format!(".") );} // Mark non-ascii symbols
            } else
            if pos == buf.len() {
                printw(" "); // Pad ascii with spaces
            }

            color_ascii_cond(false, pos==cursorpos, cursorstate);
        }
        printw("\n");
    }
    for _ in 0 .. screenheight-rows-2 { // TODO: check if "rows" is better
        printw("\n"); // Put the cursor on last line of terminal
    }
    if mode == 2 {
        printw(":"); // Indicate that a command can be typed in
    }
    if mode == 3 {
        printw("insert"); // Indicate that insert mode is active
    }
    if mode == 4 {
        printw("/"); // indicate that the search mode is active
    }
    printw(&format!("{}", command));
}

fn get_line(cols:usize, screenoffset:usize, z:usize) -> usize {
    return z*cols+screenoffset*cols;
}
fn get_pos(cols:usize, screenoffset:usize, z:usize, s:usize) -> usize {
    return z*cols+screenoffset*cols+s;
}

fn color_left_nibble(color:bool, cursorstate:usize) {
    if color {
        if cursorstate == 0 {attron(COLOR_PAIR(1) | A_STANDOUT());}
        else if cursorstate == 2 {attron(A_UNDERLINE());}
    } else {
        if cursorstate == 0 {attroff(COLOR_PAIR(1) | A_STANDOUT());}
        else if cursorstate == 2 {attroff(A_UNDERLINE());}
    }
}
fn color_left_nibble_cond(color:bool, condition:bool, cursorstate:usize) {
    if condition { color_left_nibble(color, cursorstate); }
}

fn color_right_nibble(color:bool, cursorstate:usize) {
    if color {
        if cursorstate == 1 {attron(COLOR_PAIR(1) | A_STANDOUT());}
        else if cursorstate == 2 {attron(A_UNDERLINE());}
    } else {
        if cursorstate == 1 {attroff(COLOR_PAIR(1) | A_STANDOUT());}
        else if cursorstate == 2 {attroff(A_UNDERLINE());}
    }
}
fn color_right_nibble_cond(color:bool, condition:bool, cursorstate:usize) {
    if condition { color_right_nibble(color, cursorstate); }
}

fn color_ascii(color:bool, cursorstate:usize) {
    if color {
        if cursorstate == 2 {attron(COLOR_PAIR(1) | A_STANDOUT());}
        else {attron(A_UNDERLINE());}
    } else {
        if cursorstate == 2 {attroff(COLOR_PAIR(1) | A_STANDOUT());}
        else {attroff(A_UNDERLINE());}
    }
}
fn color_ascii_cond(color:bool, condition:bool, cursorstate:usize) {
    if condition { color_ascii(color, cursorstate); }
}
<|endoftext|>


<commit_before><commit_msg>fix stupid bug<commit_after><|endoftext|>


<commit_before><commit_msg>easage-list: Add a '--verbose' flag to cut down on noise<commit_after><|endoftext|>


<commit_before><commit_msg>Moving libstd's read() & write() to here<commit_after><|endoftext|>


<commit_before>use piston_window::*;
use piston_window::types::Color;

use board::Board;
use randomizer::Randomizer;
use tetromino::*;
use settings::*;
use stats::*;

enum GameState {
    Playing,
    Paused
}

pub trait Game {
    fn on_input(&mut self, input: Input);
    fn on_update(&mut self, update_args: UpdateArgs);
    fn render(&mut self, context: Context, graphics: &mut G2d);
}

pub trait Renderer {
    fn render(&self, context: Context, graphics: &mut G2d);
}

pub trait GridRenderer {
    fn render(&self, x: i32, y: i32, context: Context, graphics: &mut G2d);
}

pub struct Rustris {
    board: Board,
    randomizer: Randomizer,
    current_piece: Piece,
    next_piece: Piece,
    stats: GameStats,
    time_since_moved: f64,
    time_per_tick: f64
    // state: GameState
}
impl Rustris {
    pub fn new() -> Rustris {
        let mut randomizer = Randomizer::new();
        let current_piece = randomizer.create_piece();
        let next_piece = randomizer.create_piece();
        Rustris {
            board: Board::new(),
            randomizer: randomizer,
            current_piece: current_piece,
            next_piece: next_piece,
            stats: GameStats::new(),
            time_since_moved: 0.0,
            time_per_tick: 1.0  //For testing
        }
    }

    pub fn reset(&mut self) {

    }

    pub fn get_game_stats(&self) -> &GameStats {
        &self.stats
    }

    pub fn set_current_piece(&mut self, piece: Piece) {
        // TODO: Add tests for this
        if self.is_valid_board_position(&piece) {
            self.current_piece = piece;
        }
    }

    fn is_valid_board_position(&self, piece: &Piece) -> bool {
        // TODO: Add tests for this
        piece.blocks_iter().all(|block| {
            (block.x >= 0 && block.x < WIDTH_IN_BLOCKS &&
             block.y >= 0 && block.y < HEIGHT_IN_BLOCKS &&
             !self.board.is_space_occupied(block))
        })
    }

    fn should_lock(&self, piece: &Piece) -> bool {
        // TODO: Add tests for this
        piece.blocks_iter().any(|block| {
            block.y >= HEIGHT_IN_BLOCKS ||
            self.board.is_space_occupied(block)
        })
    }

    fn lock_current_piece(&mut self) {
        self.board.set_piece(&self.current_piece);
    }

    fn remove_completed_lines(&mut self) {
        let number_removed = self.board.remove_completed_rows();
        self.stats.score_completed_lines(number_removed);
    }

    fn get_new_piece(&mut self) {
        let next = self.next_piece;
        self.set_current_piece(next);
        self.next_piece = self.randomizer.create_piece();
    }

    fn update(&mut self) {
        let moved = self.current_piece.moved(Direction::Down);
        if self.should_lock(&moved) {
            self.lock_current_piece();
            self.remove_completed_lines();
            self.get_new_piece();
        } else {
            self.set_current_piece(moved);
        }
    }
}
impl Game for Rustris {
    fn on_input(&mut self, input: Input) {
        match input {
            Input::Press(key) => {
                match key {
                    Button::Keyboard(Key::Up) => {
                        let rotated = self.current_piece.rotated();
                        self.set_current_piece(rotated);
                    }
                    Button::Keyboard(Key::Down) => {
                        let moved = self.current_piece.moved(Direction::Down);
                        self.set_current_piece(moved);
                        self.time_since_moved = 0.0;
                        self.stats.score_soft_drop();
                    }
                    Button::Keyboard(Key::Left) => {
                        let moved = self.current_piece.moved(Direction::Left);
                        self.set_current_piece(moved);
                    }
                    Button::Keyboard(Key::Right) => {
                        let moved = self.current_piece.moved(Direction::Right);
                        self.set_current_piece(moved);
                    }
                    Button::Keyboard(Key::Space) => {
                        // TODO: Implement hard drop code
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }

    fn on_update(&mut self, update_args: UpdateArgs) {
        self.time_since_moved += update_args.dt;
        // TODO: The threshold needs to be able to be updated
        // as the game progresses
        if self.time_since_moved >= self.time_per_tick {
            self.time_since_moved -= self.time_per_tick;
            self.update();
        }
    }

    fn render(&mut self, context: Context, graphics: &mut G2d) {
        self.board.render(context, graphics);
        self.current_piece.render(context, graphics);
    }
}

// TODO: Move this into its own module
pub fn render_square_in_grid(x: i32, y: i32, color: Color, context: Context, graphics: &mut G2d) {
    let square = rectangle::square(
        0.0, 0.0, BLOCK_SIZE - (2.0 * GRID_LINE_WIDTH)
    );
    let transform = context.transform
        // Translate the origin of the transform based on where the grid starts
        .trans(GRID_X_OFFSET, GRID_Y_OFFSET)
        // Translate the square into the first grid cell (off of the bounding box)
        .trans(GRID_LINE_WIDTH, GRID_LINE_WIDTH)
        // Translate the square into the proper grid cell based on the grid x and y position
        .trans((x as f64)*BLOCK_SIZE, (y as f64)*BLOCK_SIZE);
    rectangle(color, square, transform, graphics);
}
<commit_msg>fix a bug where the player could keep accumulating points by holding the down key<commit_after>use piston_window::*;
use piston_window::types::Color;

use board::Board;
use randomizer::Randomizer;
use tetromino::*;
use settings::*;
use stats::*;

enum GameState {
    Playing,
    Paused
}

pub trait Game {
    fn on_input(&mut self, input: Input);
    fn on_update(&mut self, update_args: UpdateArgs);
    fn render(&mut self, context: Context, graphics: &mut G2d);
}

pub trait Renderer {
    fn render(&self, context: Context, graphics: &mut G2d);
}

pub trait GridRenderer {
    fn render(&self, x: i32, y: i32, context: Context, graphics: &mut G2d);
}

pub struct Rustris {
    board: Board,
    randomizer: Randomizer,
    current_piece: Piece,
    next_piece: Piece,
    stats: GameStats,
    time_since_moved: f64,
    time_per_tick: f64
    // state: GameState
}
impl Rustris {
    pub fn new() -> Rustris {
        let mut randomizer = Randomizer::new();
        let current_piece = randomizer.create_piece();
        let next_piece = randomizer.create_piece();
        Rustris {
            board: Board::new(),
            randomizer: randomizer,
            current_piece: current_piece,
            next_piece: next_piece,
            stats: GameStats::new(),
            time_since_moved: 0.0,
            time_per_tick: 1.0  //For testing
        }
    }

    pub fn reset(&mut self) {

    }

    pub fn get_game_stats(&self) -> &GameStats {
        &self.stats
    }

    pub fn set_current_piece(&mut self, piece: Piece) {
        self.current_piece = piece;
    }

    fn is_valid_board_position(&self, piece: &Piece) -> bool {
        // TODO: Add tests for this
        piece.blocks_iter().all(|block| {
            (block.x >= 0 && block.x < WIDTH_IN_BLOCKS &&
             block.y >= 0 && block.y < HEIGHT_IN_BLOCKS &&
             !self.board.is_space_occupied(block))
        })
    }

    fn should_lock(&self, piece: &Piece) -> bool {
        // TODO: Add tests for this
        piece.blocks_iter().any(|block| {
            block.y >= HEIGHT_IN_BLOCKS ||
            self.board.is_space_occupied(block)
        })
    }

    fn lock_current_piece(&mut self) {
        self.board.set_piece(&self.current_piece);
    }

    fn remove_completed_lines(&mut self) {
        let number_removed = self.board.remove_completed_rows();
        self.stats.score_completed_lines(number_removed);
    }

    fn get_new_piece(&mut self) {
        let next = self.next_piece;
        self.set_current_piece(next);
        self.next_piece = self.randomizer.create_piece();
    }

    fn update(&mut self) {
        let moved = self.current_piece.moved(Direction::Down);
        if self.should_lock(&moved) {
            self.lock_current_piece();
            self.remove_completed_lines();
            self.get_new_piece();
        } else {
            self.set_current_piece(moved);
        }
    }
}
impl Game for Rustris {
    fn on_input(&mut self, input: Input) {
        let mut moved: Option<Piece> = None;
        match input {
            Input::Press(key) => {
                match key {
                    Button::Keyboard(Key::Up) => {
                        moved = Some(self.current_piece.rotated());
                    }
                    Button::Keyboard(Key::Down) => {
                        let move_down = self.current_piece.moved(Direction::Down);
                        if self.is_valid_board_position(&move_down) {
                            self.time_since_moved = 0.0;
                            self.stats.score_soft_drop();
                            self.set_current_piece(move_down);
                        }
                    }
                    Button::Keyboard(Key::Left) => {
                        moved = Some(self.current_piece.moved(Direction::Left));
                    }
                    Button::Keyboard(Key::Right) => {
                        moved = Some(self.current_piece.moved(Direction::Right));
                    }
                    Button::Keyboard(Key::Space) => {
                        // TODO: Implement hard drop code
                    }
                    _ => {}
                }
            }
            _ => {}
        }
        if let Some(piece) = moved {
            if self.is_valid_board_position(&piece) {
                self.set_current_piece(piece);
            }
        }
    }

    fn on_update(&mut self, update_args: UpdateArgs) {
        self.time_since_moved += update_args.dt;
        // TODO: The threshold needs to be able to be updated
        // as the game progresses
        if self.time_since_moved >= self.time_per_tick {
            self.time_since_moved -= self.time_per_tick;
            self.update();
        }
    }

    fn render(&mut self, context: Context, graphics: &mut G2d) {
        self.board.render(context, graphics);
        self.current_piece.render(context, graphics);
    }
}

// TODO: Move this into its own module
pub fn render_square_in_grid(x: i32, y: i32, color: Color, context: Context, graphics: &mut G2d) {
    let square = rectangle::square(
        0.0, 0.0, BLOCK_SIZE - (2.0 * GRID_LINE_WIDTH)
    );
    let transform = context.transform
        // Translate the origin of the transform based on where the grid starts
        .trans(GRID_X_OFFSET, GRID_Y_OFFSET)
        // Translate the square into the first grid cell (off of the bounding box)
        .trans(GRID_LINE_WIDTH, GRID_LINE_WIDTH)
        // Translate the square into the proper grid cell based on the grid x and y position
        .trans((x as f64)*BLOCK_SIZE, (y as f64)*BLOCK_SIZE);
    rectangle(color, square, transform, graphics);
}
<|endoftext|>


<commit_before>use rand::{thread_rng, Rng};

#[derive(Clone, Debug)]
pub enum Color {
    Red,
    Yellow,
    Blue,
    Green,
}

impl Color {
    fn rand() -> Color {
        let mut rng = thread_rng();

        rng.choose(&[
            Color::Red,
            Color::Yellow,
            Color::Blue,
            Color::Green,
        ]).unwrap().clone()
    }

    pub fn as_rgba(&self) -> [f32; 4] {
        match *self {
            Color::Red => [0.8, 0.0, 0.0, 1.0],
            Color::Yellow => [1.0, 1.0, 0.5, 1.0],
            Color::Blue => [0.0, 0.5, 1.0, 1.0],
            Color::Green => [0.0, 0.5, 0.0, 1.0],
        }
    }
}

#[derive(Clone, Debug)]
pub struct Piece {
    col: usize,
    row: usize,
    color: Color,
}

impl Piece {
    pub fn new() -> Piece {
        let color = Color::rand();

         Piece {col: 0, row: 0, color: color}
    }

    pub fn row(&self) -> usize {
        self.row
    }

    pub fn col(&self) -> usize {
        self.col
    }

    pub fn color_rgba(&self) -> [f32; 4]{
        self.color.as_rgba()
    }
}

pub struct Game {
    current_piece: Piece,
    height: usize,
    width: usize,
    pieces: Vec<Vec<Option<Piece>>>,
}

impl Game {
    pub fn new(height: usize, width: usize) -> Game {
        Game {
            current_piece: Piece::new(),
            height: height,
            width: width,
            pieces: vec![vec![None; width]; height],
        }
    }

    fn is_current_piece_blocked(&self) -> bool {
        let col = self.current_piece.col;
        let row = self.current_piece.row + 1;

        if row >= self.height {
            return true
        }

        self.pieces.get(row).unwrap().get(col).unwrap().is_some()
    }

    pub fn step(&mut self) {
        if self.is_current_piece_blocked() {
            if let Some(col) = self.pieces.get_mut(self.current_piece.row) {
                col[self.current_piece.col] = Some(self.current_piece.clone());
            } else {
                panic!()
            }

            self.current_piece = Piece::new();
        } else {
            self.current_piece.row += 1;
        }
    }

    pub fn move_left(&mut self) {
        if self.current_piece.col > 0 {
            self.current_piece.col -= 1;
        }
    }

    pub fn move_right(&mut self) {
        if self.current_piece.col < self.width - 1 {
            self.current_piece.col += 1;
        }
    }

    pub fn get_pieces(&self) -> Vec<Piece> {
        self.pieces.iter()
            .flat_map(|col| col.iter().flat_map(|piece| piece.clone()))
            .chain(vec![self.current_piece.clone()])
            .collect()
    }

    pub fn current_piece_col(&self) -> usize {
        self.current_piece.col
    }

    pub fn current_piece_row(&self) -> usize {
        self.current_piece.row
    }
}
<commit_msg>clear 4 of a color in a row<commit_after>use rand::{thread_rng, Rng};

#[derive(Clone, Debug, PartialEq)]
pub enum Color {
    Red,
    Yellow,
    Blue,
    Green,
}

impl Color {
    fn rand() -> Color {
        let mut rng = thread_rng();

        rng.choose(&[
            Color::Red,
            Color::Yellow,
            Color::Blue,
            Color::Green,
        ]).unwrap().clone()
    }

    pub fn as_rgba(&self) -> [f32; 4] {
        match *self {
            Color::Red => [0.8, 0.0, 0.0, 1.0],
            Color::Yellow => [1.0, 1.0, 0.5, 1.0],
            Color::Blue => [0.0, 0.5, 1.0, 1.0],
            Color::Green => [0.0, 0.5, 0.0, 1.0],
        }
    }
}

#[derive(Clone, Debug)]
pub struct Piece {
    col: usize,
    row: usize,
    color: Color,
}

impl Piece {
    pub fn new() -> Piece {
        let color = Color::rand();

         Piece {col: 0, row: 0, color: color}
    }

    pub fn row(&self) -> usize {
        self.row
    }

    pub fn col(&self) -> usize {
        self.col
    }

    pub fn color_rgba(&self) -> [f32; 4]{
        self.color.as_rgba()
    }
}

pub struct Game {
    current_piece: Piece,
    height: usize,
    width: usize,
    pieces: Vec<Vec<Option<Piece>>>,
}

impl Game {
    pub fn new(height: usize, width: usize) -> Game {
        Game {
            current_piece: Piece::new(),
            height: height,
            width: width,
            pieces: vec![vec![None; width]; height],
        }
    }

    fn is_current_piece_blocked(&self) -> bool {
        let col = self.current_piece.col;
        let row = self.current_piece.row + 1;

        if row >= self.height {
            return true
        }

        self.pieces.get(row).unwrap().get(col).unwrap().is_some()
    }

    fn remove_cleared_rows(&mut self) {
        let mut in_sequence = 0;

        for col in 0..4 {
            let piece = self.pieces.get(self.current_piece.row).unwrap().get(col).unwrap();

            if let Some(ref p) = *piece {
                if p.color == self.current_piece.color {
                    in_sequence += 1
                } else {
                    in_sequence = 0
                }
            }
        }

        if in_sequence < 4 {
            return
        }

        self.pieces.remove(self.current_piece.row);
        self.pieces.insert(0, vec![None; self.width]);

        self.refresh_piece_rows_and_cols();
    }

    fn refresh_piece_rows_and_cols(&mut self) {
        self.pieces = self.pieces.iter().enumerate()
            .map(|(row_index, col)| {
                col.iter().enumerate().map(|(col_index, piece)| {
                    if let Some(ref p) = *piece {
                        Some(Piece {
                            row: row_index,
                            col: col_index,
                            color: p.color.clone(),
                        })
                    } else {
                        None
                    }
                }).collect()
            }).collect();
    }

    pub fn step(&mut self) {
        if self.is_current_piece_blocked() {
            if let Some(col) = self.pieces.get_mut(self.current_piece.row) {
                col[self.current_piece.col] = Some(self.current_piece.clone());
            } else {
                panic!()
            }

            self.remove_cleared_rows();
            self.current_piece = Piece::new();
        } else {
            self.current_piece.row += 1;
        }
    }

    pub fn move_left(&mut self) {
        if self.current_piece.col > 0 {
            self.current_piece.col -= 1;
        }
    }

    pub fn move_right(&mut self) {
        if self.current_piece.col < self.width - 1 {
            self.current_piece.col += 1;
        }
    }

    pub fn get_pieces(&self) -> Vec<Piece> {
        self.pieces.iter()
            .flat_map(|col| col.iter().flat_map(|piece| piece.clone()))
            .chain(vec![self.current_piece.clone()])
            .collect()
    }

    pub fn current_piece_col(&self) -> usize {
        self.current_piece.col
    }

    pub fn current_piece_row(&self) -> usize {
        self.current_piece.row
    }
}
<|endoftext|>


<commit_before><commit_msg>add get_3 which gets a 3 sided square area<commit_after><|endoftext|>


<commit_before><commit_msg>identifiers<commit_after>//! Assign unique identifiers to records.

use timely::dataflow::Scope;

use ::{Collection, Data, Hashable};
use ::lattice::Lattice;
use ::operators::*;
use difference::Diff;

/// Assign unique identifiers to elements of a collection.
pub trait Identifiers<G: Scope, D: Data, R: Diff> {
    /// Assign unique identifiers to elements of a collection.
    ///
    /// # Example
    /// ```
    /// extern crate timely;
    /// extern crate differential_dataflow;
    ///
    /// use differential_dataflow::input::Input;
    /// use differential_dataflow::algorithms::identifiers::Identifiers;
    /// use differential_dataflow::operators::Threshold;
    ///
    /// fn main() {
    ///     ::timely::example(|scope| {
    ///
    ///         let identifiers =
    ///         scope.new_collection_from(1 .. 10).1
    ///              .identifiers()
    ///              // assert no conflicts
    ///              .map(|(data, id)| id)
    ///              .threshold(|_id,cnt| if cnt > 1 { 1 } else { 0 })
    ///              .assert_empty();
    ///     });
    /// }
    /// ```
    fn identifiers(&self) -> Collection<G, (D, u64), R>;
}

impl<G, D, R> Identifiers<G, D, R> for Collection<G, D, R>
where
    G: Scope,
    G::Timestamp: Lattice,
    D: Data+::std::hash::Hash,
    R: Diff,
{
    fn identifiers(&self) -> Collection<G, (D, u64), R> {

        // The design here is that we iteratively develop a collection
        // of pairs (round, record), where each pair is a proposal that
        // the hash for record should be (round, record).hashed().
        //
        // Iteratively, any colliding pairs establish a winner (the one
        // with the lower round, breaking ties by record), and indicate
        // that the losers should increment their round and try again.
        //
        // Non-obviously, this happens via a `group` operator that yields
        // additions and subtractions of losers, rather than reproducing
        // the winners. This is done under the premise that losers are
        // very rare, and maintaining winners in both the input and output
        // of `group` is an unneccesary duplication.

        use collection::AsCollection;

        let init = self.map(|record| (0, record));
        timely::dataflow::operators::generic::operator::empty(&init.scope())
            .as_collection()
            .iterate(|diff|
                init.enter(&diff.scope())
                    .concat(&diff)
                    .map(|pair| (pair.hashed(), pair))
                    .group(|_hash, input, output| {
                        // keep round-positive records as changes.
                        let ((round, record), count) = &input[0];
                        if *round > 0 {
                            output.push(((0, record.clone()), -*count));
                            output.push(((*round, record.clone()), *count));
                        }
                        // if any losers, increment their rounds.
                        for ((round, record), count) in input[1..].iter() {
                            output.push(((0, record.clone()), -*count));
                            output.push(((*round+1, record.clone()), *count));
                        }
                    })
                    .map(|(_hash, pair)| pair)
            )
            .concat(&init)
            .map(|pair| { let hash = pair.hashed(); (pair.1, hash) })
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn are_unique() {

        // It is hard to test the above method, because we would want
        // to exercise the case with hash collisions. Instead, we test
        // a version with a crippled hash function to see that even if
        // there are collisions, everyone gets a unique identifier.

        use ::input::Input;
        use ::operators::{Consolidate, Threshold, Group};
        use ::operators::iterate::Iterate;

        ::timely::example(|scope| {

            let input = scope.new_collection_from(1 .. 10).1;

            use collection::AsCollection;

            let init = input.map(|record| (0, record));
            timely::dataflow::operators::generic::operator::empty(&init.scope())
                .as_collection()
                .iterate(|diff|
                    init.enter(&diff.scope())
                        .concat(&diff)
                        .map(|(round, num)| ((round + num) / 10, (round, num)))
                        .group(|_hash, input, output| {
                            // keep round-positive records as changes.
                            let ((round, record), count) = &input[0];
                            if *round > 0 {
                                output.push(((0, record.clone()), -*count));
                                output.push(((*round, record.clone()), *count));
                            }
                            // if any losers, increment their rounds.
                            for ((round, record), count) in input[1..].iter() {
                                output.push(((0, record.clone()), -*count));
                                output.push(((*round+1, record.clone()), *count));
                            }
                        })
                        .map(|(_hash, pair)| pair)
                )
                .concat(&init)
                .map(|(round, num)| { (num, (round + num) / 10) })
                .map(|(_data, id)| id)
                .threshold(|_id,cnt| if cnt > 1 { 1 } else { 0 })
                .assert_empty();
        });
    }
}<|endoftext|>


<commit_before><commit_msg>Added file with action definitions<commit_after>use ecs::*;
use game::*;
use direction::Direction;

pub fn walk(action: &mut EcsAction, entity: EntityRef, direction: Direction) -> Result<()> {
    let current_position = entity.position().ok_or(Error::MissingComponent)?;
    let new_position = current_position + direction.vector();
    action.insert_position(entity.id(), new_position);
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Add guards for the result of vkGetInstanceProcAddr (against being None) and change order of destruction<commit_after><|endoftext|>


<commit_before><commit_msg>Fix the depth buffer clearing on Vulkan<commit_after><|endoftext|>