<commit_before><commit_msg>add CloudWatch Events integration tests<commit_after>#![cfg(feature = "events")]

extern crate rusoto;

use rusoto::events::{CloudWatchEventsClient, ListRulesRequest};
use rusoto::{DefaultCredentialsProvider, Region};

#[test]
fn should_list_rules() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = CloudWatchEventsClient::new(credentials, Region::UsEast1);

    let request = ListRulesRequest::default();

    match client.list_rules(&request) {
        Ok(response) => {
            println!("{:#?}", response);
            assert!(true)
        },
        Err(err) => panic!("Expected OK response, got {:#?}", err)
    };
}
<|endoftext|>


<commit_before><commit_msg>add a bunch of tests for the parser, some of which fail because of bugs, some of which are tricky and the result of ambiguity/not enough types of brackets on my keyboard<commit_after>#[macro_use(run_test)]
extern crate interpreter;

#[test]
fn unclosed_paren() {
    run_test!(
        should_fail(parse)
        => r"
            x = (5 + (5);
        ");
}

#[test]
fn missing_assignment_semicolon() {
    run_test!(
        should_fail(parse)
        => r"
            x = 5
        ");
}

#[test]
fn bad_item() {
    run_test!(
        should_fail(parse)
        => r"
            a;
        ");
    run_test!(
        should_fail(parse)
        => r"
            5 = a;
        ");
}

#[test]
fn empty_assignment_expr() {
    run_test!(
        should_fail(parse)
        => r"
            a = ;
        ");
}

#[test]
fn extra_closing_paren() {
    run_test!(
        should_fail(parse)
        => r"
            a = (5+5));
        ");
}

#[test]
fn unary_operator_used_as_binary() {
    run_test!(
        should_fail(parse)
        => r"
            a = true ! false;
        ");
}

#[test]
fn binary_operator_used_as_unary() {
    run_test!(
        should_fail(parse)
        => r"
            a = 5 + * 5;
        ");
    run_test!(
        should_fail(parse)
        => r"
            a = 5 + 5 -;
        ");
    run_test!(
        should_fail(parse)
        => r"
            a = + 5 + 5;
        ");
}

#[test]
fn closure_missing_block() {
    run_test!(
        should_fail(parse)
        => r"
            a = \x,y,z;
        ");
}

#[test]
fn block_not_closed() {
    run_test!(
        should_fail(parse)
        => r"
            a = \x,y,z { x; { y; z; }
        ");
    run_test!(
        should_fail(parse)
        => r"
            a = { 5 + 5;
        ");
}

#[test]
fn extra_semicolon() {
    run_test!(
        should_fail(parse)
        => r"
            a = 5;;
        ");
    run_test!(
        should_fail(parse)
        => r"
            a = {
                5;
                ;
            };
        ");
}

#[test]
fn empty_program() {
    run_test!(
        should_pass(parse)
        => "");
}

#[test]
fn empty_argument() {
    run_test!(
        should_fail(parse)
        => r"
            a = fn(5,);
        ");
}

#[test]
fn wrong_bracket_type() {
    run_test!(
        should_fail(parse)
        => r"
            a = fn(5];
        ");
    run_test!(
        should_fail(parse)
        => r"
            a = fn{5);
        ");
}

#[test]
fn bad_argument() {
    run_test!(
        should_fail(parse)
        => r"
            a = fn(5=a);
        ");
    run_test!(
        should_fail(parse)
        => r"
            b = fn(=5);
        ");
    run_test!(
        should_fail(parse)
        => r"
            c = fn(x=);
        ");
    run_test!(
        should_fail(parse)
        => r"
            d = fn(=);
        ");
}

#[test]
fn closure_in_default_arg() {
    run_test!(
        should_pass(parse)
        => r"
            fn y=\x{x<5} { }
        ");
    run_test!(
        should_pass(parse)
        => r"
            fn z=\x=\{5},y=\{6}{x()<y()} { z() }
        ");
}

#[test]
fn closure_in_arg() {
    run_test!(
        should_pass(parse)
        => r"
            a = fn(3, cond=\{x>5});
        ");
}

#[test]
fn block_in_default_arg() {
    run_test!(
        should_pass(parse) // hopefully this will be supported at some point for completeness
                           // but right now implementing it is a major pain
        => r"
            fn y=99-{1+2+3+4+5} { }
        ");
}

#[test]
fn block_in_arg() {
    run_test!(
        should_pass(parse)
        => r"
            a = fn(y={1+2+3+4+5});
        ");
}

#[test]
fn partial_application_in_arg() {
    run_test!(
        should_pass(parse)
        => r"
            a = fn(y=fx{5});
            a = fn{y=fx{5}};
        ");
}

#[test]
fn partial_application_in_default_arg() {
    run_test!(
        should_pass(parse)
        => r"
            fn x=y{5} { x() }
        ");
}

#[test]
fn closure_with_semicolon() {
    run_test!(
        should_pass(parse)
        => r"
            a = \x, y { x; y; };
        ");
    run_test!(
        should_pass(parse)
        => r"
            a = \x=\c{c;}, y { x; y; };
        ");
}

#[test]
fn call_types() {
    run_test!(
        should_pass(parse)
        => r"
            a = fn(1, 2);
            b = fn(x=1, 2);
            c = fn(2, x=1);
            e = fn(y=1, x=2);
            f = fn[1, 2];
            g = fn[x=1, 2];
            h = fn[2, x=1];
            i = fn[y=1, x=2];
            j = fn{1, 2};
            k = fn{x=1, 2};
            l = fn{2, x=1};
            m = fn{y=1, x=2};
        ");
}

#[test]
fn everything_at_once() {
    run_test!(
        should_pass(parse)
        => r"
            z = \x{x*x*x};
            fn a, b=z{5}, c=true, d=\e,f=1,g=\i=\j{2*j}{i();}{e;f*g()} {
                x = a + {
                    b if c else d(c);
                    d{e=a}(f=2);
                    d{b}[3];
                    d{b}{g=\x{x^2}};
                };
            }
            a = fn({5;4;3;2;1;});
        ");
}
<|endoftext|>


<commit_before>extern crate rsedis;

use std;

use rsedis::database::Database;
use rsedis::database::Value;
use rsedis::util::mstime;

#[test]
fn set_get() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = vec![1u8, 2, 3, 4];
    let expected = Vec::clone(&value);
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    match database.get(0, &key) {
        Some(val) => {
            match val {
                &Value::Data(ref bytes) => assert_eq!(*bytes, expected),
                _ => assert!(false),
            }
        }
        _ => assert!(false),
    }
}

#[test]
fn get_empty() {
    let database = Database::new();
    let key = vec![1u8];
    match database.get(0, &key) {
        None => {},
        _ => assert!(false),
    }
}

#[test]
fn set_set_get() {
    let mut database = Database::new();
    let key = vec![1u8];
    assert!(database.get_or_create(0, &key).set(vec![0u8, 0, 0]).is_ok());
    let value = vec![1u8, 2, 3, 4];
    let expected = Vec::clone(&value);
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    match database.get(0, &key) {
        Some(val) => {
            match val {
                &Value::Data(ref bytes) => assert_eq!(*bytes, expected),
                _ => assert!(false),
            }
        }
        _ => assert!(false),
    }
}

#[test]
fn append_append_get() {
    let mut database = Database::new();
    let key = vec![1u8];
    assert_eq!(database.get_or_create(0, &key).append(vec![0u8, 0, 0]).unwrap(), 3);
    assert_eq!(database.get_or_create(0, &key).append(vec![1u8, 2, 3, 4]).unwrap(), 7);
    match database.get(0, &key) {
        Some(val) => {
            match val {
                &Value::Data(ref bytes) => assert_eq!(*bytes, vec![0u8, 0, 0, 1, 2, 3, 4]),
                _ => assert!(false),
            }
        }
        _ => assert!(false),
    }
}

#[test]
fn set_number() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = b"123".to_vec();
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    match database.get(0, &key) {
        Some(val) => {
            match val {
                &Value::Integer(ref num) => assert_eq!(*num, 123i64),
                _ => assert!(false),
            }
        }
        _ => assert!(false),
    }
}

#[test]
fn append_number() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = b"123".to_vec();
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    assert_eq!(database.get_or_create(0, &key).append(b"asd".to_vec()).unwrap(), 6);
    match database.get(0, &key) {
        Some(val) => {
            match val {
                &Value::Data(ref bytes) => assert_eq!(*bytes, b"123asd".to_vec()),
                _ => assert!(false),
            }
        }
        _ => assert!(false),
    }
}

#[test]
fn remove_value() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = vec![1u8, 2, 3, 4];
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    match database.remove(0, &key) {
        Some(_) => {},
        _ => assert!(false),
    }
    match database.remove(0, &key) {
        Some(_) => assert!(false),
        _ => {},
    }
}

#[test]
fn incr_str() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = b"123".to_vec();
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    assert_eq!(database.get_or_create(0, &key).incr(1).unwrap(), 124);
    match database.get(0, &key) {
        Some(val) => {
            match val {
                &Value::Integer(i) => assert_eq!(i, 124),
                _ => assert!(false),
            }
        }
        _ => assert!(false),
    }
}

#[test]
fn incr_create_update() {
    let mut database = Database::new();
    let key = vec![1u8];
    assert_eq!(database.get_or_create(0, &key).incr(124).unwrap(), 124);
    match database.get(0, &key) {
        Some(val) => {
            match val {
                &Value::Integer(i) => assert_eq!(i, 124),
                _ => assert!(false),
            }
        }
        _ => assert!(false),
    }
    assert_eq!(database.get_or_create(0, &key).incr(1).unwrap(), 125);
    match database.get(0, &key) {
        Some(val) => {
            match val {
                &Value::Integer(i) => assert_eq!(i, 125),
                _ => assert!(false),
            }
        }
        _ => assert!(false),
    }
}

#[test]
fn incr_overflow() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = format!("{}", std::i64::MAX).into_bytes();
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    assert!(database.get_or_create(0, &key).incr(1).is_err());
}

#[test]
fn set_expire_get() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = vec![1u8, 2, 3, 4];
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    database.set_msexpiration(0, key.clone(), mstime());
    assert_eq!(database.get(0, &key), None);
}

#[test]
fn set_will_expire_get() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = vec![1u8, 2, 3, 4];
    let expected = Vec::clone(&value);
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    database.set_msexpiration(0, key.clone(), mstime() + 10000);
    assert_eq!(database.get(0, &key), Some(&Value::Data(expected)));
}
<commit_msg>Simplify test assertions<commit_after>extern crate rsedis;

use std;

use rsedis::database::Database;
use rsedis::database::Value;
use rsedis::util::mstime;

#[test]
fn set_get() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = vec![1u8, 2, 3, 4];
    let expected = Vec::clone(&value);
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    assert_eq!(database.get(0, &key).unwrap(), &Value::Data(expected));
}

#[test]
fn get_empty() {
    let database = Database::new();
    let key = vec![1u8];
    assert!(database.get(0, &key).is_none());
}

#[test]
fn set_set_get() {
    let mut database = Database::new();
    let key = vec![1u8];
    assert!(database.get_or_create(0, &key).set(vec![0u8, 0, 0]).is_ok());
    let value = vec![1u8, 2, 3, 4];
    let expected = Vec::clone(&value);
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    assert_eq!(database.get(0, &key).unwrap(), &Value::Data(expected));
}

#[test]
fn append_append_get() {
    let mut database = Database::new();
    let key = vec![1u8];
    assert_eq!(database.get_or_create(0, &key).append(vec![0u8, 0, 0]).unwrap(), 3);
    assert_eq!(database.get_or_create(0, &key).append(vec![1u8, 2, 3, 4]).unwrap(), 7);
    assert_eq!(database.get(0, &key).unwrap(), &Value::Data(vec![0u8, 0, 0, 1, 2, 3, 4]));
}

#[test]
fn set_number() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = b"123".to_vec();
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    assert_eq!(database.get(0, &key).unwrap(), &Value::Integer(123));
}

#[test]
fn append_number() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = b"123".to_vec();
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    assert_eq!(database.get_or_create(0, &key).append(b"asd".to_vec()).unwrap(), 6);
    assert_eq!(database.get(0, &key).unwrap(), &Value::Data(b"123asd".to_vec()));
}

#[test]
fn remove_value() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = vec![1u8, 2, 3, 4];
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    database.remove(0, &key).unwrap();
    assert!(database.remove(0, &key).is_none());
}

#[test]
fn incr_str() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = b"123".to_vec();
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    assert_eq!(database.get_or_create(0, &key).incr(1).unwrap(), 124);
    assert_eq!(database.get(0, &key).unwrap(), &Value::Integer(124));
}

#[test]
fn incr_create_update() {
    let mut database = Database::new();
    let key = vec![1u8];
    assert_eq!(database.get_or_create(0, &key).incr(124).unwrap(), 124);
    assert_eq!(database.get(0, &key).unwrap(), &Value::Integer(124));
    assert_eq!(database.get_or_create(0, &key).incr(1).unwrap(), 125);
    assert_eq!(database.get(0, &key).unwrap(), &Value::Integer(125));
}

#[test]
fn incr_overflow() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = format!("{}", std::i64::MAX).into_bytes();
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    assert!(database.get_or_create(0, &key).incr(1).is_err());
}

#[test]
fn set_expire_get() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = vec![1u8, 2, 3, 4];
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    database.set_msexpiration(0, key.clone(), mstime());
    assert_eq!(database.get(0, &key), None);
}

#[test]
fn set_will_expire_get() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = vec![1u8, 2, 3, 4];
    let expected = Vec::clone(&value);
    assert!(database.get_or_create(0, &key).set(value).is_ok());
    database.set_msexpiration(0, key.clone(), mstime() + 10000);
    assert_eq!(database.get(0, &key), Some(&Value::Data(expected)));
}
<|endoftext|>


<commit_before><commit_msg>add test that was failing from tedh<commit_after>fn main() {
    // sometimes we have had trouble finding
    // the right type for f, as we unified
    // bot and u32 here
    let f = alt uint::from_str("1234") {
        none { ret () }
        some(num) { num as u32 }
    };
    assert f == 1234u32;
    log(error, f)
}
<|endoftext|>


<commit_before><commit_msg>Don't return the number of bytes send, from send_file*<commit_after><|endoftext|>


<commit_before><commit_msg>refactor(tmux/mod): Don't compare length<commit_after><|endoftext|>


<commit_before><commit_msg>Added nickel.rs example<commit_after>#[macro_use]
extern crate nickel;
extern crate multipart;

use std::fs::File;
use std::io::Read;
use multipart::server::{Entries, Multipart, SaveResult};
use nickel::{HttpRouter, MiddlewareResult, Nickel, Request, Response};

fn handle_multipart<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> {
    match Multipart::from_request(req) {
        Ok(mut multipart) => {
            match multipart.save_all() {
                SaveResult::Full(entries) => process_entries(res, entries),

                SaveResult::Partial(entries, e) => {
                    println!("Partial errors ... {:?}", e);
                    return process_entries(res, entries);
                },

                SaveResult::Error(e) => {
                    println!("There are errors in multipart POSTing ... {:?}", e);
                    res.set(nickel::status::StatusCode::InternalServerError);
                    return res.send(format!("Server could not handle multipart POST! {:?}", e));
                },
            }
        }
        Err(_) => {
            res.set(nickel::status::StatusCode::BadRequest);
            return res.send("Request seems not was a multipart request")
        }
    }
}

/// Processes saved entries from multipart request.
/// Returns an OK response or an error.
fn process_entries<'mw>(res: Response<'mw>, entries: Entries) -> MiddlewareResult<'mw> {
    for (name, field) in entries.fields {
        println!(r#"Field "{}": "{}""#, name, field);
    }

    for (name, savedfile) in entries.files {
        let filename = match savedfile.filename {
            Some(s) => s,
            None => "None".into(),
        };

        match File::open(savedfile.path) {
            Ok(mut file) => {
                let mut contents = String::new();
                match file.read_to_string(&mut contents) {
                    Ok(sz) => println!("File: \"{}\" is of size: {}b.", filename, sz),
                    Err(e) => println!("Could not read file's \"{}\" size. Error: {:?}", filename, e),
                }
                println!(r#"Field "{}" is file "{}":"#, name, filename);
                println!("{}", contents);
                file
            }
            Err(e) => {
                println!("Could open file \"{}\". Error: {:?}", filename, e);
                return res.error(nickel::status::StatusCode::BadRequest, "The uploaded file was not readable")
            }
        };
    }

    res.send("Ok")
}

fn main() {
    let mut srv = Nickel::new();

    srv.post("/multipart_upload/", handle_multipart);

    srv.listen("127.0.0.1:6868");
}
<|endoftext|>


<commit_before><commit_msg>add examples/thread<commit_after>extern crate egg_mode;

mod common;

use std::collections::{VecDeque, HashSet};
use egg_mode::tweet;

fn main() {
    let c = common::Config::load();

    //Thread Reconstruction
    //
    //This is fairly imperfect, but still effective enough for use in a regular client or with
    //recent-enough tweets. The idea is that we have an arbitrary tweet and we want to find tweets
    //that it replied to, and tweets the user posted that reply to it.
    //
    //The first part is fairly easy: it's essentially a linked list, where each node traversal is a
    //call to tweet::show. Since we're receiving these tweets in reverse-chronological order,
    //calling push_front makes sure the order of the eventual thread is properly chronological.
    //
    //The latter part calls for some creative use of tweet::user_timeline. First we set up the
    //timeline itself, indicating that replies should be included in the response. Then, rather
    //than calling start() to get the most recent, we use call() directly, saying "give me tweets
    //posted since this ID". Since this could include tweets that aren't on the same thread, we
    //need to make keep track of the tweet IDs in the thread, so we can make sure the tweet itself
    //is a reply to something within the thread. Since the timeline returned by this call is in
    //reverse-chronologocal order, we rev() the output page to make sure we're pushing tweets in
    //chronological order. If we wanted to fill our thread buffer completely, we could keep calling
    //newer() for a certain number of pages or until we've hit our cap, but using the default 20 is
    //sufficient for this demo.

    //The example post used in this demo is the fourth post in a seven-post thread I
    //(@QuietMisdreavus) posted shortly before writing this. You can easily extrapolate this into a
    //function that takes i64 as needed.
    let start_id: i64 = 773236818921873409;

    println!("Let's reconstruct a tweet thread!");

    let mut thread = VecDeque::with_capacity(21);
    let mut thread_ids = HashSet::new();

    let start_tweet = tweet::show(start_id, &c.con_token, &c.access_token).unwrap();
    let thread_user = start_tweet.response.user.id;
    thread_ids.insert(start_tweet.response.id);
    thread.push_front(start_tweet.response);

    for _ in 0..10 {
        if let Some(id) = thread.front().and_then(|t| t.in_reply_to_status_id) {
            let parent = tweet::show(id, &c.con_token, &c.access_token).unwrap();
            thread_ids.insert(parent.response.id);
            thread.push_front(parent.response);
        }
        else {
            break;
        }
    }

    let replies = tweet::user_timeline(thread_user, true, false, &c.con_token, &c.access_token);

    for tweet in replies.call(Some(start_id), None).unwrap().into_iter().rev() {
        if let Some(reply_id) = tweet.response.in_reply_to_status_id {
            if thread_ids.contains(&reply_id) {
                thread_ids.insert(tweet.response.id);
                thread.push_back(tweet.response);
            }
        }

        if thread.len() == thread.capacity() {
            break;
        }
    }

    for tweet in &thread {
        println!("");
        if tweet.id == start_id {
            println!("-- this is our starting tweet");
        }
        common::print_tweet(&tweet);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add header affine tests<commit_after>#[cfg(feature = "nalgebra_affine")] extern crate nalgebra;
#[cfg(feature = "nalgebra_affine")] extern crate nifti;

#[cfg(feature = "nalgebra_affine")]
mod nalgebra_affine {
    use nalgebra::Vector4;
    use nifti::{affine::Affine4, NiftiHeader};

        #[test]
    fn affine() {
        let mut header = NiftiHeader::default();
        let affine = Affine4::from_diagonal(&Vector4::new(2.0, 2.0, 2.0, 1.0));
        header.set_affine(&affine);
        assert_eq!(affine, header.affine());
        assert_eq!(header.sform_code, 2);
        assert_eq!(header.qform_code, 0);
    }

    #[test]
    fn sform() {
        let mut header = NiftiHeader::default();
        header.sform_code = 1;
        header.qform_code = 0;
        header.srow_x = [2.4, -0.0008, -0.0411765, -114.766396];
        header.srow_y = [0.1, 2.4995277, 0.0485984, -97.420204];
        header.srow_z = [0.4, -0.0485, 2.4991884, -89.12282];

        assert_eq!(header.affine(), Affine4::new(
            2.4, -0.0008,    -0.0411765, -114.766396,
            0.1,  2.4995277,  0.0485984,  -97.420204,
            0.4, -0.0485,     2.4991884,  -89.12282,
            0.0, 0.0, 0.0, 1.0
        ));
    }

    #[test]
    fn qform() {
        let mut header = NiftiHeader::default();
        header.sform_code = 0;
        header.qform_code = 1;
        header.pixdim = [-1.0, 0.9375, 0.9375, 3.0, 0.0, 0.0, 0.0, 0.0];
        header.quatern_b = 0.0;
        header.quatern_c = 1.0;
        header.quatern_d = 0.0;
        header.quatern_x = 59.557503;
        header.quatern_y = 73.172;
        header.quatern_z = 43.4291;

        assert_eq!(header.affine(), Affine4::new(
            -0.9375, 0.0,    0.0, 59.557503,
            0.0,     0.9375, 0.0, 73.172,
            0.0,     0.0,    3.0, 43.4291,
            0.0,     0.0,    0.0, 1.0
        ));
    }

    #[test]
    fn both_valid() {
        let mut header = NiftiHeader::default();
        header.sform_code = 1;
        header.srow_x = [2.4, 0.0, 0.0, -114.766396];
        header.srow_y = [0.1, 2.4, 0.0, -97.420204];
        header.srow_z = [0.4, 0.4, 2.4, -89.12282];

        // All this should be ignored
        header.qform_code = 1;
        header.pixdim = [-1.0, 0.9375, 0.9375, 3.0, 0.0, 0.0, 0.0, 0.0];
        header.quatern_b = 0.0;
        header.quatern_c = 1.0;
        header.quatern_d = 0.0;
        header.quatern_x = 59.0;
        header.quatern_y = 73.0;
        header.quatern_z = 43.0;

        assert_eq!(header.affine(), Affine4::new(
            2.4, 0.0, 0.0, -114.766396,
            0.1, 2.4, 0.0, -97.420204,
            0.4, 0.4, 2.4, -89.12282,
            0.0, 0.0, 0.0, 1.0
        ));
    }

    #[test]
    fn none_valid() {
        let mut header = NiftiHeader::default();
        header.dim = [3, 100, 100, 100, 0, 0, 0, 0];
        header.pixdim = [-1.0, 0.9, 0.9, 3.0, 0.0, 0.0, 0.0, 0.0];

        // All this should be ignored, because only `shape_zoom_affine` will be called.
        header.sform_code = 0;
        header.srow_x = [1.0, 0.0, 0.0, 1.0];
        header.srow_y = [0.0, 1.0, 0.0, 1.0];
        header.srow_z = [0.0, 0.0, 1.0, 1.0];
        header.qform_code = 0;
        header.quatern_b = 0.0;
        header.quatern_c = 1.0;
        header.quatern_d = 0.0;
        header.quatern_x = 59.0;
        header.quatern_y = 73.0;
        header.quatern_z = 43.0;

        assert_eq!(header.affine(), Affine4::new(
            -0.9, 0.0, 0.0,   44.55,
            0.0,  0.9, 0.0,  -44.55,
            0.0,  0.0, 3.0, -148.5,
            0.0, 0.0, 0.0, 1.0
        ));
    }
}
<|endoftext|>


<commit_before><commit_msg>Add a test case for helpful errors when copying into closures (#2942)<commit_after>fn closure1(+x: ~str) -> (~str, fn@() -> ~str) {
    let f = fn@() -> ~str {
        copy x
        //~^ WARNING implicitly copying a non-implicitly-copyable value
        //~^^ NOTE to copy values into a @fn closure, use a capture clause
    };
    (x,f)
}

fn closure2(+x: util::NonCopyable) -> (util::NonCopyable,
                                       fn@() -> util::NonCopyable) {
    let f = fn@() -> util::NonCopyable {
        copy x
        //~^ ERROR copying a noncopyable value
        //~^^ NOTE non-copyable value cannot be copied into a @fn closure
        //~^^^ ERROR copying a noncopyable value
    };
    (x,f)
}
fn closure3(+x: util::NonCopyable) {
    do task::spawn {
        let s = copy x;
        //~^ ERROR copying a noncopyable value
        //~^^ NOTE non-copyable value cannot be copied into a ~fn closure
        //~^^^ ERROR copying a noncopyable value
        error!("%?", s);
    }
    error!("%?", x);
}
fn main() {
    let x = ~"hello";
    do task::spawn {
        let s = copy x;
        //~^ WARNING implicitly copying a non-implicitly-copyable value
        //~^^ NOTE to copy values into a ~fn closure, use a capture clause
        error!("%s from child", s);
    }
    error!("%s", x);
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #5242 - matthiaskrgr:5238_test, r=flip1995<commit_after>// Regression test for #5238 / https://github.com/rust-lang/rust/pull/69562

#![feature(generators, generator_trait)]

fn main() {
    let _ = || {
        yield;
    };
}
<|endoftext|>


<commit_before><commit_msg>Add touch example, Fixes #21<commit_after>#[macro_use]
extern crate wlroots;

use wlroots::{Compositor, CompositorBuilder, InputManagerHandler, Keyboard, KeyboardHandler,
              Output, OutputBuilder, OutputBuilderResult, OutputHandler, OutputLayout,
              OutputManagerHandler, PointerHandler, Texture, TextureFormat, Touch, TouchHandler};
use wlroots::key_events::KeyEvent;
use wlroots::touch_events::{DownEvent, MotionEvent, UpEvent};
use wlroots::utils::{init_logging, L_DEBUG};
use wlroots::xkbcommon::xkb::keysyms::KEY_Escape;

const CAT_STRIDE: i32 = 128;
const CAT_WIDTH: i32 = 128;
const CAT_HEIGHT: i32 = 128;
const CAT_DATA: &'static [u8] = include_bytes!("cat.data");

#[derive(Debug, Clone)]
struct TouchPoint {
    touch_id: i32,
    x: f64,
    y: f64
}

struct State {
    cat_texture: Option<Texture>,
    touch_points: Vec<TouchPoint>
}

impl State {
    fn new() -> Self {
        State { cat_texture: None,
                touch_points: Vec::new() }
    }
}

compositor_data!(State);

struct TouchHandlerEx;

struct OutputManager;

struct ExOutput;

struct InputManager;

struct ExPointer;

struct ExKeyboardHandler;

impl OutputManagerHandler for OutputManager {
    fn output_added<'output>(&mut self,
                             compositor: &mut Compositor,
                             builder: OutputBuilder<'output>)
                             -> Option<OutputBuilderResult<'output>> {
        Some(builder.build_best_mode(ExOutput))
    }
}

impl KeyboardHandler for ExKeyboardHandler {
    fn on_key(&mut self, compositor: &mut Compositor, _: &mut Keyboard, key_event: &mut KeyEvent) {
        for key in key_event.pressed_keys() {
            if key == KEY_Escape {
                compositor.terminate()
            }
        }
    }
}

impl PointerHandler for ExPointer {}

impl OutputHandler for ExOutput {
    fn on_frame(&mut self, compositor: &mut Compositor, output: &mut Output) {
        let renderer = compositor.renderer.as_mut().unwrap();
        let state: &mut State = (&mut compositor.data).downcast_mut().unwrap();
        // NOTE gl functions will probably always be unsafe.
        let (width, height) = output.effective_resolution();
        let transform_matrix = output.transform_matrix();
        let mut renderer = renderer.render(output);
        renderer.clear([0.25, 0.25, 0.25, 1.0]);
        let cat_texture = state.cat_texture.as_mut().unwrap();
        let (cat_width, cat_height) = cat_texture.size();
        for touch_point in &mut state.touch_points {
            let matrix =
                cat_texture.get_matrix(&transform_matrix,
                                       (touch_point.x * width as f64) as i32 - (cat_width / 2),
                                       (touch_point.y * height as f64) as i32 - (cat_height / 2));
            renderer.render_with_matrix(cat_texture, &matrix);
        }
    }
}

impl TouchHandler for TouchHandlerEx {
    fn on_down(&mut self, compositor: &mut Compositor, touch: &mut Touch, event: &DownEvent) {
        let state: &mut State = compositor.into();
        let (width, height) = event.size();
        let (x, y) = event.location();
        let point = TouchPoint { touch_id: event.touch_id(),
                                 x: x / width,
                                 y: y / height };
        wlr_log!(L_ERROR, "New touch point at {:?}", point);
        state.touch_points.push(point)
    }

    fn on_up(&mut self, compositor: &mut Compositor, touch: &mut Touch, event: &UpEvent) {
        let state: &mut State = compositor.into();
        wlr_log!(L_ERROR,
                 "Removing {:?} from {:#?}",
                 event.touch_id(),
                 state.touch_points);
        if let Some(index) = state.touch_points
                                  .iter()
                                  .position(|touch_point| touch_point.touch_id == event.touch_id())
        {
            state.touch_points.remove(index);
        }
    }

    fn on_motion(&mut self, compositor: &mut Compositor, touch: &mut Touch, event: &MotionEvent) {
        let state: &mut State = compositor.into();
        let (width, height) = event.size();
        let (x, y) = event.location();
        wlr_log!(L_ERROR, "New location: {:?}", (x, y));
        for touch_point in &mut state.touch_points {
            if touch_point.touch_id == event.touch_id() {
                touch_point.x = x / width;
                touch_point.y = y / height;
            }
        }
    }
}

impl InputManagerHandler for InputManager {
    fn touch_added(&mut self, _: &mut Compositor, _: &mut Touch) -> Option<Box<TouchHandler>> {
        Some(Box::new(TouchHandlerEx))
    }
    fn keyboard_added(&mut self,
                      _: &mut Compositor,
                      _: &mut Keyboard)
                      -> Option<Box<KeyboardHandler>> {
        Some(Box::new(ExKeyboardHandler))
    }
}

fn main() {
    init_logging(L_DEBUG, None);
    let mut layout = OutputLayout::new().expect("Could not construct an output layout");
    let mut compositor = CompositorBuilder::new().gles2(true)
                                                 .build_auto(State::new(),
                                                             Some(Box::new(InputManager)),
                                                             Some(Box::new(OutputManager)),
                                                             None);
    {
        let gles2 = &mut compositor.renderer.as_mut().unwrap();
        let compositor_data: &mut State = (&mut compositor.data).downcast_mut().unwrap();
        compositor_data.cat_texture = gles2.create_texture().map(|mut cat_texture| {
            cat_texture.upload_pixels(TextureFormat::ABGR8888,
                                      CAT_STRIDE,
                                      CAT_WIDTH,
                                      CAT_HEIGHT,
                                      CAT_DATA);
            cat_texture
        });
    }
    compositor.run();
}
<|endoftext|>


<commit_before><commit_msg>added exercise 4.17<commit_after>extern crate libc;

use std::ffi::CString;
use std::io;

static FILE_MODE:libc::mode_t =
	libc::S_IRUSR + libc::S_IWUSR +
	libc::S_IRGRP + libc::S_IWGRP +
	libc::S_IROTH + libc::S_IWOTH;

fn main() {
	let fd1 = CString::new("/dev/fd/1").unwrap().as_ptr();
	let fd = unsafe {
		if libc::unlink(fd1) < 0 {
			println!("{}", io::Error::last_os_error());
		}
		libc::creat(fd1, FILE_MODE)
	};
	if fd < 0 {
		println!("{}", io::Error::last_os_error());
	}
	println!("{}", fd);
}

// # Solution:

// on OS X: 'Permission denied' when unlinking /dev/fd/1
//           creating /dev/fd/1 results in a new fd with value 3<|endoftext|>


<commit_before><commit_msg>025: solve in rust (too slow!)<commit_after>// Copyright (C) 2014 Jorge Aparicio

extern mod extra;

use extra::bigint::BigUint;
use extra::bigint::ToBigUint;
use std::num::One;
use std::num::Zero;
use std::util::replace;

fn main() {
    println!("{}", fibonacci().enumerate().skip_while(|&(_, ref n)| number_of_digits(n.clone()) < 1000).next().unwrap().n0() + 1);
}

fn number_of_digits(mut n: BigUint) -> uint {
    let mut nod = 0;

    while !n.is_zero() {
        nod += 1;
        n = n / 10u.to_biguint().unwrap();
    }

    nod
}

struct Fibonacci { curr: BigUint, next: BigUint }

fn fibonacci() -> Fibonacci {
    Fibonacci { curr: One::one(), next: One::one() }
}

impl Iterator<BigUint> for Fibonacci {
    fn next(&mut self) -> Option<BigUint> {
        let new_next = self.curr + self.next;
        let new_curr = replace(&mut self.next, new_next);
        Some(replace(&mut self.curr, new_curr))
    }
}

<|endoftext|>


<commit_before><commit_msg>Normalize cuboid orientations in collision detection<commit_after><|endoftext|>


<commit_before><commit_msg>Add and xfail test for 2101<commit_after>// xfail-test
use std;
import std::arena;
import std::arena::arena;

enum hold { s(str) }

fn init(ar: &a.arena::arena, str: str) -> &a.hold {
    new(*ar) s(str)
}

fn main(args: [str]) {
    let ar = arena::arena();
    let leak = init(&ar, args[0]);
    alt *leak {
        s(astr) {
            io::println(#fmt("%?", astr));
        }
    };
}
<|endoftext|>


<commit_before><commit_msg>Create a detrend binary<commit_after>extern crate simple_csv;

use std::env;
use std::fs::File;
use std::io::BufReader;
use std::str::FromStr;
use simple_csv::{SimpleCsvWriter, SimpleCsvReader};

fn main(){
    let args : Vec<String> = env::args().collect();
    let alpha = f64::from_str(&args[1]).expect("first argument should be the threshold");

    let f = File::open("assets/filter.csv").unwrap();
    let buf = BufReader::new(f);
    let reader = SimpleCsvReader::new(buf);

    let raw: Vec<(f64, f64)> = reader
        .map (|r| r.unwrap())
        .map(data)
        .collect();

    let mut result: Vec<(f64, f64, f64)> = vec!();
    let mut smoothed: Option<(f64, f64)> = None;
    for candidate in raw {
        match smoothed {
            Some(previous) => {
                let next = alpha * candidate.1 + (1f64 - alpha) * previous.1;
                result.push((candidate.0, next, candidate.1 - next));
                smoothed = Some((candidate.0, next));
            }

            None => {
                smoothed = Some(candidate)
            }
        }
    }

    let o = File::create("assets/detrend.csv").unwrap();
    let mut writer = SimpleCsvWriter::new(o);

    for (time, trend, difference) in result {
        writer.write(
            &vec!(time.to_string(), trend.to_string(), difference.to_string())
        ).unwrap();
    }
}

fn data(row: Vec<String>) -> (f64, f64) {
    let iter = row.iter();

    let raw: Vec<f64> = iter
        .map(|s| f64::from_str(s).unwrap())
        .collect();

    (raw[0], raw[1])
}
<|endoftext|>


<commit_before><commit_msg>single-threaded<commit_after>extern crate graph_map;

use graph_map::GraphMMap;

fn main() {

    let filename = std::env::args().nth(1).expect("Must supply filename");
    let rootnode = std::env::args().nth(2).expect("Must supply root node").parse().expect("Invalid root node");

    let graph = GraphMMap::new(&filename);

    let timer = ::std::time::Instant::now();
    breadth_first(&graph, rootnode);
    println!("{:?}\tbreadth_first", timer.elapsed());

    let timer = ::std::time::Instant::now();
    breadth_first_hash(&graph, rootnode);
    println!("{:?}\tbreadth_first_hash", timer.elapsed());

    let timer = ::std::time::Instant::now();
    union_find(&graph);
    println!("{:?}\tunion_find", timer.elapsed());

    let timer = ::std::time::Instant::now();
    union_find_hash(&graph);
    println!("{:?}\tunion_find_hash", timer.elapsed());

}

fn breadth_first(graph: &GraphMMap, root: u32) {

    let nodes = graph.nodes() as u32;

    let mut reached = vec![false; nodes as usize];
    let mut buff1 = Vec::with_capacity(nodes as usize);
    let mut buff2 = Vec::with_capacity(nodes as usize);

    reached[root as usize] = true;
    buff1.push(root);

    while !buff1.is_empty() {
        buff1.sort_unstable();          // useful here, not for hashset tho.
        for node in buff1.drain(..) {
            for &edge in graph.edges(node as usize) {
                unsafe {
                    if !*reached.get_unchecked(edge as usize) {
                        *reached.get_unchecked_mut(edge as usize) = true;
                        buff2.push(edge);
                    }
                }
            }
        }
        ::std::mem::swap(&mut buff1, &mut buff2);
    }
}

fn breadth_first_hash(graph: &GraphMMap, root: u32) {

    use std::collections::HashSet;

    let nodes = graph.nodes() as u32;

    let mut reached = HashSet::new();
    let mut buff1 = Vec::with_capacity(nodes as usize);
    let mut buff2 = Vec::with_capacity(nodes as usize);

    reached.insert(root);
    buff1.push(root);

    while !buff1.is_empty() {
        for node in buff1.drain(..) {
            for &edge in graph.edges(node as usize) {
                if !reached.contains(&edge) {
                    reached.insert(edge);
                    buff2.push(edge);
                }
            }
        }
        ::std::mem::swap(&mut buff1, &mut buff2);
    }
}

fn union_find(graph: &GraphMMap) {

    let nodes = graph.nodes() as u32;
    let mut roots: Vec<u32> = (0..nodes).collect();      // u32 works, and is smaller than uint/u64
    let mut ranks: Vec<u8> = vec![0u8; nodes as usize];  // u8 should be large enough (n < 2^256)

    for node in 0 .. graph.nodes() {
        for &edge in graph.edges(node) {

            let mut x = node as u32;
            let mut y = edge as u32;

            // x = roots[x as usize];
            // y = roots[y as usize];
            x = unsafe { *roots.get_unchecked(x as usize) };
            y = unsafe { *roots.get_unchecked(y as usize) };

            // while x != roots[x as usize] { x = roots[x as usize]; }
            // while y != roots[y as usize] { y = roots[y as usize]; }
            unsafe { while x != *roots.get_unchecked(x as usize) { x = *roots.get_unchecked(x as usize); } }
            unsafe { while y != *roots.get_unchecked(y as usize) { y = *roots.get_unchecked(y as usize); } }

            if x != y {
                unsafe {
                    match ranks[x as usize].cmp(&ranks[y as usize]) {
                        std::cmp::Ordering::Less    => *roots.get_unchecked_mut(x as usize) = y as u32,
                        std::cmp::Ordering::Greater => *roots.get_unchecked_mut(y as usize) = x as u32,
                        std::cmp::Ordering::Equal   => { *roots.get_unchecked_mut(y as usize) = x as u32;
                                                         *ranks.get_unchecked_mut(x as usize) += 1 },
                    }
                }
            }
        }
    }
}

fn union_find_hash(graph: &GraphMMap) {

    use std::collections::HashMap;
    let nodes = graph.nodes() as u32;
    let mut roots: HashMap<u32,u32> = (0..nodes).map(|x| (x,x)).collect();
    let mut ranks: HashMap<u32,u8> =  (0..nodes).map(|x| (x,0)).collect();

    for node in 0 .. graph.nodes() {
        for &edge in graph.edges(node) {

            let mut x = node as u32;
            let mut y = edge as u32;

            x = roots[&x];
            y = roots[&y];

            while x != roots[&x] { x = roots[&x]; }
            while y != roots[&y] { y = roots[&y]; }

            if x != y {
                match ranks[&x].cmp(&ranks[&y]) {
                    std::cmp::Ordering::Less    => *roots.get_mut(&x).unwrap() = y,
                    std::cmp::Ordering::Greater => *roots.get_mut(&y).unwrap() = x,
                    std::cmp::Ordering::Equal   => { *roots.get_mut(&y).unwrap() = x; *ranks.get_mut(&x).unwrap() += 1; },
                }
            }
        }
    }
}<|endoftext|>


<commit_before><commit_msg>Fix: Do not write data if output is pipe<commit_after><|endoftext|>


<commit_before><commit_msg>Remove calls to trace_error_exit<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #1109 - RalfJung:track-caller, r=RalfJung<commit_after>#![feature(track_caller, core_intrinsics)]

use std::panic::Location;

#[track_caller]
fn tracked() -> &'static Location<'static> {
    Location::caller() // most importantly, we never get line 7
}

fn nested_intrinsic() -> &'static Location<'static> {
    Location::caller()
}

fn nested_tracked() -> &'static Location<'static> {
    tracked()
}

macro_rules! caller_location_from_macro {
    () => (core::panic::Location::caller());
}

fn main() {
    let location = Location::caller();
    assert_eq!(location.file(), file!());
    assert_eq!(location.line(), 23);
    assert_eq!(location.column(), 20);

    let tracked = tracked();
    assert_eq!(tracked.file(), file!());
    assert_eq!(tracked.line(), 28);
    assert_eq!(tracked.column(), 19);

    let nested = nested_intrinsic();
    assert_eq!(nested.file(), file!());
    assert_eq!(nested.line(), 11);
    assert_eq!(nested.column(), 5);

    let contained = nested_tracked();
    assert_eq!(contained.file(), file!());
    assert_eq!(contained.line(), 15);
    assert_eq!(contained.column(), 5);

    // `Location::caller()` in a macro should behave similarly to `file!` and `line!`,
    // i.e. point to where the macro was invoked, instead of the macro itself.
    let inmacro = caller_location_from_macro!();
    assert_eq!(inmacro.file(), file!());
    assert_eq!(inmacro.line(), 45);
    assert_eq!(inmacro.column(), 19);

    let intrinsic = core::intrinsics::caller_location();
    assert_eq!(intrinsic.file(), file!());
    assert_eq!(intrinsic.line(), 50);
    assert_eq!(intrinsic.column(), 21);
}
<|endoftext|>


<commit_before><commit_msg>Add test dir for list<commit_after>//! The integration suite for inspecting sessions.

extern crate common;
extern crate list;

#[cfg(test)]
mod test {
    mod list {
        use common::args::Args;
        use common::rand_names;
        use list;
        use std::fs;
        use std::fs::File;
        use std::path::PathBuf;

        fn make_files() -> PathBuf {
            let dir_name = rand_names::project_path_name();
            let dir = PathBuf::from(&dir_name);

            dbg!(&dir);
            if !&dir.exists() {
                println!("{:?}", fs::create_dir(&dir))
            };

            let configs = ["foo.yml", "bar.yml", "muxed.yml"];
            for config in &configs {
              let path = PathBuf::from(&dir_name).join(config);
              let _ = File::create(&path).expect("Muxed list test failed to create test config files.");
            }

            dir
        }

        fn cleanup(config_path: PathBuf) {
            // TODO: Do I really want to do this? What if we get it wrong.
            let _ = fs::remove_dir_all(config_path);
        }

        #[test]
        fn lists_files_muxed_dir() {
            // Uhhh I haven't captured any stdout data here. So it really just
            // tests to ensure it runs. Either capture stdout, or break the
            // functions down to test the collection of files, and the filtering.
            let project_dir = make_files();

            let args = Args {
                cmd_list: true,
                flag_p: Some(project_dir.display().to_string()),
                ..Default::default()
            };

            assert!(list::exec(args).is_ok());

            cleanup(project_dir);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Replace usage of error::FromError with std::convert::From<commit_after><|endoftext|>


<commit_before>
use std;
use piston::{
    Event,
    Input,
    Update,
    UpdateArgs,
};
use piston::input;
use {
    Action,
    AlwaysSucceed,
    Behavior,
    Failure,
    Not,
    Pressed,
    Released,
    Running,
    Select,
    Sequence,
    Status,
    Success,
    Wait,
    WaitForever,
    WhenAll,
    While,
};

/// Keeps track of an event.
#[deriving(Clone)]
pub enum State<A> {
    /// Keeps track of whether a button was pressed.
    PressedState(input::Button),
    /// Keeps track of whether a button was released.
    ReleasedState(input::Button),
    /// Keeps track of an event where you have a state of an action.
    ActionState(A),
    /// Keeps track of converting `Success` into `Failure` and vice versa.
    NotState(Box<State<A>>),
    /// Keeps track of a behavior that ignore failures.
    AlwaysSucceedState(Box<State<A>>),
    /// Keeps track of an event where you wait and do nothing.
    WaitState(f64, f64),
    /// Keeps track of a behavior that waits forever.
    WaitForeverState,
    /// Keeps track of a `Select` event.
    SelectState(Vec<Behavior<A>>, uint, Box<State<A>>),
    /// Keeps track of an event where sub events happens sequentially.
    SequenceState(Vec<Behavior<A>>, uint, Box<State<A>>),
    /// Keeps track of an event where sub events are repeated sequentially.
    WhileState(Box<State<A>>, Vec<Behavior<A>>, uint, Box<State<A>>),
    /// Keeps track of an event where all sub events must happen.
    WhenAllState(Vec<Option<State<A>>>),
}

impl<A: Clone> State<A> {
    /// Creates a state from a behavior.
    pub fn new(behavior: Behavior<A>) -> State<A> {
        match behavior {
            Pressed(button) => PressedState(button),
            Released(button) => ReleasedState(button),
            Action(action) => ActionState(action),
            Not(ev) => NotState(box State::new(*ev)),
            AlwaysSucceed(ev) => AlwaysSucceedState(box State::new(*ev)),
            Wait(dt) => WaitState(dt, 0.0),
            WaitForever => WaitForeverState,
            Select(sel) => {
                let state = State::new(sel[0].clone());
                SelectState(sel, 0, box state)
            }
            Sequence(seq) => {
                let state = State::new(seq[0].clone());
                SequenceState(seq, 0, box state)
            }
            While(ev, rep) => {
                let state = State::new(rep[0].clone());
                WhileState(box State::new(*ev), rep, 0, box state)
            }
            WhenAll(all)
                => WhenAllState(all.move_iter().map(
                    |ev| Some(State::new(ev))).collect()),
        }
    }

    /// Updates the cursor that tracks an event.
    ///
    /// The action need to return status and remaining delta time.
    /// Returns status and the remaining delta time.
    pub fn update(
        &mut self,
        e: &Event,
        f: |dt: f64, action: &A| -> (Status, f64)
    ) -> (Status, f64) {
        match (e, self) {
            (&Input(input::Press(button_pressed)), &PressedState(button))
            if button_pressed == button => {
                // Button press is considered to happen instantly.
                // There is no remaining delta time because this is input event.
                (Success, 0.0)
            }
            (&Input(input::Release(button_released)), &ReleasedState(button))
            if button_released == button => {
                // Button release is considered to happen instantly.
                // There is no remaining delta time because this is input event.
                (Success, 0.0)
            }
            (&Update(UpdateArgs { dt }), &ActionState(ref action)) => {
                // Execute action.
                f(dt, action)
            }
            (_, &NotState(ref mut cur)) => {
                match cur.update(e, f) {
                    (Running, dt) => (Running, dt),
                    (Failure, dt) => (Success, dt),
                    (Success, dt) => (Failure, dt),
                }
            }
            (_, &AlwaysSucceedState(ref mut cur)) => {
                match cur.update(e, f) {
                    (Running, dt) => (Running, dt),
                    (_, dt) => (Success, dt),
                }
            }
            (&Update(UpdateArgs { dt }), &WaitState(wait_t, ref mut t)) => {
                if *t + dt >= wait_t {
                    let remaining_dt = *t + dt - wait_t;
                    *t = wait_t;
                    (Success, remaining_dt)
                } else {
                    *t += dt;
                    (Running, 0.0)
                }
            }
            (_, &SelectState(
                ref seq,
                ref mut i,
                ref mut cursor
            )) => {
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                while *i < seq.len() {
                    match cursor.update(
                        match *e {
                            Update(_) => {
                                remaining_e = Update(UpdateArgs { dt: remaining_dt });
                                &remaining_e
                            }
                            _ => e
                        },
                        |dt, a| f(dt, a)) {
                        (Success, x) => { return (Success, x) }
                        (Running, _) => { break }
                        (Failure, new_dt) => { remaining_dt = new_dt }
                    };
                    *i += 1;
                    // If end of sequence,
                    // return the 'dt' that is left.
                    if *i >= seq.len() { return (Failure, remaining_dt); }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cursor = State::new(seq[*i].clone());
                }
                (Running, 0.0)
            }
            (_, &SequenceState(
                ref seq,
                ref mut i,
                ref mut cursor
            )) => {
                let cur = cursor;
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                while *i < seq.len() {
                    match cur.update(match *e {
                            Update(_) => {
                                remaining_e = Update(UpdateArgs { dt: remaining_dt });
                                &remaining_e
                            }
                            _ => e
                        },
                        |dt, a| f(dt, a)) {
                        (Failure, x) => return (Failure, x),
                        (Running, _) => { break },
                        (Success, new_dt) => {
                            remaining_dt = match *e {
                                // Change update event with remaining delta time.
                                Update(_) => new_dt,
                                // Other events are 'consumed' and not passed to next.
                                // If this is the last event, then the sequence succeeded.
                                _ => if *i == seq.len() - 1 {
                                        return (Success, new_dt)
                                    } else {
                                        return (Running, 0.0)
                                    }
                            }
                        }
                    };
                    *i += 1;
                    // If end of sequence,
                    // return the 'dt' that is left.
                    if *i >= seq.len() { return (Success, remaining_dt); }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cur = State::new(seq[*i].clone());
                }
                (Running, 0.0)
            }
            (_, &WhileState(
                ref mut ev_cursor,
                ref rep,
                ref mut i,
                ref mut cursor
            )) => {
                // If the event terminates, do not execute the loop.
                match ev_cursor.update(e, |dt, a| f(dt, a)) {
                    (Running, _) => {}
                    x => return x,
                };
                let cur = cursor;
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                loop {
                    match cur.update(match *e {
                            Update(_) => {
                                remaining_e = Update(UpdateArgs { dt: remaining_dt });
                                &remaining_e
                            }
                            _ => e
                        },
                        |dt, a| f(dt, a)) {
                        (Failure, x) => return (Failure, x),
                        (Running, _) => { break },
                        (Success, new_dt) => {
                            remaining_dt = match *e {
                                // Change update event with remaining delta time.
                                Update(_) => new_dt,
                                // Other events are 'consumed' and not passed to next.
                                _ => return (Running, 0.0)
                            }
                        }
                    };
                    *i += 1;
                    // If end of repeated events,
                    // start over from the first one.
                    if *i >= rep.len() { *i = 0; }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cur = State::new(rep[*i].clone());
                }
                (Running, 0.0)
            }
            (_, &WhenAllState(ref mut cursors)) => {
                // Get the least delta time left over.
                let mut min_dt = std::f64::MAX_VALUE;
                // Count number of terminated events.
                let mut terminated = 0;
                for cur in cursors.mut_iter() {
                    match *cur {
                        None => terminated += 1,
                        Some(ref mut cur) => {
                            match cur.update(e, |dt, a| f(dt, a)) {
                                (Running, _) => {},
                                (Failure, new_dt) => return (Failure, new_dt),
                                (Success, new_dt) => {
                                    min_dt = min_dt.min(new_dt);
                                    terminated += 1;
                                }
                            }
                        }
                    }
                }
                match terminated {
                    // If there are no events, there is a whole 'dt' left.
                    0 if cursors.len() == 0 => (Success, match *e {
                            Update(UpdateArgs { dt }) => dt,
                            // Other kind of events happen instantly.
                            _ => 0.0
                        }),
                    // If all events terminated, the least delta time is left.
                    n if cursors.len() == n => (Success, min_dt),
                    _ => (Running, 0.0)
                }
            }
            _ => (Running, 0.0)
        }
    }
}
<commit_msg>Fixed doc comments<commit_after>
use std;
use piston::{
    Event,
    Input,
    Update,
    UpdateArgs,
};
use piston::input;
use {
    Action,
    AlwaysSucceed,
    Behavior,
    Failure,
    Not,
    Pressed,
    Released,
    Running,
    Select,
    Sequence,
    Status,
    Success,
    Wait,
    WaitForever,
    WhenAll,
    While,
};

/// Keeps track of a behavior.
#[deriving(Clone)]
pub enum State<A> {
    /// Returns `Success` when button is pressed.
    PressedState(input::Button),
    /// Returns `Success` when button is released.
    ReleasedState(input::Button),
    /// Executes an action.
    ActionState(A),
    /// Converts `Success` into `Failure` and vice versa.
    NotState(Box<State<A>>),
    /// Ignores failures and always return `Success`.
    AlwaysSucceedState(Box<State<A>>),
    /// Number of seconds we should wait and seconds we have waited.
    WaitState(f64, f64),
    /// Waits forever.
    WaitForeverState,
    /// Keeps track of a `Select` behavior.
    SelectState(Vec<Behavior<A>>, uint, Box<State<A>>),
    /// Keeps track of an `Sequence` behavior.
    SequenceState(Vec<Behavior<A>>, uint, Box<State<A>>),
    /// Keeps track of a `While` behavior.
    WhileState(Box<State<A>>, Vec<Behavior<A>>, uint, Box<State<A>>),
    /// Keeps track of an `WhenAll` behavior.
    WhenAllState(Vec<Option<State<A>>>),
}

impl<A: Clone> State<A> {
    /// Creates a state from a behavior.
    pub fn new(behavior: Behavior<A>) -> State<A> {
        match behavior {
            Pressed(button) => PressedState(button),
            Released(button) => ReleasedState(button),
            Action(action) => ActionState(action),
            Not(ev) => NotState(box State::new(*ev)),
            AlwaysSucceed(ev) => AlwaysSucceedState(box State::new(*ev)),
            Wait(dt) => WaitState(dt, 0.0),
            WaitForever => WaitForeverState,
            Select(sel) => {
                let state = State::new(sel[0].clone());
                SelectState(sel, 0, box state)
            }
            Sequence(seq) => {
                let state = State::new(seq[0].clone());
                SequenceState(seq, 0, box state)
            }
            While(ev, rep) => {
                let state = State::new(rep[0].clone());
                WhileState(box State::new(*ev), rep, 0, box state)
            }
            WhenAll(all)
                => WhenAllState(all.move_iter().map(
                    |ev| Some(State::new(ev))).collect()),
        }
    }

    /// Updates the cursor that tracks an event.
    ///
    /// The action need to return status and remaining delta time.
    /// Returns status and the remaining delta time.
    pub fn update(
        &mut self,
        e: &Event,
        f: |dt: f64, action: &A| -> (Status, f64)
    ) -> (Status, f64) {
        match (e, self) {
            (&Input(input::Press(button_pressed)), &PressedState(button))
            if button_pressed == button => {
                // Button press is considered to happen instantly.
                // There is no remaining delta time because this is input event.
                (Success, 0.0)
            }
            (&Input(input::Release(button_released)), &ReleasedState(button))
            if button_released == button => {
                // Button release is considered to happen instantly.
                // There is no remaining delta time because this is input event.
                (Success, 0.0)
            }
            (&Update(UpdateArgs { dt }), &ActionState(ref action)) => {
                // Execute action.
                f(dt, action)
            }
            (_, &NotState(ref mut cur)) => {
                match cur.update(e, f) {
                    (Running, dt) => (Running, dt),
                    (Failure, dt) => (Success, dt),
                    (Success, dt) => (Failure, dt),
                }
            }
            (_, &AlwaysSucceedState(ref mut cur)) => {
                match cur.update(e, f) {
                    (Running, dt) => (Running, dt),
                    (_, dt) => (Success, dt),
                }
            }
            (&Update(UpdateArgs { dt }), &WaitState(wait_t, ref mut t)) => {
                if *t + dt >= wait_t {
                    let remaining_dt = *t + dt - wait_t;
                    *t = wait_t;
                    (Success, remaining_dt)
                } else {
                    *t += dt;
                    (Running, 0.0)
                }
            }
            (_, &SelectState(
                ref seq,
                ref mut i,
                ref mut cursor
            )) => {
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                while *i < seq.len() {
                    match cursor.update(
                        match *e {
                            Update(_) => {
                                remaining_e = Update(UpdateArgs { dt: remaining_dt });
                                &remaining_e
                            }
                            _ => e
                        },
                        |dt, a| f(dt, a)) {
                        (Success, x) => { return (Success, x) }
                        (Running, _) => { break }
                        (Failure, new_dt) => { remaining_dt = new_dt }
                    };
                    *i += 1;
                    // If end of sequence,
                    // return the 'dt' that is left.
                    if *i >= seq.len() { return (Failure, remaining_dt); }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cursor = State::new(seq[*i].clone());
                }
                (Running, 0.0)
            }
            (_, &SequenceState(
                ref seq,
                ref mut i,
                ref mut cursor
            )) => {
                let cur = cursor;
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                while *i < seq.len() {
                    match cur.update(match *e {
                            Update(_) => {
                                remaining_e = Update(UpdateArgs { dt: remaining_dt });
                                &remaining_e
                            }
                            _ => e
                        },
                        |dt, a| f(dt, a)) {
                        (Failure, x) => return (Failure, x),
                        (Running, _) => { break },
                        (Success, new_dt) => {
                            remaining_dt = match *e {
                                // Change update event with remaining delta time.
                                Update(_) => new_dt,
                                // Other events are 'consumed' and not passed to next.
                                // If this is the last event, then the sequence succeeded.
                                _ => if *i == seq.len() - 1 {
                                        return (Success, new_dt)
                                    } else {
                                        return (Running, 0.0)
                                    }
                            }
                        }
                    };
                    *i += 1;
                    // If end of sequence,
                    // return the 'dt' that is left.
                    if *i >= seq.len() { return (Success, remaining_dt); }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cur = State::new(seq[*i].clone());
                }
                (Running, 0.0)
            }
            (_, &WhileState(
                ref mut ev_cursor,
                ref rep,
                ref mut i,
                ref mut cursor
            )) => {
                // If the event terminates, do not execute the loop.
                match ev_cursor.update(e, |dt, a| f(dt, a)) {
                    (Running, _) => {}
                    x => return x,
                };
                let cur = cursor;
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                loop {
                    match cur.update(match *e {
                            Update(_) => {
                                remaining_e = Update(UpdateArgs { dt: remaining_dt });
                                &remaining_e
                            }
                            _ => e
                        },
                        |dt, a| f(dt, a)) {
                        (Failure, x) => return (Failure, x),
                        (Running, _) => { break },
                        (Success, new_dt) => {
                            remaining_dt = match *e {
                                // Change update event with remaining delta time.
                                Update(_) => new_dt,
                                // Other events are 'consumed' and not passed to next.
                                _ => return (Running, 0.0)
                            }
                        }
                    };
                    *i += 1;
                    // If end of repeated events,
                    // start over from the first one.
                    if *i >= rep.len() { *i = 0; }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cur = State::new(rep[*i].clone());
                }
                (Running, 0.0)
            }
            (_, &WhenAllState(ref mut cursors)) => {
                // Get the least delta time left over.
                let mut min_dt = std::f64::MAX_VALUE;
                // Count number of terminated events.
                let mut terminated = 0;
                for cur in cursors.mut_iter() {
                    match *cur {
                        None => terminated += 1,
                        Some(ref mut cur) => {
                            match cur.update(e, |dt, a| f(dt, a)) {
                                (Running, _) => {},
                                (Failure, new_dt) => return (Failure, new_dt),
                                (Success, new_dt) => {
                                    min_dt = min_dt.min(new_dt);
                                    terminated += 1;
                                }
                            }
                        }
                    }
                }
                match terminated {
                    // If there are no events, there is a whole 'dt' left.
                    0 if cursors.len() == 0 => (Success, match *e {
                            Update(UpdateArgs { dt }) => dt,
                            // Other kind of events happen instantly.
                            _ => 0.0
                        }),
                    // If all events terminated, the least delta time is left.
                    n if cursors.len() == n => (Success, min_dt),
                    _ => (Running, 0.0)
                }
            }
            _ => (Running, 0.0)
        }
    }
}
<|endoftext|>


<commit_before>use std::{usize, iter};
use std::cmp::max;
use std::time::duration::Duration;
use std::num::UnsignedInt;
use time::precise_time_ns;
use os::token::Token;
use util::Slab;

use self::TimerErrorKind::TimerOverflow;

const EMPTY: Token = Token(usize::MAX);
const NS_PER_MS: u64 = 1_000_000;

// Implements coarse-grained timeouts using an algorithm based on hashed timing
// wheels by Varghese & Lauck.
//
// TODO:
// * Handle the case when the timer falls more than an entire wheel behind. There
//   is no point to loop multiple times around the wheel in one go.
// * New type for tick, now() -> Tick
#[derive(Debug)]
pub struct Timer<T> {
    // Size of each tick in milliseconds
    tick_ms: u64,
    // Slab of timeout entries
    entries: Slab<Entry<T>>,
    // Timeout wheel. Each tick, the timer will look at the next slot for
    // timeouts that match the current tick.
    wheel: Vec<Token>,
    // Tick 0's time in milliseconds
    start: u64,
    // The current tick
    tick: u64,
    // The next entry to possibly timeout
    next: Token,
    // Masks the target tick to get the slot
    mask: u64,
}

#[derive(Copy)]
pub struct Timeout {
    // Reference into the timer entry slab
    token: Token,
    // Tick that it should matchup with
    tick: u64,
}

impl<T> Timer<T> {
    pub fn new(tick_ms: u64, mut slots: usize, mut capacity: usize) -> Timer<T> {
        slots = UnsignedInt::next_power_of_two(slots);
        capacity = UnsignedInt::next_power_of_two(capacity);

        Timer {
            tick_ms: tick_ms,
            entries: Slab::new(capacity),
            wheel: iter::repeat(EMPTY).take(slots).collect(),
            start: 0,
            tick: 0,
            next: EMPTY,
            mask: (slots as u64) - 1
        }
    }

    #[test]
    pub fn count(&self) -> usize {
        self.entries.count()
    }

    // Number of ms remaining until the next tick
    pub fn next_tick_in_ms(&self) -> u64 {
        let now = self.now_ms();
        let nxt = self.start + (self.tick + 1) * self.tick_ms;

        if nxt <= now {
            return 0;
        }

        nxt - now
    }

    /*
     *
     * ===== Initialization =====
     *
     */

    // Sets the starting time of the timer using the current system time
    pub fn setup(&mut self) {
        let now = self.now_ms();
        self.set_start_ms(now);
    }

    fn set_start_ms(&mut self, start: u64) {
        assert!(!self.is_initialized(), "the timer has already started");
        self.start = start;
    }

    /*
     *
     * ===== Timeout create / cancel =====
     *
     */

    pub fn timeout(&mut self, token: T, delay: Duration) -> TimerResult<Timeout> {
        let at = self.now_ms() + (max(0, delay.num_milliseconds()) as u64);
        self.timeout_at_ms(token, at)
    }

    pub fn timeout_at_ms(&mut self, token: T, mut at: u64) -> TimerResult<Timeout> {
        // Make relative to start
        at -= self.start;
        // Calculate tick
        let mut tick = (at + self.tick_ms - 1) / self.tick_ms;

        // Always target at least 1 tick in the future
        if tick <= self.tick {
            tick = self.tick + 1;
        }

        self.insert(token, tick)
    }

    pub fn clear(&mut self, timeout: Timeout) -> bool {
        let links = match self.entries.get(timeout.token) {
            Some(e) => e.links,
            None => return false
        };

        // Sanity check
        if links.tick != timeout.tick {
            return false;
        }

        self.unlink(&links, timeout.token);
        self.entries.remove(timeout.token);
        true
    }

    fn insert(&mut self, token: T, tick: u64) -> TimerResult<Timeout> {
        // Get the slot for the requested tick
        let slot = (tick & self.mask) as usize;
        let curr = self.wheel[slot];

        // Insert the new entry
        let token = try!(
            self.entries.insert(Entry::new(token, tick, curr))
            .map_err(|_| TimerError::overflow()));

        if curr != EMPTY {
            // If there was a previous entry, set its prev pointer to the new
            // entry
            self.entries[curr].links.prev = token;
        }

        // Update the head slot
        self.wheel[slot] = token;

        debug!("inserted timout; slot={}; token={:?}", slot, token);

        // Return the new timeout
        Ok(Timeout {
            token: token,
            tick: tick
        })
    }

    fn unlink(&mut self, links: &EntryLinks, token: Token) {
        debug!("unlinking timeout; slot={}; token={:?}",
               self.slot_for(links.tick), token);

        if links.prev == EMPTY {
            let slot = self.slot_for(links.tick);
            self.wheel[slot] = links.next;
        } else {
            self.entries[links.prev].links.next = links.next;
        }

        if links.next != EMPTY {
            self.entries[links.next].links.prev = links.prev;

            if token == self.next {
                self.next = links.next;
            }
        } else if token == self.next {
            self.next = EMPTY;
        }
    }

    /*
     *
     * ===== Advance time =====
     *
     */

    pub fn now(&self) -> u64 {
        self.ms_to_tick(self.now_ms())
    }

    pub fn tick_to(&mut self, now: u64) -> Option<T> {
        debug!("tick_to; now={}; tick={}", now, self.tick);

        while self.tick <= now {
            let curr = self.next;

            debug!("ticking; curr={:?}", curr);

            if curr == EMPTY {
                self.tick += 1;
                self.next = self.wheel[self.slot_for(self.tick)];
            } else {
                let links = self.entries[curr].links;

                if links.tick <= self.tick {
                    debug!("triggering; token={:?}", curr);

                    // Unlink will also advance self.next
                    self.unlink(&links, curr);

                    // Remove and return the token
                    return self.entries.remove(curr)
                        .map(|e| e.token);
                } else {
                    self.next = links.next;
                }
            }
        }

        None
    }

    /*
     *
     * ===== Misc =====
     *
     */

    // Timers are initialized when either the current time has been advanced or a timeout has been set
    #[inline]
    fn is_initialized(&self) -> bool {
        self.tick > 0 || !self.entries.is_empty()
    }

    #[inline]
    fn slot_for(&self, tick: u64) -> usize {
        (self.mask & tick) as usize
    }

    // Convert a ms duration into a number of ticks, rounds up
    #[inline]
    fn ms_to_tick(&self, ms: u64) -> u64 {
        (ms - self.start) / self.tick_ms
    }

    #[inline]
    fn now_ms(&self) -> u64 {
        precise_time_ns() / NS_PER_MS
    }
}

// Doubly linked list of timer entries. Allows for efficient insertion /
// removal of timeouts.
struct Entry<T> {
    token: T,
    links: EntryLinks,
}

impl<T> Entry<T> {
    fn new(token: T, tick: u64, next: Token) -> Entry<T> {
        Entry {
            token: token,
            links: EntryLinks {
                tick: tick,
                prev: EMPTY,
                next: next,
            },
        }
    }
}

#[derive(Copy)]
struct EntryLinks {
    tick: u64,
    prev: Token,
    next: Token
}

pub type TimerResult<T> = Result<T, TimerError>;

#[derive(Debug)]
pub struct TimerError {
    kind: TimerErrorKind,
    desc: &'static str,
}

impl TimerError {
    fn overflow() -> TimerError {
        TimerError {
            kind: TimerOverflow,
            desc: "too many timer entries"
        }
    }
}

#[derive(Debug)]
pub enum TimerErrorKind {
    TimerOverflow,
}

#[cfg(test)]
mod test {
    use super::Timer;

    #[test]
    pub fn test_timeout_next_tick() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 100).unwrap();

        tick = t.ms_to_tick(50);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(100);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(150);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));

        assert_eq!(t.count(), 0);
    }

    #[test]
    pub fn test_clearing_timeout() {
        let mut t = timer();
        let mut tick;

        let to = t.timeout_at_ms("a", 100).unwrap();
        assert!(t.clear(to));

        tick = t.ms_to_tick(100);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));

        assert_eq!(t.count(), 0);
    }

    #[test]
    pub fn test_multiple_timeouts_same_tick() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 100).unwrap();
        t.timeout_at_ms("b", 100).unwrap();

        let mut rcv = vec![];

        tick = t.ms_to_tick(100);
        rcv.push(t.tick_to(tick).unwrap());
        rcv.push(t.tick_to(tick).unwrap());

        assert_eq!(None, t.tick_to(tick));

        rcv.sort();
        assert!(rcv.as_slice() == ["a", "b"].as_slice(), "actual={:?}", rcv.as_slice());

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));

        assert_eq!(t.count(), 0);
    }

    #[test]
    pub fn test_multiple_timeouts_diff_tick() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 110).unwrap();
        t.timeout_at_ms("b", 220).unwrap();
        t.timeout_at_ms("c", 230).unwrap();
        t.timeout_at_ms("d", 440).unwrap();

        tick = t.ms_to_tick(100);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(300);
        assert_eq!(Some("c"), t.tick_to(tick));
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(400);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(500);
        assert_eq!(Some("d"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(600);
        assert_eq!(None, t.tick_to(tick));
    }

    #[test]
    pub fn test_catching_up() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 110).unwrap();
        t.timeout_at_ms("b", 220).unwrap();
        t.timeout_at_ms("c", 230).unwrap();
        t.timeout_at_ms("d", 440).unwrap();

        tick = t.ms_to_tick(600);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(Some("c"), t.tick_to(tick));
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(Some("d"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));
    }

    #[test]
    pub fn test_timeout_hash_collision() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 100).unwrap();
        t.timeout_at_ms("b", 100 + TICK * SLOTS as u64).unwrap();

        tick = t.ms_to_tick(100);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(1, t.count());

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));
        assert_eq!(1, t.count());

        tick = t.ms_to_tick(100 + TICK * SLOTS as u64);
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(0, t.count());
    }

    #[test]
    pub fn test_clearing_timeout_between_triggers() {
        let mut t = timer();
        let mut tick;

        let a = t.timeout_at_ms("a", 100).unwrap();
        let _ = t.timeout_at_ms("b", 100).unwrap();
        let _ = t.timeout_at_ms("c", 200).unwrap();

        tick = t.ms_to_tick(100);
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(2, t.count());

        t.clear(a);
        assert_eq!(1, t.count());

        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(Some("c"), t.tick_to(tick));
        assert_eq!(0, t.count());
    }

    const TICK: u64 = 100;
    const SLOTS: usize = 16;

    fn timer() -> Timer<&'static str> {
        Timer::new(TICK, SLOTS, 32)
    }
}
<commit_msg>Fix test only cfg<commit_after>use std::{usize, iter};
use std::cmp::max;
use std::time::duration::Duration;
use std::num::UnsignedInt;
use time::precise_time_ns;
use os::token::Token;
use util::Slab;

use self::TimerErrorKind::TimerOverflow;

const EMPTY: Token = Token(usize::MAX);
const NS_PER_MS: u64 = 1_000_000;

// Implements coarse-grained timeouts using an algorithm based on hashed timing
// wheels by Varghese & Lauck.
//
// TODO:
// * Handle the case when the timer falls more than an entire wheel behind. There
//   is no point to loop multiple times around the wheel in one go.
// * New type for tick, now() -> Tick
#[derive(Debug)]
pub struct Timer<T> {
    // Size of each tick in milliseconds
    tick_ms: u64,
    // Slab of timeout entries
    entries: Slab<Entry<T>>,
    // Timeout wheel. Each tick, the timer will look at the next slot for
    // timeouts that match the current tick.
    wheel: Vec<Token>,
    // Tick 0's time in milliseconds
    start: u64,
    // The current tick
    tick: u64,
    // The next entry to possibly timeout
    next: Token,
    // Masks the target tick to get the slot
    mask: u64,
}

#[derive(Copy)]
pub struct Timeout {
    // Reference into the timer entry slab
    token: Token,
    // Tick that it should matchup with
    tick: u64,
}

impl<T> Timer<T> {
    pub fn new(tick_ms: u64, mut slots: usize, mut capacity: usize) -> Timer<T> {
        slots = UnsignedInt::next_power_of_two(slots);
        capacity = UnsignedInt::next_power_of_two(capacity);

        Timer {
            tick_ms: tick_ms,
            entries: Slab::new(capacity),
            wheel: iter::repeat(EMPTY).take(slots).collect(),
            start: 0,
            tick: 0,
            next: EMPTY,
            mask: (slots as u64) - 1
        }
    }

    #[cfg(test)]
    pub fn count(&self) -> usize {
        self.entries.count()
    }

    // Number of ms remaining until the next tick
    pub fn next_tick_in_ms(&self) -> u64 {
        let now = self.now_ms();
        let nxt = self.start + (self.tick + 1) * self.tick_ms;

        if nxt <= now {
            return 0;
        }

        nxt - now
    }

    /*
     *
     * ===== Initialization =====
     *
     */

    // Sets the starting time of the timer using the current system time
    pub fn setup(&mut self) {
        let now = self.now_ms();
        self.set_start_ms(now);
    }

    fn set_start_ms(&mut self, start: u64) {
        assert!(!self.is_initialized(), "the timer has already started");
        self.start = start;
    }

    /*
     *
     * ===== Timeout create / cancel =====
     *
     */

    pub fn timeout(&mut self, token: T, delay: Duration) -> TimerResult<Timeout> {
        let at = self.now_ms() + (max(0, delay.num_milliseconds()) as u64);
        self.timeout_at_ms(token, at)
    }

    pub fn timeout_at_ms(&mut self, token: T, mut at: u64) -> TimerResult<Timeout> {
        // Make relative to start
        at -= self.start;
        // Calculate tick
        let mut tick = (at + self.tick_ms - 1) / self.tick_ms;

        // Always target at least 1 tick in the future
        if tick <= self.tick {
            tick = self.tick + 1;
        }

        self.insert(token, tick)
    }

    pub fn clear(&mut self, timeout: Timeout) -> bool {
        let links = match self.entries.get(timeout.token) {
            Some(e) => e.links,
            None => return false
        };

        // Sanity check
        if links.tick != timeout.tick {
            return false;
        }

        self.unlink(&links, timeout.token);
        self.entries.remove(timeout.token);
        true
    }

    fn insert(&mut self, token: T, tick: u64) -> TimerResult<Timeout> {
        // Get the slot for the requested tick
        let slot = (tick & self.mask) as usize;
        let curr = self.wheel[slot];

        // Insert the new entry
        let token = try!(
            self.entries.insert(Entry::new(token, tick, curr))
            .map_err(|_| TimerError::overflow()));

        if curr != EMPTY {
            // If there was a previous entry, set its prev pointer to the new
            // entry
            self.entries[curr].links.prev = token;
        }

        // Update the head slot
        self.wheel[slot] = token;

        debug!("inserted timout; slot={}; token={:?}", slot, token);

        // Return the new timeout
        Ok(Timeout {
            token: token,
            tick: tick
        })
    }

    fn unlink(&mut self, links: &EntryLinks, token: Token) {
        debug!("unlinking timeout; slot={}; token={:?}",
               self.slot_for(links.tick), token);

        if links.prev == EMPTY {
            let slot = self.slot_for(links.tick);
            self.wheel[slot] = links.next;
        } else {
            self.entries[links.prev].links.next = links.next;
        }

        if links.next != EMPTY {
            self.entries[links.next].links.prev = links.prev;

            if token == self.next {
                self.next = links.next;
            }
        } else if token == self.next {
            self.next = EMPTY;
        }
    }

    /*
     *
     * ===== Advance time =====
     *
     */

    pub fn now(&self) -> u64 {
        self.ms_to_tick(self.now_ms())
    }

    pub fn tick_to(&mut self, now: u64) -> Option<T> {
        debug!("tick_to; now={}; tick={}", now, self.tick);

        while self.tick <= now {
            let curr = self.next;

            debug!("ticking; curr={:?}", curr);

            if curr == EMPTY {
                self.tick += 1;
                self.next = self.wheel[self.slot_for(self.tick)];
            } else {
                let links = self.entries[curr].links;

                if links.tick <= self.tick {
                    debug!("triggering; token={:?}", curr);

                    // Unlink will also advance self.next
                    self.unlink(&links, curr);

                    // Remove and return the token
                    return self.entries.remove(curr)
                        .map(|e| e.token);
                } else {
                    self.next = links.next;
                }
            }
        }

        None
    }

    /*
     *
     * ===== Misc =====
     *
     */

    // Timers are initialized when either the current time has been advanced or a timeout has been set
    #[inline]
    fn is_initialized(&self) -> bool {
        self.tick > 0 || !self.entries.is_empty()
    }

    #[inline]
    fn slot_for(&self, tick: u64) -> usize {
        (self.mask & tick) as usize
    }

    // Convert a ms duration into a number of ticks, rounds up
    #[inline]
    fn ms_to_tick(&self, ms: u64) -> u64 {
        (ms - self.start) / self.tick_ms
    }

    #[inline]
    fn now_ms(&self) -> u64 {
        precise_time_ns() / NS_PER_MS
    }
}

// Doubly linked list of timer entries. Allows for efficient insertion /
// removal of timeouts.
struct Entry<T> {
    token: T,
    links: EntryLinks,
}

impl<T> Entry<T> {
    fn new(token: T, tick: u64, next: Token) -> Entry<T> {
        Entry {
            token: token,
            links: EntryLinks {
                tick: tick,
                prev: EMPTY,
                next: next,
            },
        }
    }
}

#[derive(Copy)]
struct EntryLinks {
    tick: u64,
    prev: Token,
    next: Token
}

pub type TimerResult<T> = Result<T, TimerError>;

#[derive(Debug)]
pub struct TimerError {
    kind: TimerErrorKind,
    desc: &'static str,
}

impl TimerError {
    fn overflow() -> TimerError {
        TimerError {
            kind: TimerOverflow,
            desc: "too many timer entries"
        }
    }
}

#[derive(Debug)]
pub enum TimerErrorKind {
    TimerOverflow,
}

#[cfg(test)]
mod test {
    use super::Timer;

    #[test]
    pub fn test_timeout_next_tick() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 100).unwrap();

        tick = t.ms_to_tick(50);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(100);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(150);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));

        assert_eq!(t.count(), 0);
    }

    #[test]
    pub fn test_clearing_timeout() {
        let mut t = timer();
        let mut tick;

        let to = t.timeout_at_ms("a", 100).unwrap();
        assert!(t.clear(to));

        tick = t.ms_to_tick(100);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));

        assert_eq!(t.count(), 0);
    }

    #[test]
    pub fn test_multiple_timeouts_same_tick() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 100).unwrap();
        t.timeout_at_ms("b", 100).unwrap();

        let mut rcv = vec![];

        tick = t.ms_to_tick(100);
        rcv.push(t.tick_to(tick).unwrap());
        rcv.push(t.tick_to(tick).unwrap());

        assert_eq!(None, t.tick_to(tick));

        rcv.sort();
        assert!(rcv.as_slice() == ["a", "b"].as_slice(), "actual={:?}", rcv.as_slice());

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));

        assert_eq!(t.count(), 0);
    }

    #[test]
    pub fn test_multiple_timeouts_diff_tick() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 110).unwrap();
        t.timeout_at_ms("b", 220).unwrap();
        t.timeout_at_ms("c", 230).unwrap();
        t.timeout_at_ms("d", 440).unwrap();

        tick = t.ms_to_tick(100);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(300);
        assert_eq!(Some("c"), t.tick_to(tick));
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(400);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(500);
        assert_eq!(Some("d"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(600);
        assert_eq!(None, t.tick_to(tick));
    }

    #[test]
    pub fn test_catching_up() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 110).unwrap();
        t.timeout_at_ms("b", 220).unwrap();
        t.timeout_at_ms("c", 230).unwrap();
        t.timeout_at_ms("d", 440).unwrap();

        tick = t.ms_to_tick(600);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(Some("c"), t.tick_to(tick));
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(Some("d"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));
    }

    #[test]
    pub fn test_timeout_hash_collision() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 100).unwrap();
        t.timeout_at_ms("b", 100 + TICK * SLOTS as u64).unwrap();

        tick = t.ms_to_tick(100);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(1, t.count());

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));
        assert_eq!(1, t.count());

        tick = t.ms_to_tick(100 + TICK * SLOTS as u64);
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(0, t.count());
    }

    #[test]
    pub fn test_clearing_timeout_between_triggers() {
        let mut t = timer();
        let mut tick;

        let a = t.timeout_at_ms("a", 100).unwrap();
        let _ = t.timeout_at_ms("b", 100).unwrap();
        let _ = t.timeout_at_ms("c", 200).unwrap();

        tick = t.ms_to_tick(100);
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(2, t.count());

        t.clear(a);
        assert_eq!(1, t.count());

        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(Some("c"), t.tick_to(tick));
        assert_eq!(0, t.count());
    }

    const TICK: u64 = 100;
    const SLOTS: usize = 16;

    fn timer() -> Timer<&'static str> {
        Timer::new(TICK, SLOTS, 32)
    }
}
<|endoftext|>


<commit_before><commit_msg>tee hee... forgot to commit types.rs<commit_after>//! Type conversions for binding parameters and getting query results.

use super::{ResultRow, SqliteResult, SQLITE_MISMATCH};
use super::{ParameterValue,
            Null,
            Integer,
            Integer64,
            Float64,
            Text};
use time;

/// A trait for result values from a query.
///
/// cf [sqlite3 result values][column].
///
/// *inspired by sfackler's FromSql (and some haskell bindings?)*
///
/// [column]: http://www.sqlite.org/c3ref/column_blob.html
///
///   - TODO: consider a `types` submodule
///   - TODO: many more implementors, including Option<T>
pub trait FromSql {
    fn from_sql(row: &ResultRow, col: uint) -> SqliteResult<Self>;
}

pub trait ToSql {
    fn to_sql(&self) -> ParameterValue;
}

impl FromSql for i32 {
    fn from_sql(row: &ResultRow, col: uint) -> SqliteResult<i32> { Ok(row.column_int(col)) }
}

impl FromSql for int {
    // TODO: get_int should take a uint, not an int, right?
    fn from_sql(row: &ResultRow, col: uint) -> SqliteResult<int> { Ok(row.column_int(col) as int) }
}

impl ToSql for int {
    fn to_sql(&self) -> ParameterValue { Integer(*self) }
}

impl ToSql for i64 {
    fn to_sql(&self) -> ParameterValue { Integer64(*self) }
}

impl ToSql for f64 {
    fn to_sql(&self) -> ParameterValue { Float64(*self) }
}

impl<T: ToSql + Clone> ToSql for Option<T> {
    fn to_sql(&self) -> ParameterValue {
        match (*self).clone() {
            Some(x) => x.to_sql(),
            None => Null
        }
    }
}

impl FromSql for String {
    fn from_sql(row: &ResultRow, col: uint) -> SqliteResult<String> {
        Ok(row.column_text(col).to_string())
    }
}

impl ToSql for String {
    // TODO: eliminate copy?
    fn to_sql(&self) -> ParameterValue { Text(self.clone()) }
}

impl FromSql for time::Tm {
    /// TODO: propagate error message
    fn from_sql(row: &ResultRow, col: uint) -> SqliteResult<time::Tm> {
        let isofmt = "%F";  // YYYY-MM-DD
        match row.column_text(col) {
            None => Err(SQLITE_MISMATCH),
            Some(txt) => match time::strptime(txt.as_slice(), isofmt) {
                Ok(tm) => Ok(tm),
                Err(msg) => Err(SQLITE_MISMATCH)
            }
        }
    }
}

impl ToSql for time::Timespec {
    fn to_sql(&self) -> ParameterValue {
        Text(time::at_utc(*self).rfc3339())
    }
}

impl FromSql for time::Timespec {
    /// TODO: propagate error message
    fn from_sql(row: &ResultRow, col: uint) -> SqliteResult<time::Timespec> {
        let tmo: SqliteResult<time::Tm> = FromSql::from_sql(row, col);
        tmo.map(|tm| tm.to_timespec())
    }
}

// Local Variables:
// flycheck-rust-crate-root: "lib.rs"
// End:
<|endoftext|>


<commit_before><commit_msg>increase generation with tick<commit_after><|endoftext|>


<commit_before><commit_msg>Create chap2.rs<commit_after>use std::f32::consts;

static RAD : f32 = 3.14;

fn get_radius() -> Option<f32> {
Some(3.45)
}

fn main() {
let rad = get_radius().unwrap_or(RAD);
println!("The Area of Circle is {:?} (m)^2",consts::PI*rad*rad);
}
<|endoftext|>


<commit_before><commit_msg>Test that async/await compiles with `#![no_std]`<commit_after>// edition:2018
// check-pass

#![no_std]
#![crate_type = "rlib"]

use core::future::Future;

async fn a(f: impl Future) {
    f.await;
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #22814<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.

trait Test {}

macro_rules! test {
( $($name:ident)+) => (
    impl<$($name: Test),*> Test for ($($name,)*) {
    }
)
}

test!(A B C);

fn main() {}
<|endoftext|>


<commit_before><commit_msg>tests(IAM): add simple IAM tests<commit_after>#![cfg(feature = "iam")]

extern crate rusoto;

use rusoto::iam::IamClient;
use rusoto::iam::{GetUserRequest, ListUsersRequest};
use rusoto::{DefaultCredentialsProvider, Region};

#[test]
fn get_user() {
    let credentials = DefaultCredentialsProvider::new().unwrap();

    let iam = IamClient::new(credentials, Region::UsEast1);

    // http://docs.aws.amazon.com/IAM/latest/APIReference/Welcome.html
    let request = GetUserRequest {
        ..Default::default()
    };
    iam.get_user(&request).unwrap();
}

#[test]
fn list_users() {
    let credentials = DefaultCredentialsProvider::new().unwrap();

    let iam = IamClient::new(credentials, Region::UsEast1);

    // http://docs.aws.amazon.com/IAM/latest/APIReference/Welcome.html
    let request = ListUsersRequest {
        ..Default::default()
    };
    iam.list_users(&request).unwrap();
}
<|endoftext|>