<commit_before><commit_msg>Factor out pixel drawing fn<commit_after><|endoftext|>


<commit_before><commit_msg>Added File 'api-rand.rs' and examples of using 'rand'<commit_after>extern crate rand;

use rand::Rng;

fn main() {
	let mut tmp_rand = rand::thread_rng();

	let boolean: bool = tmp_rand.gen();
	println!("bool: {}", boolean);

	let int_8: i8 = tmp_rand.gen::<i8>();
	let uint_8: u8 = tmp_rand.gen::<u8>();
	println!("int_8: {}\nuint_8: {}", int_8, uint_8);

	let int_32: i32 = tmp_rand.gen::<i32>();
	let uint_32: u32 = tmp_rand.gen::<u32>();
	println!("int_32: {}\nuint_32: {}", int_32, uint_32);

	let float32: f32 = tmp_rand.gen::<f32>();
	let float64: f64 = tmp_rand.gen::<f64>();
	println!("float32: {}\nfloat64: {}", float32, float64);

	let int8_for_range: u8 = tmp_rand.gen_range(0, 127);
	println!("int8_for_range: {}", int8_for_range);

	let tuple = rand::random::<(f32, f32)>();
	println!("tuple: {:?}", tuple);
}<|endoftext|>


<commit_before><commit_msg>Back out the last changeset: paranoia induced swapchain behaviour test<commit_after><|endoftext|>


<commit_before><commit_msg>Example tcp echo server<commit_after>// Example TCP

use std::net::{TcpListener, TcpStream};
use std::thread;

use std::io::Read;
use std::io::Write;

fn handle_client(mut stream: TcpStream) {
    let mut buf;
    loop {
        // clear out the buffer so we don't send garbage
        buf = [0; 512];
        let _ = match stream.read(&mut buf) {
            Err(e) => panic!("Got an error: {}", e),
            Ok(m) => {
                if m == 0 {
                    // we've got an EOF
                    break;
                }
                m
            },
        };

        match stream.write(&buf) {
            Err(_) => break,
            Ok(_) => continue,
        }
    }
}

pub fn run_echo() {
    let listener = TcpListener::bind("127.0.0.1:8888").unwrap();
    for stream in listener.incoming() {
        match stream {
            Err(e) => { println!("failed: {}", e) }
            Ok(stream) => {
                println!("Startin' a connect!");
                thread::spawn(move || {
                    handle_client(stream)
                });
            }
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>Renaming<commit_after>#![macro_escape]

#![macro_export]
macro_rules! cond{
  ($($pred:expr => $body:block),+ _ => $default:block) => (
    $(if $pred $body else)+

    $default
  )
}
<|endoftext|>


<commit_before><commit_msg>Simplify the use of sparkle_filter!<commit_after><|endoftext|>


<commit_before>// Copyright 2013 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.

//! The Rust prelude. Imported into every module by default.

/* Reexported core operators */

pub use either::{Either, Left, Right};
pub use kinds::{Const, Copy, Owned, Durable};
#[cfg(stage0)]
pub use ops::{Add, Sub, Mul, Div, Modulo, Neg, Not};
#[cfg(not(stage0))]
pub use ops::{Add, Sub, Mul, Div, Rem, Neg, Not};
pub use ops::{BitAnd, BitOr, BitXor};
pub use ops::{Drop};
pub use ops::{Shl, Shr, Index};
pub use option::{Option, Some, None};
pub use result::{Result, Ok, Err};

/* Reexported functions */

pub use io::{print, println};

/* Reexported types and traits */

pub use clone::Clone;
pub use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Less, Equal, Greater};
pub use container::{Container, Mutable, Map, Set};
pub use hash::Hash;
pub use old_iter::{BaseIter, ReverseIter, MutableIter, ExtendedIter, EqIter};
pub use old_iter::{CopyableIter, CopyableOrderedIter, CopyableNonstrictIter};
pub use old_iter::{ExtendedMutableIter};
pub use iter::Times;
pub use num::{Num, NumCast};
pub use num::{Orderable, Signed, Unsigned, Round};
pub use num::{Algebraic, Trigonometric, Exponential, Hyperbolic};
pub use num::{Integer, Fractional, Real, RealExt};
pub use num::{Bitwise, BitCount, Bounded};
pub use num::{Primitive, Int, Float};
pub use path::GenericPath;
pub use path::Path;
pub use path::PosixPath;
pub use path::WindowsPath;
pub use ptr::Ptr;
pub use ascii::{Ascii, AsciiCast, OwnedAsciiCast, AsciiStr};
pub use str::{StrSlice, OwnedStr};
pub use from_str::{FromStr};
pub use to_bytes::IterBytes;
pub use to_str::{ToStr, ToStrConsume};
pub use tuple::{CopyableTuple, ImmutableTuple, ExtendedTupleOps};
pub use vec::{CopyableVector, ImmutableVector};
pub use vec::{ImmutableEqVector, ImmutableCopyableVector};
pub use vec::{OwnedVector, OwnedCopyableVector, MutableVector};
pub use io::{Reader, ReaderUtil, Writer, WriterUtil};

/* Reexported runtime types */
pub use comm::{stream, Port, Chan, GenericChan, GenericSmartChan, GenericPort, Peekable};
pub use task::spawn;

/* Reexported modules */

pub use at_vec;
pub use bool;
pub use cast;
pub use char;
pub use cmp;
pub use either;
pub use f32;
pub use f64;
pub use float;
pub use i16;
pub use i32;
pub use i64;
pub use i8;
pub use int;
pub use io;
pub use iter;
pub use old_iter;
pub use libc;
pub use num;
pub use ops;
pub use option;
pub use os;
pub use path;
pub use comm;
pub use unstable;
pub use ptr;
pub use rand;
pub use result;
pub use str;
pub use sys;
pub use task;
pub use to_str;
pub use u16;
pub use u32;
pub use u64;
pub use u8;
pub use uint;
pub use vec;
<commit_msg>auto merge of #6216 : Sodel-the-Vociferous/rust/dralston-6146, r=graydon<commit_after>// Copyright 2013 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.

//! The Rust prelude. Imported into every module by default.

/* Reexported core operators */

pub use either::{Either, Left, Right};
pub use kinds::{Const, Copy, Owned, Durable};
#[cfg(stage0)]
pub use ops::{Add, Sub, Mul, Div, Modulo, Neg, Not};
#[cfg(not(stage0))]
pub use ops::{Add, Sub, Mul, Div, Rem, Neg, Not};
pub use ops::{BitAnd, BitOr, BitXor};
pub use ops::{Drop};
pub use ops::{Shl, Shr, Index};
pub use option::{Option, Some, None};
pub use result::{Result, Ok, Err};

/* Reexported functions */

pub use io::{print, println};

/* Reexported types and traits */

pub use clone::Clone;
pub use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Less, Equal, Greater, Equiv};
pub use container::{Container, Mutable, Map, Set};
pub use hash::Hash;
pub use old_iter::{BaseIter, ReverseIter, MutableIter, ExtendedIter, EqIter};
pub use old_iter::{CopyableIter, CopyableOrderedIter, CopyableNonstrictIter};
pub use old_iter::{ExtendedMutableIter};
pub use iter::Times;
pub use num::{Num, NumCast};
pub use num::{Orderable, Signed, Unsigned, Round};
pub use num::{Algebraic, Trigonometric, Exponential, Hyperbolic};
pub use num::{Integer, Fractional, Real, RealExt};
pub use num::{Bitwise, BitCount, Bounded};
pub use num::{Primitive, Int, Float};
pub use path::GenericPath;
pub use path::Path;
pub use path::PosixPath;
pub use path::WindowsPath;
pub use ptr::Ptr;
pub use ascii::{Ascii, AsciiCast, OwnedAsciiCast, AsciiStr};
pub use str::{StrSlice, OwnedStr};
pub use from_str::{FromStr};
pub use to_bytes::IterBytes;
pub use to_str::{ToStr, ToStrConsume};
pub use tuple::{CopyableTuple, ImmutableTuple, ExtendedTupleOps};
pub use vec::{CopyableVector, ImmutableVector};
pub use vec::{ImmutableEqVector, ImmutableCopyableVector};
pub use vec::{OwnedVector, OwnedCopyableVector, MutableVector};
pub use io::{Reader, ReaderUtil, Writer, WriterUtil};

/* Reexported runtime types */
pub use comm::{stream, Port, Chan, GenericChan, GenericSmartChan, GenericPort, Peekable};
pub use task::spawn;

/* Reexported modules */

pub use at_vec;
pub use bool;
pub use cast;
pub use char;
pub use cmp;
pub use either;
pub use f32;
pub use f64;
pub use float;
pub use i16;
pub use i32;
pub use i64;
pub use i8;
pub use int;
pub use io;
pub use iter;
pub use old_iter;
pub use libc;
pub use num;
pub use ops;
pub use option;
pub use os;
pub use path;
pub use comm;
pub use unstable;
pub use ptr;
pub use rand;
pub use result;
pub use str;
pub use sys;
pub use task;
pub use to_str;
pub use u16;
pub use u32;
pub use u64;
pub use u8;
pub use uint;
pub use vec;
<|endoftext|>


<commit_before>#[doc = "Converts the Rust AST to the rustdoc document model"];

import rustc::syntax::ast;

export from_srv, extract;

fn from_srv(
    srv: astsrv::srv,
    default_name: str
) -> doc::cratedoc {

    #[doc = "Use the AST service to create a document tree"];

    astsrv::exec(srv) {|ctxt|
        extract(ctxt.ast, default_name)
    }
}

fn extract(
    crate: @ast::crate,
    default_name: str
) -> doc::cratedoc {
    ~{
        topmod: top_moddoc_from_crate(crate, default_name),
    }
}

fn top_moddoc_from_crate(
    crate: @ast::crate,
    default_name: str
) -> doc::moddoc {
    moddoc_from_mod(crate.node.module, default_name, ast::crate_node_id)
}

fn moddoc_from_mod(
    module: ast::_mod,
    name: ast::ident,
    id: ast::node_id
) -> doc::moddoc {
    ~{
        id: id,
        name: name,
        path: [],
        brief: none,
        desc: none,
        mods: doc::modlist(
            vec::filter_map(module.items) {|item|
                alt item.node {
                  ast::item_mod(m) {
                    some(moddoc_from_mod(m, item.ident, item.id))
                  }
                  _ {
                    none
                  }
                }
            }),
        fns: doc::fnlist(
            vec::filter_map(module.items) {|item|
                alt item.node {
                  ast::item_fn(decl, _, _) {
                    some(fndoc_from_fn(
                        decl, item.ident, item.id))
                  }
                  _ {
                    none
                  }
                }
            }),
        consts: doc::constlist(
            vec::filter_map(module.items) {|item|
                alt item.node {
                  ast::item_const(_, _) {
                    some(constdoc_from_const(item.ident, item.id))
                  }
                  _ {
                    none
                  }
                }
            }),
        enums: doc::enumlist([])
    }
}

fn fndoc_from_fn(
    decl: ast::fn_decl,
    name: ast::ident,
    id: ast::node_id
) -> doc::fndoc {
    ~{
        id: id,
        name: name,
        brief: none,
        desc: none,
        args: argdocs_from_args(decl.inputs),
        return: {
            desc: none,
            ty: none
        },
        failure: none,
        sig: none
    }
}

#[test]
fn should_extract_fn_args() {
    let source = "fn a(b: int, c: int) { }";
    let ast = parse::from_str(source);
    let doc = extract(ast, "");
    let fn_ = doc.topmod.fns[0];
    assert fn_.args[0].name == "b";
    assert fn_.args[1].name == "c";
}

fn argdocs_from_args(args: [ast::arg]) -> [doc::argdoc] {
    vec::map(args, argdoc_from_arg)
}

fn argdoc_from_arg(arg: ast::arg) -> doc::argdoc {
    ~{
        name: arg.ident,
        desc: none,
        ty: none
    }
}

fn constdoc_from_const(
    name: ast::ident,
    id: ast::node_id
) -> doc::constdoc {
    ~{
        id: id,
        name: name,
        brief: none,
        desc: none,
        ty: none
    }
}

#[test]
fn should_extract_const_name_and_id() {
    let source = "const a: int = 0;";
    let ast = parse::from_str(source);
    let doc = extract(ast, "");
    assert doc.topmod.consts[0].id != 0;
    assert doc.topmod.consts[0].name == "a";
}

#[cfg(test)]
mod tests {

    #[test]
    fn extract_empty_crate() {
        let source = ""; // empty crate
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        // FIXME #1535: These are boxed to prevent a crash
        assert ~doc.topmod.mods == ~doc::modlist([]);
        assert ~doc.topmod.fns == ~doc::fnlist([]);
    }

    #[test]
    fn extract_mods() {
        let source = "mod a { mod b { } mod c { } }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.mods[0].name == "a";
        assert doc.topmod.mods[0].mods[0].name == "b";
        assert doc.topmod.mods[0].mods[1].name == "c";
    }

    #[test]
    fn extract_mods_deep() {
        let source = "mod a { mod b { mod c { } } }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.mods[0].mods[0].mods[0].name == "c";
    }

    #[test]
    fn extract_should_set_mod_ast_id() {
        let source = "mod a { }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.mods[0].id != 0;
    }

    #[test]
    fn extract_fns() {
        let source =
            "fn a() { } \
             mod b { fn c() { } }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.fns[0].name == "a";
        assert doc.topmod.mods[0].fns[0].name == "c";
    }

    #[test]
    fn extract_should_set_fn_ast_id() {
        let source = "fn a() { }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.fns[0].id != 0;
    }

    #[test]
    fn extract_should_use_default_crate_name() {
        let source = "";
        let ast = parse::from_str(source);
        let doc = extract(ast, "burp");
        assert doc.topmod.name == "burp";
    }

    #[test]
    fn extract_from_seq_srv() {
        let source = "";
        let srv = astsrv::mk_srv_from_str(source);
        let doc = from_srv(srv, "name");
        assert doc.topmod.name == "name";
    }
}<commit_msg>rustdoc: Extract enum doc nodes from AST nodes<commit_after>#[doc = "Converts the Rust AST to the rustdoc document model"];

import rustc::syntax::ast;

export from_srv, extract;

fn from_srv(
    srv: astsrv::srv,
    default_name: str
) -> doc::cratedoc {

    #[doc = "Use the AST service to create a document tree"];

    astsrv::exec(srv) {|ctxt|
        extract(ctxt.ast, default_name)
    }
}

fn extract(
    crate: @ast::crate,
    default_name: str
) -> doc::cratedoc {
    ~{
        topmod: top_moddoc_from_crate(crate, default_name),
    }
}

fn top_moddoc_from_crate(
    crate: @ast::crate,
    default_name: str
) -> doc::moddoc {
    moddoc_from_mod(crate.node.module, default_name, ast::crate_node_id)
}

fn moddoc_from_mod(
    module: ast::_mod,
    name: ast::ident,
    id: ast::node_id
) -> doc::moddoc {
    ~{
        id: id,
        name: name,
        path: [],
        brief: none,
        desc: none,
        mods: doc::modlist(
            vec::filter_map(module.items) {|item|
                alt item.node {
                  ast::item_mod(m) {
                    some(moddoc_from_mod(m, item.ident, item.id))
                  }
                  _ {
                    none
                  }
                }
            }),
        fns: doc::fnlist(
            vec::filter_map(module.items) {|item|
                alt item.node {
                  ast::item_fn(decl, _, _) {
                    some(fndoc_from_fn(
                        decl, item.ident, item.id))
                  }
                  _ {
                    none
                  }
                }
            }),
        consts: doc::constlist(
            vec::filter_map(module.items) {|item|
                alt item.node {
                  ast::item_const(_, _) {
                    some(constdoc_from_const(item.ident, item.id))
                  }
                  _ {
                    none
                  }
                }
            }),
        enums: doc::enumlist(
            vec::filter_map(module.items) {|item|
                alt item.node {
                  ast::item_enum(variants, _) {
                    some(enumdoc_from_enum(item.ident, item.id, variants))
                  }
                  _ {
                    none
                  }
                }
            })
    }
}

fn fndoc_from_fn(
    decl: ast::fn_decl,
    name: ast::ident,
    id: ast::node_id
) -> doc::fndoc {
    ~{
        id: id,
        name: name,
        brief: none,
        desc: none,
        args: argdocs_from_args(decl.inputs),
        return: {
            desc: none,
            ty: none
        },
        failure: none,
        sig: none
    }
}

#[test]
fn should_extract_fn_args() {
    let source = "fn a(b: int, c: int) { }";
    let ast = parse::from_str(source);
    let doc = extract(ast, "");
    let fn_ = doc.topmod.fns[0];
    assert fn_.args[0].name == "b";
    assert fn_.args[1].name == "c";
}

fn argdocs_from_args(args: [ast::arg]) -> [doc::argdoc] {
    vec::map(args, argdoc_from_arg)
}

fn argdoc_from_arg(arg: ast::arg) -> doc::argdoc {
    ~{
        name: arg.ident,
        desc: none,
        ty: none
    }
}

fn constdoc_from_const(
    name: ast::ident,
    id: ast::node_id
) -> doc::constdoc {
    ~{
        id: id,
        name: name,
        brief: none,
        desc: none,
        ty: none
    }
}

#[test]
fn should_extract_const_name_and_id() {
    let source = "const a: int = 0;";
    let ast = parse::from_str(source);
    let doc = extract(ast, "");
    assert doc.topmod.consts[0].id != 0;
    assert doc.topmod.consts[0].name == "a";
}

fn enumdoc_from_enum(
    name: ast::ident,
    id: ast::node_id,
    variants: [ast::variant]
) -> doc::enumdoc {
    ~{
        id: id,
        name: name,
        brief: none,
        desc: none,
        variants: variantdocs_from_variants(variants)
    }
}

fn variantdocs_from_variants(
    variants: [ast::variant]
) -> [doc::variantdoc] {
    vec::map(variants, variantdoc_from_variant)
}

fn variantdoc_from_variant(variant: ast::variant) -> doc::variantdoc {
    ~{
        name: variant.node.name,
        desc: none,
        sig: none
    }
}

#[test]
fn should_extract_enums() {
    let source = "enum e { v }";
    let ast = parse::from_str(source);
    let doc = extract(ast, "");
    assert doc.topmod.enums[0].id != 0;
    assert doc.topmod.enums[0].name == "e";
}

#[test]
fn should_extract_enum_variants() {
    let source = "enum e { v }";
    let ast = parse::from_str(source);
    let doc = extract(ast, "");
    assert doc.topmod.enums[0].variants[0].name == "v";
}

#[cfg(test)]
mod tests {

    #[test]
    fn extract_empty_crate() {
        let source = ""; // empty crate
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        // FIXME #1535: These are boxed to prevent a crash
        assert ~doc.topmod.mods == ~doc::modlist([]);
        assert ~doc.topmod.fns == ~doc::fnlist([]);
    }

    #[test]
    fn extract_mods() {
        let source = "mod a { mod b { } mod c { } }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.mods[0].name == "a";
        assert doc.topmod.mods[0].mods[0].name == "b";
        assert doc.topmod.mods[0].mods[1].name == "c";
    }

    #[test]
    fn extract_mods_deep() {
        let source = "mod a { mod b { mod c { } } }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.mods[0].mods[0].mods[0].name == "c";
    }

    #[test]
    fn extract_should_set_mod_ast_id() {
        let source = "mod a { }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.mods[0].id != 0;
    }

    #[test]
    fn extract_fns() {
        let source =
            "fn a() { } \
             mod b { fn c() { } }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.fns[0].name == "a";
        assert doc.topmod.mods[0].fns[0].name == "c";
    }

    #[test]
    fn extract_should_set_fn_ast_id() {
        let source = "fn a() { }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.fns[0].id != 0;
    }

    #[test]
    fn extract_should_use_default_crate_name() {
        let source = "";
        let ast = parse::from_str(source);
        let doc = extract(ast, "burp");
        assert doc.topmod.name == "burp";
    }

    #[test]
    fn extract_from_seq_srv() {
        let source = "";
        let srv = astsrv::mk_srv_from_str(source);
        let doc = from_srv(srv, "name");
        assert doc.topmod.name == "name";
    }
}<|endoftext|>


<commit_before><commit_msg>Add test for uint and negative literals as discriminants<commit_after>enum Animal {
    Cat = 0u,
    Dog = 1u,
    Horse = 2u,
    Snake = 3u
}

enum Hero {
    Batman = -1,
    Superman = -2,
    Ironman = -3,
    Spiderman = -4
}

fn main() {
    let pet: Animal = Snake;
    let hero: Hero = Superman;
    assert!(pet as uint == 3);
    assert!(hero as int == -2);
}
<|endoftext|>


<commit_before><commit_msg>crav1e: First iteration<commit_after>extern crate rav1e;

use std::slice;
use std::sync::Arc;

use std::ffi::CStr;
use std::os::raw::c_char;
use std::os::raw::c_int;

pub struct RaFrame(Arc<rav1e::Frame>);

pub struct RaConfig {
    cfg: rav1e::Config,
    last_err: Option<rav1e::EncoderStatus>,
}

pub struct RaContext {
    ctx: rav1e::Context,
    last_err: Option<rav1e::EncoderStatus>,
}

type RaFrameType = rav1e::FrameType;

#[repr(C)]
pub struct RaPacket {
    pub data: *const u8,
    pub len: usize,
    pub number: usize,
    pub frame_type: RaFrameType,
}

#[no_mangle]
pub unsafe extern "C" fn rav1e_config_default(
    width: usize,
    height: usize,
    bit_depth: usize,
    chroma_sampling: rav1e::ChromaSampling,
    timebase: rav1e::Ratio,
) -> *mut RaConfig {
    let cfg = rav1e::Config {
        frame_info: rav1e::FrameInfo {
            width,
            height,
            bit_depth,
            chroma_sampling,
        },
        timebase,
        enc: Default::default(),
    };

    let c = Box::new(RaConfig {
        cfg,
        last_err: None,
    });

    Box::into_raw(c)
}

#[no_mangle]
pub unsafe extern "C" fn rav1e_config_drop(cfg: *mut RaConfig) {
    let _ = Box::from_raw(cfg);
}

#[no_mangle]
pub unsafe extern "C" fn rav1e_config_parse(
    cfg: *mut RaConfig,
    key: *const c_char,
    value: *const c_char,
) -> c_int {
    let key = CStr::from_ptr(key).to_string_lossy();
    let value = CStr::from_ptr(value).to_string_lossy();

    (*cfg)
        .cfg
        .parse(&key, &value)
        .map(|_v| {
            (*cfg).last_err = None;
            0
        }).map_err(|e| (*cfg).last_err = Some(e))
        .unwrap_or(-1)
}

#[no_mangle]
pub unsafe extern "C" fn rav1e_context_new(cfg: *const RaConfig) -> *mut RaContext {
    let ctx = RaContext {
        ctx: (*cfg).cfg.new_context(),
        last_err: None,
    };

    Box::into_raw(Box::new(ctx))
}

#[no_mangle]
pub unsafe extern "C" fn rav1e_context_drop(ctx: *mut RaContext) {
    let _ = Box::from_raw(ctx);
}

#[no_mangle]
pub unsafe extern "C" fn rav1e_frame_new(ctx: *const RaContext) -> *mut RaFrame {
    let f = (*ctx).ctx.new_frame();
    let frame = Box::new(RaFrame(f));

    Box::into_raw(frame)
}

#[no_mangle]
pub unsafe extern "C" fn rav1e_frame_drop(ctx: *mut RaFrame) {
    let _ = Arc::from_raw(ctx);
}

#[no_mangle]
pub unsafe extern "C" fn rav1e_send_frame(ctx: *mut RaContext, frame: *const RaFrame) -> c_int {
    let frame = if frame.is_null() {
        None
    } else {
        Some((*frame).0.clone())
    };

    (*ctx)
        .ctx
        .send_frame(frame)
        .map(|_v| {
            (*ctx).last_err = None;
            0
        }).map_err(|e| (*ctx).last_err = Some(e))
        .unwrap_or(-1)
}

#[no_mangle]
pub unsafe extern "C" fn rav1e_receive_packet(
    ctx: *mut RaContext,
    pkt: *mut *mut RaPacket,
) -> c_int {
    (*ctx)
        .ctx
        .receive_packet()
        .map(|p| {
            (*ctx).last_err = None;
            let packet = RaPacket {
                data: p.data.as_ptr(),
                len: p.data.len(),
                number: p.number,
                frame_type: p.frame_type,
            };
            *pkt = Box::into_raw(Box::new(packet));
            0
        }).map_err(|e| (*ctx).last_err = Some(e))
        .unwrap_or(-1)
}

#[no_mangle]
pub unsafe extern fn rav1e_packet_drop(pkt: *mut RaPacket) {
    let _ = Box::from_raw(pkt);
}

#[no_mangle]
pub unsafe extern "C" fn rav1e_frame_fill_plane(
    frame: *mut RaFrame,
    plane: usize,
    data: *const u8,
    data_len: usize,
    stride: usize,
    bytewidth: usize,
) {
    let input = Arc::get_mut(&mut (*frame).0).unwrap();
    let data_slice = slice::from_raw_parts(data, data_len);

    input.planes[plane].copy_from_raw_u8(data_slice, stride, bytewidth);
}
<|endoftext|>


<commit_before>extern crate orbclient;

use super::render;

pub struct Window {
    width: u32,
    height: u32,
    window: Box<orbclient::window::Window>
}

impl Window {
    pub fn new(x: i32, y: i32, width: u32, height: u32, title: &str) -> Window {
        Window {
            width: width,
            height: height,
            window: Box::new(orbclient::window::Window::new_flags(x, y, width, height, title, true)).unwrap()
        }
    }

    pub fn apply_buf(&mut self, framebuffer: &render::Framebuffer) {
        for x in 0..framebuffer.width as u32 {
            for y in 0..framebuffer.height as u32 {
                let pixel = framebuffer.get_pixel(x, y);

                if pixel.is_none() {
                    continue;
                } else {
                    self.window.pixel(x as i32, y as i32, pixel.unwrap().as_orbclient());
                }
            }
        }
    }

    pub fn sync(&mut self) {
        self.window.sync();
    }

    pub fn clear(&mut self) {
        self.window.clear();
    }
}
<commit_msg>Added set_pixel and apply_z_buf<commit_after>extern crate orbclient;

use super::render;

pub struct Window {
    width: u32,
    height: u32,
    window: Box<orbclient::window::Window>
}

impl Window {
    pub fn new(x: i32, y: i32, width: u32, height: u32, title: &str) -> Window {
        Window {
            width: width,
            height: height,
            window: Box::new(orbclient::window::Window::new_flags(x, y, width, height, title, true)).unwrap()
        }
    }

    pub fn apply_buf(&mut self, framebuffer: &render::Framebuffer) {
        for x in 0..framebuffer.width as u32 {
            for y in 0..framebuffer.height as u32 {
                let pixel = framebuffer.get_pixel(x, y);

                if pixel.is_none() {
                    continue;
                } else {
                    self.window.pixel(x as i32, y as i32, pixel.unwrap().color.as_orbclient());
                }
            }
        }
    }

    pub fn apply_z_buf(&mut self, framebuffer: &render::Framebuffer) {
        for x in 0..framebuffer.width as u32 {
            for y in 0..framebuffer.height as u32 {
                let pixel = framebuffer.get_pixel(x, y);

                if pixel.is_none() {
                    continue;
                } else {
                    let z_color = (((1.0 / -pixel.unwrap().z) * 255.0) + 255.0) as u8;
                    self.window.pixel(x as i32, y as i32, render::Color::new(z_color, z_color, z_color).as_orbclient());
                }
            }
        }
    }

    pub fn get_pixel(&mut self, x: i32, y: i32) -> render::Color {
        unimplemented!();
    }

    pub fn set_pixel(&mut self, x: i32, y: i32, color: &render::Color) {
        self.window.pixel(x as i32, y as i32, color.as_orbclient());
    }

    pub fn sync(&mut self) {
        self.window.sync();
    }

    pub fn clear(&mut self) {
        self.window.clear();
    }
}
<|endoftext|>


<commit_before><commit_msg>day 7<commit_after><|endoftext|>


<commit_before><commit_msg>Create initial unit test suite, refactor parsing for multiple array items<commit_after><|endoftext|>


<commit_before><commit_msg>:sparkles: Make enable to consider user timezone<commit_after><|endoftext|>


<commit_before><commit_msg>math functions<commit_after>use num::rational::Ratio;

use std::f32::{atan2, sqrt, sin, cos, tan, round};
use std::f32::consts::PI;
use std::fmt::{Show, Formatter, Result};

type coord = f32;
type rawAngle = f32;

pub struct vector2 {
	x: coord,
	y: coord,
}

impl vector2 {
	pub fn null() -> vector2 {
		vector2 { x: 0 as coord , y: 0 as coord }
	}

	pub fn new(x: coord, y: coord) -> vector2 {
		vector2 { x: x, y: y }
	}

	pub fn normalize(&self) -> vector2 {
		let len = self.len();

		match len {
			0. => vector2::null(),
			_ => vector2 {x: self.x / len, y : self.y / len}
		}
	}

	pub fn len_squared(&self) -> f32 {
		self.x * self.x + self.y * self.y
	}

	pub fn len(&self) -> f32 {
		sqrt(self.len_squared())
	}

	pub fn polar(&self) -> Polar{
		Polar::new(Angle::rad(atan2(self.y, self.x)), self.len())
	}

}

impl Add<vector2, vector2> for vector2 {
	fn add(&self, rhs: &vector2) -> vector2 {
		vector2 { x : self.x + rhs.x,  y : self.y + rhs.y }
	}
}

impl Sub<vector2, vector2> for vector2 {
	fn sub(&self, rhs: &vector2) -> vector2 {
		vector2 { x : self.x - rhs.x,  y : self.y - rhs.y }
	}
}

impl Mul<f32, vector2> for vector2 {
	fn mul(&self, rhs: &f32) -> vector2 {
		vector2 { x : self.x * (*rhs),  y : self.y * (*rhs) }
	}
}

impl Div<f32, vector2> for vector2{
	fn div(&self, rhs: &f32) -> vector2 {
		vector2 { x : self.x / (*rhs),  y : self.y / (*rhs) }
	}
}

impl Neg<vector2> for vector2 {
	fn neg(&self) -> vector2 {
		vector2 { x: -self.x, y: -self.y }
	}
}

impl Eq for vector2{
	fn eq(&self, other: &vector2) -> bool {
		self.x == other.x && self.y == other.y
	}

	fn ne(&self, other: &vector2) -> bool {
		self.x != other.x || self.y != other.y
	}
}

impl Show for vector2 {
	fn fmt(&self, formatter: &mut Formatter) -> Result {
		let dirStr = AngleToDirStr(&self.polar().angle);
		write!(formatter.buf, "\\{ {} | x: {:.2}, y:{:.2} \\}", dirStr, self.x, self.y)
	}
}

pub fn dot(v1: vector2, v2: vector2) -> f32 {
	v1.x * v2.x + v1.y * v2.y
}

//Angle---
pub struct Angle {
	//in radians
	theta: rawAngle,
}

impl Angle {

	//constructors---
	pub fn deg(deg: rawAngle) -> Angle {
		Angle { theta: Angle::clamp(deg.to_radians()) }
	}
	pub fn rad(rad: rawAngle) -> Angle{
		Angle { theta: Angle::clamp(rad) }
	}

	pub fn sin(&self) -> f32 {
		sin(self.theta)
	}

	pub fn cos(&self) -> f32 {
		cos(self.theta)
	}

	pub fn tan(&self) -> f32 {
		tan(self.theta)
	}

	fn clamp(rad: rawAngle) -> rawAngle {
		let tolerance = 2 as rawAngle;
		let limit = (PI as rawAngle) *  tolerance;

		if rad > limit || rad < -limit {
			return angle_to_principal_domain(rad);
		}
		return rad
	}
}

impl Add<Angle, Angle> for Angle {
	fn add(&self, rhs: &Angle) -> Angle {
		Angle { theta : Angle::clamp(self.theta + rhs.theta) }
	}
}

impl Sub<Angle, Angle> for Angle {
	fn sub(&self, rhs: &Angle) -> Angle {
		Angle { theta : Angle::clamp(self.theta - rhs.theta) }
	}
}

impl Mul<f32, Angle> for Angle {
	fn mul(&self, rhs: &f32) -> Angle {
		Angle { theta : Angle::clamp(self.theta * *rhs) }
	}
}

impl Div<f32, Angle> for Angle{
	fn div(&self, rhs: &f32) -> Angle {
		//clamp if divided by negative values
		Angle { theta : Angle::clamp(self.theta / *rhs) }
	}
}

impl Neg<Angle> for Angle {
	fn neg(&self) -> Angle {
		Angle { theta : Angle::clamp(-self.theta) }
	}
}

impl Show for Angle {
	fn fmt(&self, formatter: &mut Formatter) -> Result {

		let normalizedAngle = angle_to_principal_domain(self.theta);
		let simplificationFactor = 6;
		let simplifiedNumerator = (normalizedAngle / PI * simplificationFactor as f32).round() as int;
		let ratio = Ratio::new(simplifiedNumerator, simplificationFactor);

		let n = *ratio.numer();
		let d = *ratio.denom();

		let degrees = (self.theta * 180f32 / PI);

		let radStr = match (n, d) {
			(0, _) => ~"0",
			(1, 1) => ~"π",
			(1, _) => format!("π/{}", d),
			(_, 1) => format!("{}π", n),
			_ => format!("{}π/{}", n, d),
		};

		let dirStr = AngleToDirStr(self);

		write!(formatter.buf, "\\{ {} | rad: {} | {:.2}° \\}", dirStr, radStr, degrees)

	}
}

fn AngleToDirStr(Angle : &Angle) -> ~str {
	let principalAngle = angle_to_principal_domain(Angle.theta);
	let degrees = (principalAngle * 180f32 / PI);

	match (degrees / 45.).floor() as int {
		0 => ~"→",
		1 => ~"↗",
		2 => ~"↑",
		3 => ~"↖",
		4 => ~"←",
		5 => ~"↙",
		6 => ~"↓",
		7 => ~"↘",
		_ => ~"⟳"
	}
}

//polar coordinates-----------------

#[deriving(Show)]
pub struct Polar {
	angle: Angle,
	len: f32
}

impl Polar {
	pub fn new(angle: Angle, len: f32) -> Polar {
		Polar { angle: angle, len: len }
	}

	pub fn unit(angle: Angle) -> Polar {
		Polar { angle: angle, len: 1. }
	}

	pub fn unit_rad(rad: f32) -> Polar {
		Polar { angle: Angle::rad(rad), len: 1. }
	}

	pub fn unit_deg(deg: f32) -> Polar {
		Polar { angle: Angle::deg(deg), len: 1. }
	}

	//member functions-----
	pub fn cartesian(&self) -> vector2 {
		vector2::new(self.angle.cos() * self.len, self.angle.sin() * self.len)
	}

	pub fn normalize(&self) -> Polar {
		Polar { angle: self.angle, len: 1.}
	}
}

//polar by polar multiplication
impl Mul<Polar, Polar> for Polar {
	fn mul(&self, rhs: &Polar) -> Polar {
		Polar { angle: self.angle + rhs.angle, len: self.len * rhs.len }
	}
}

impl Div<Polar, Polar> for Polar{
	fn div(&self, rhs: &Polar) -> Polar {
		Polar { angle: self.angle - rhs.angle, len: self.len / rhs.len }
	}
}

impl Neg<Polar> for Polar {
	fn neg(&self) -> Polar {
		Polar { angle : -self.angle, len: self.len }
	}
}

//auxiliary helper functions--------------------------------
fn angle_to_principal_domain(rad: rawAngle) -> rawAngle{
	let twoPi = (2. * PI) as rawAngle;

	let mut clamped : rawAngle = rad % twoPi;

	if clamped < 0. {
		clamped += twoPi;
	}

	assert!(clamped >= 0 as rawAngle && clamped < twoPi);
	return clamped
}

//tests

#[test]
fn test_vector_cons() {
	let v1 = vector2::null();
	let v2 = vector2::new(3.0, 4.0);

	assert!(v1.x == 0. && v1.y == 0.);
	assert!(v2.x == 3. && v2.y == 4.);
}

#[test]
fn test_vector_normalize() {
	let v1 = vector2::null();
	let v2 = vector2::new(3.0, 4.0);
	let v3 = vector2::new(1.0, 0.0);

	assert!(v1.normalize() == v1);
	assert!(v3.normalize() == v3);

	assert!(v2.normalize().x == 3.0 / 5.0 && v2.normalize().y == 4.0 / 5.0)
}

#[test]
fn test_vector_len() {
	let v1 = vector2::null();
	let v2 = vector2::new(3.0, 4.0);
	let v3 = vector2::new(1.0, 0.0);
	let v4 = vector2::new(1.0, 1.0);

	assert!(v1.len() == 0. && v1.len_squared() == 0.);
	assert!(v2.len() == 5.);
	assert!(v3.len_squared() == 1. && v3.len() == 1.);
	assert!(v4.len_squared() == 2.);
}

#[test]
fn test_vector_operators() {
	let v1 = vector2::null();
	let v2 = vector2::new(3.0, 4.0);
	let v3 = vector2::new(1.0, 0.0);
	let v4 = vector2::new(1.0, 1.0);
	let v5 = vector2::new(0.0, 1.0);

	assert!(v1 + v2 == v2);
	assert!(v1 + v1 == v1);
	assert!(v4 + v4 == v4 * 2.);
	assert!(v3 + v4 == vector2::new(2.0, 1.0));

	assert!(v2 - v1 == v2);
	assert!(v2 - v2 == v1);
	assert!(v4 - v3 == vector2::new(0.0, 1.0));

	assert!(v2 != v1);
	assert!(v3 != v4 && v5 != v4 && v5 != v3);
}

#[test]
fn test_cartesian_polar() {
	let v1 = vector2::null();
	let a1 = v1.polar();

	assert!(a1.len == 0.);
	assert!(a1.cartesian() == v1);

	let a1 = Polar::new(Angle::deg(90.), 2.);

	assert!(a1.cartesian().len() == 2.);
	assert!(a1.cartesian().polar() == a1);
	assert!(a1.cartesian().y == 2. && a1.cartesian().x == 0.);

}
<|endoftext|>


<commit_before><commit_msg>a bit<commit_after>fn reverse_word(s: String) -> String {
    let mut result: Vec<char> = vec![];
    let mut cache: Vec<char> = vec![];

    for c in s.chars() {
        if c == ' ' {
            result.append(&mut cache);
            result.push(c);
        } else {
            let mut temp = vec![c];
            temp.append(&mut cache);
            cache = temp;
        }
    }

    result.append(&mut cache);
    result.into_iter().collect()
}

fn main() {
    println!("{}", reverse_word("  hello world ! ".to_string()));
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 174<commit_after>// https://leetcode.com/problems/dungeon-game/
pub fn calculate_minimum_hp(dungeon: Vec<Vec<i32>>) -> i32 {
    todo!()
}

fn main() {
    println!(
        "{}",
        calculate_minimum_hp(vec![vec![-2, -3, 3], vec![-5, -10, 1], vec![10, 30, -5]])
    ); // 7
    println!("{}", calculate_minimum_hp(vec![vec![0]])); // 1
}
<|endoftext|>


<commit_before><commit_msg>Initial commit with skeleton<commit_after>//============================================================================
//
// A simple Mandelbrot image generator in Rust
//
// Copyright (c) 2014 Gavin Baker <gavinb@antonym.org>
// Published under the MIT license
//
// Packages required:
//
// - OpenGL
// - GLFW
// - cgmath
//
// export RUST_PATH=~/src/cgmath-rs:~/src/glfw-rs:~/src/rust-opengles
//
//============================================================================

extern crate gl;
extern crate glfw;
extern crate cgmath;

use gl::gl2;

use cgmath::vector::Vec3;
use cgmath::aabb::Aabb3;

use std::libc;

#[feature(link_args)]
#[link(name = "OpenGL")]

type Vec3f = Vec3<f32>;
type AABB3f = Aabb3<f32>;

static vertex_shader_source: &'static str = "
#version 150

in vec2 position;
in vec3 color;

out vec3 Color;

void main()
{
    Color = color;
    gl_Position = vec4(position, 0.0, 1.0);
}
";

static fragment_shader_source: &'static str = "
#version 150

in vec3 Color;
out vec4 outColor;

void main()
{
    outColor = vec4(Color, 1.0);
}";

struct Particle {
    position: Vec3f,
    lastPosition: Vec3f,
    velocity: Vec3f,
    colour: Vec3f,
    energy: f32,
    size: f32,
}

struct ParticleSystem {
    // texture: Texture,
    // blendMode: BlendMode,
    // systemType: int,
    particles: ~[Particle],
    // shapes: [Shape],
    aliveCount: uint,
    boundingBox: AABB3f,
}

struct ErrorContext;
impl glfw::ErrorCallback for ErrorContext {
    fn call(&self, _: glfw::Error, description: ~str) {
        println!("GLFW Error: {:s}", description);
    }
}

struct WindowController<'a> {
    window: &'a glfw::Window,
    vertices: ~[f32],
    vao: ~[gl2::GLuint],
    vbo: ~[gl2::GLuint],
    vertex_shader: gl2::GLuint,
    fragment_shader: gl2::GLuint,
    shader_program: gl2::GLuint,
}

struct KeyController;

impl glfw::KeyCallback for KeyController {
    fn call(&self, window: &glfw::Window, key: glfw::Key, _: libc::c_int, action: glfw::Action, _: glfw::Modifiers) {
        if action == glfw::Press && key == glfw::KeyEscape {
            window.set_should_close(true);
        }
    }
}

struct MandelEngine {
    re0: f32,
    re1: f32,
    im0: f32,
    im1: f32,
    delta: f32,
}

impl MandelEngine {

    fn new() -> MandelEngine {
        MandelEngine(re0=-2.0, re1=2.0, im0=-2.0, im1=2.0)
    }

    // Evalute entire region
    fn process() {
    }

    // Evaluate a single point
    fn mandel(z: Complex64) -> int {
        let maxiter: int = 80;
        let mut c: Complex64 = z;
        for n in range(0, maxiter) {
            if c.norm() > 2.0 {
                return n;
            }
            c = c*c+z;
        }
        return maxiter;
    }
}

impl<'a> WindowController<'a> {
    fn new(window: &'a glfw::Window) -> WindowController<'a> {
        let mut wc = WindowController { window: window,
                                        vao: ~[0],
                                        vbo: ~[0],
                                        vertices: ~[],
                                        vertex_shader: 0,
                                        fragment_shader: 0,
                                        shader_program: 0,
        };

        let (width, height) =  wc.window.get_framebuffer_size();

        gl2::viewport(0, 0, width as i32, height as i32);

        println!("Viewport: {} x {}", width, height);

        wc.vertices = ~[
            0.0,  0.5, 1.0, 0.0, 0.0,
            0.5, -0.5, 0.0, 1.0, 0.0,
            -0.5, -0.5, 0.0, 0.0, 1.0,
            ];

        // VAO

        wc.vao = gl2::gen_vertex_arrays(1);
        gl2::bind_vertex_array(wc.vao[0]);

        // VBO

        wc.vbo = gl2::gen_buffers(1);
        gl2::bind_buffer(gl2::ARRAY_BUFFER, wc.vbo[0]);
        gl2::buffer_data(gl2::ARRAY_BUFFER, wc.vertices, gl2::STATIC_DRAW);

        // Vertex Shader

        wc.vertex_shader = gl2::create_shader(gl2::VERTEX_SHADER);
        gl2::shader_source(wc.vertex_shader, [vertex_shader_source.to_owned().into_bytes()]);

        gl2::compile_shader(wc.vertex_shader);

        let status = gl2::get_shader_iv(wc.vertex_shader, gl2::COMPILE_STATUS);

        if status != gl2::TRUE as i32 {
            let log = gl2::get_shader_info_log(wc.vertex_shader);
            println!("vertex_shader compile error {} = {}", status, log);
        }

        // Fragment Shader

        wc.fragment_shader = gl2::create_shader(gl2::FRAGMENT_SHADER);
        gl2::shader_source(wc.fragment_shader, [fragment_shader_source.to_owned().into_bytes()]);
        gl2::compile_shader(wc.fragment_shader);

        let status = gl2::get_shader_iv(wc.fragment_shader, gl2::COMPILE_STATUS);

        if status != gl2::TRUE as i32 {
            let log = gl2::get_shader_info_log(wc.fragment_shader);
            println!("fragment_shader compile error {} = {}", status, log);
        }

        // Link

        wc.shader_program = gl2::create_program();

        gl2::attach_shader(wc.shader_program, wc.vertex_shader);
        gl2::attach_shader(wc.shader_program, wc.fragment_shader);

        gl2::link_program(wc.shader_program);

        gl2::use_program(wc.shader_program);

        let err = gl2::get_error();
        if err != 0 {
            println!("after link err1 = 0x{:x}", err);
        }

        // Attributes

        let pos_attrib = gl2::get_attrib_location(wc.shader_program, "position");
        gl2::enable_vertex_attrib_array(pos_attrib as gl2::GLuint);
        gl2::vertex_attrib_pointer_f32(pos_attrib as gl2::GLuint, 2, false, 5*4, 0);

        let col_attrib = gl2::get_attrib_location(wc.shader_program, "color");
        gl2::enable_vertex_attrib_array(col_attrib as gl2::GLuint);
        gl2::vertex_attrib_pointer_f32(col_attrib as gl2::GLuint, 3, false, 5*4, 2*4);

        // Uniforms

        wc.uni_color = gl2::get_uniform_location(wc.shader_program, "triangleColor");

        let err = gl2::get_error();
        if err != 0 {
            println!("attrib err = {:x}", err);
        }

        wc
    }

    fn draw(&self) {

        // Clear

        gl2::clear_color(0.4, 0.4, 0.4, 1.0);
        gl2::clear(gl2::COLOR_BUFFER_BIT);

        // Animate

        let time = glfw::get_time();
        glUniform3f(wc.uni_color, (sin(time * 4.0) + 1.0) / 2.0, 0.0, 0.0);

        // Draw!

        gl2::draw_arrays(gl2::TRIANGLES, 0, 3);

        let err = gl2::get_error();
        if err != 0 {
            println!("draw err = 0x{:x}", err);
        }

        self.window.swap_buffers();
    }

    fn uninit(&mut self) {

        // Cleanup

        gl2::delete_program(self.shader_program);
        gl2::delete_shader(self.fragment_shader);
        gl2::delete_shader(self.vertex_shader);

        gl2::delete_buffers(self.vbo);

        // @todo Missing from bindings
        //gl2::delete_vertex_arrays(vao);
    }
}

#[start]
fn start(argc: int, argv: **u8) -> int {
    std::rt::start_on_main_thread(argc, argv, main)
}

fn main() {

    println(glfw::get_version().to_str());
    println!("GLFW version: {:s}", glfw::get_version_string());

    glfw::start(proc() {

        glfw::window_hint::context_version_major(3);
        glfw::window_hint::context_version_minor(2);
        glfw::window_hint::opengl_forward_compat(true);
        glfw::window_hint::opengl_profile(glfw::OpenGlCoreProfile);

        glfw::window_hint::resizable(false);

        let window = glfw::Window::create(640, 480,
                                          "MandelRust",
                                          glfw::Windowed)
            .expect("Failed to create GLFW window.");

        window.make_context_current();

        let win_ctrl = ~WindowController::new(&window);

        window.set_key_callback(~KeyController);

        while !window.should_close() {
            win_ctrl.draw();

            glfw::poll_events();
        }
    });
}
<|endoftext|>


<commit_before><commit_msg>Fix: view entries sorted<commit_after><|endoftext|>


<commit_before>#![cfg(feature = "s3")]

extern crate env_logger;
#[macro_use]
extern crate log;
extern crate time;

#[macro_use]
extern crate rusoto;

use std::io::Read;
use std::fs::File;
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::s3::S3Helper;

#[test]
fn list_buckets_tests() {
    let _ = env_logger::init();
    let s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);
    let response = s3.list_buckets().unwrap();
    info!("Got list of buckets: {:?}", response);
    for q in response.buckets {
        info!("Existing bucket: {:?}", q.name);
    }
}

#[test]
fn put_object_test() {
    let s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);
    let mut f = File::open("tests/sample-data/no_credentials").unwrap();
    let mut contents : Vec<u8> = Vec::new();
    match f.read_to_end(&mut contents) {
        Err(why) => panic!("Error opening file to send to S3: {}", why),
        Ok(_) => {
            s3.put_object("rusototester", "no_credentials", &contents).unwrap();
        }
    }
}

// Dependent on the file being there or it'll break.
#[test]
fn get_object_test() {
    let s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);
    s3.get_object("rusototester", "no_credentials2").unwrap();
}

#[test]
fn delete_object_test() {
    let s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);
    s3.delete_object("rusototester", "no_credentials").unwrap();
}
<commit_msg>Adds more S3 integration tests.<commit_after>#![cfg(feature = "s3")]

extern crate env_logger;
#[macro_use]
extern crate log;
extern crate time;

#[macro_use]
extern crate rusoto;

use std::io::Read;
use std::fs::File;
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::s3::{S3Helper, S3Client, ListObjectsRequest};

#[test]
fn list_buckets_tests() {
    let _ = env_logger::init();
    let s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);
    let response = s3.list_buckets().unwrap();
    info!("Got list of buckets: {:?}", response);
    for q in response.buckets {
        info!("Existing bucket: {:?}", q.name);
    }
}

#[test]
fn put_object_test() {
    let s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);
    let mut f = File::open("tests/sample-data/no_credentials").unwrap();
    let mut contents : Vec<u8> = Vec::new();
    match f.read_to_end(&mut contents) {
        Err(why) => panic!("Error opening file to send to S3: {}", why),
        Ok(_) => {
            s3.put_object("rusototester", "no_credentials", &contents).unwrap();
        }
    }
}

#[test]
fn list_objects_test() {
    let _ = env_logger::init();
    let bare_s3 = S3Client::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);
    let mut list_request = ListObjectsRequest::default(); // need to set bucket
    list_request.bucket = "rusototester".to_string();
    let result = bare_s3.list_objects(&list_request).unwrap();
    println!("result is {:?}", result);
}

// Dependent on the file being there or it'll break.
#[test]
fn get_object_test() {
    let s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);
    s3.get_object("rusototester", "no_credentials2").unwrap();
}

#[test]
fn delete_object_test() {
    let s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);
    s3.delete_object("rusototester", "no_credentials").unwrap();
}
<|endoftext|>


<commit_before><commit_msg>sdk: add missing policy.rs file<commit_after>// This file is generated by rust-protobuf 2.8.0. Do not edit
// @generated

// https://github.com/Manishearth/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy::all)]

#![cfg_attr(rustfmt, rustfmt_skip)]

#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(trivial_casts)]
#![allow(unsafe_code)]
#![allow(unused_imports)]
#![allow(unused_results)]
//! Generated file from `oak/proto/policy.proto`

use protobuf::Message as Message_imported_for_functions;
use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions;

/// Generated files are compatible only with the same version
/// of protobuf runtime.
const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_8_0;

#[derive(PartialEq,Clone,Default)]
pub struct Label {
    // message fields
    pub secrecy_tags: ::protobuf::RepeatedField<Tag>,
    pub integrity_tags: ::protobuf::RepeatedField<Tag>,
    // special fields
    pub unknown_fields: ::protobuf::UnknownFields,
    pub cached_size: ::protobuf::CachedSize,
}

impl<'a> ::std::default::Default for &'a Label {
    fn default() -> &'a Label {
        <Label as ::protobuf::Message>::default_instance()
    }
}

impl Label {
    pub fn new() -> Label {
        ::std::default::Default::default()
    }

    // repeated .oak.policy.Tag secrecy_tags = 1;

    pub fn get_secrecy_tags(&self) -> &[Tag] {
        &self.secrecy_tags
    }
    pub fn clear_secrecy_tags(&mut self) {
        self.secrecy_tags.clear();
    }

    // Param is passed by value, moved
    pub fn set_secrecy_tags(&mut self, v: ::protobuf::RepeatedField<Tag>) {
        self.secrecy_tags = v;
    }

    // Mutable pointer to the field.
    pub fn mut_secrecy_tags(&mut self) -> &mut ::protobuf::RepeatedField<Tag> {
        &mut self.secrecy_tags
    }

    // Take field
    pub fn take_secrecy_tags(&mut self) -> ::protobuf::RepeatedField<Tag> {
        ::std::mem::replace(&mut self.secrecy_tags, ::protobuf::RepeatedField::new())
    }

    // repeated .oak.policy.Tag integrity_tags = 2;

    pub fn get_integrity_tags(&self) -> &[Tag] {
        &self.integrity_tags
    }
    pub fn clear_integrity_tags(&mut self) {
        self.integrity_tags.clear();
    }

    // Param is passed by value, moved
    pub fn set_integrity_tags(&mut self, v: ::protobuf::RepeatedField<Tag>) {
        self.integrity_tags = v;
    }

    // Mutable pointer to the field.
    pub fn mut_integrity_tags(&mut self) -> &mut ::protobuf::RepeatedField<Tag> {
        &mut self.integrity_tags
    }

    // Take field
    pub fn take_integrity_tags(&mut self) -> ::protobuf::RepeatedField<Tag> {
        ::std::mem::replace(&mut self.integrity_tags, ::protobuf::RepeatedField::new())
    }
}

impl ::protobuf::Message for Label {
    fn is_initialized(&self) -> bool {
        for v in &self.secrecy_tags {
            if !v.is_initialized() {
                return false;
            }
        };
        for v in &self.integrity_tags {
            if !v.is_initialized() {
                return false;
            }
        };
        true
    }

    fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
        while !is.eof()? {
            let (field_number, wire_type) = is.read_tag_unpack()?;
            match field_number {
                1 => {
                    ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.secrecy_tags)?;
                },
                2 => {
                    ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.integrity_tags)?;
                },
                _ => {
                    ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
                },
            };
        }
        ::std::result::Result::Ok(())
    }

    // Compute sizes of nested messages
    #[allow(unused_variables)]
    fn compute_size(&self) -> u32 {
        let mut my_size = 0;
        for value in &self.secrecy_tags {
            let len = value.compute_size();
            my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
        };
        for value in &self.integrity_tags {
            let len = value.compute_size();
            my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
        };
        my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
        self.cached_size.set(my_size);
        my_size
    }

    fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
        for v in &self.secrecy_tags {
            os.write_tag(1, ::protobuf::wire_format::WireTypeLengthDelimited)?;
            os.write_raw_varint32(v.get_cached_size())?;
            v.write_to_with_cached_sizes(os)?;
        };
        for v in &self.integrity_tags {
            os.write_tag(2, ::protobuf::wire_format::WireTypeLengthDelimited)?;
            os.write_raw_varint32(v.get_cached_size())?;
            v.write_to_with_cached_sizes(os)?;
        };
        os.write_unknown_fields(self.get_unknown_fields())?;
        ::std::result::Result::Ok(())
    }

    fn get_cached_size(&self) -> u32 {
        self.cached_size.get()
    }

    fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
        &self.unknown_fields
    }

    fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
        &mut self.unknown_fields
    }

    fn as_any(&self) -> &dyn (::std::any::Any) {
        self as &dyn (::std::any::Any)
    }
    fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) {
        self as &mut dyn (::std::any::Any)
    }
    fn into_any(self: Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {
        self
    }

    fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
        Self::descriptor_static()
    }

    fn new() -> Label {
        Label::new()
    }

    fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
        static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
            lock: ::protobuf::lazy::ONCE_INIT,
            ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
        };
        unsafe {
            descriptor.get(|| {
                let mut fields = ::std::vec::Vec::new();
                fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<Tag>>(
                    "secrecy_tags",
                    |m: &Label| { &m.secrecy_tags },
                    |m: &mut Label| { &mut m.secrecy_tags },
                ));
                fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<Tag>>(
                    "integrity_tags",
                    |m: &Label| { &m.integrity_tags },
                    |m: &mut Label| { &mut m.integrity_tags },
                ));
                ::protobuf::reflect::MessageDescriptor::new::<Label>(
                    "Label",
                    fields,
                    file_descriptor_proto()
                )
            })
        }
    }

    fn default_instance() -> &'static Label {
        static mut instance: ::protobuf::lazy::Lazy<Label> = ::protobuf::lazy::Lazy {
            lock: ::protobuf::lazy::ONCE_INIT,
            ptr: 0 as *const Label,
        };
        unsafe {
            instance.get(Label::new)
        }
    }
}

impl ::protobuf::Clear for Label {
    fn clear(&mut self) {
        self.secrecy_tags.clear();
        self.integrity_tags.clear();
        self.unknown_fields.clear();
    }
}

impl ::std::fmt::Debug for Label {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        ::protobuf::text_format::fmt(self, f)
    }
}

impl ::protobuf::reflect::ProtobufValue for Label {
    fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
        ::protobuf::reflect::ProtobufValueRef::Message(self)
    }
}

#[derive(PartialEq,Clone,Default)]
pub struct Tag {
    // message oneof groups
    pub tag: ::std::option::Option<Tag_oneof_tag>,
    // special fields
    pub unknown_fields: ::protobuf::UnknownFields,
    pub cached_size: ::protobuf::CachedSize,
}

impl<'a> ::std::default::Default for &'a Tag {
    fn default() -> &'a Tag {
        <Tag as ::protobuf::Message>::default_instance()
    }
}

#[derive(Clone,PartialEq,Debug)]
pub enum Tag_oneof_tag {
    grpc_tag(GrpcTag),
}

impl Tag {
    pub fn new() -> Tag {
        ::std::default::Default::default()
    }

    // .oak.policy.GrpcTag grpc_tag = 1;

    pub fn get_grpc_tag(&self) -> &GrpcTag {
        match self.tag {
            ::std::option::Option::Some(Tag_oneof_tag::grpc_tag(ref v)) => v,
            _ => GrpcTag::default_instance(),
        }
    }
    pub fn clear_grpc_tag(&mut self) {
        self.tag = ::std::option::Option::None;
    }

    pub fn has_grpc_tag(&self) -> bool {
        match self.tag {
            ::std::option::Option::Some(Tag_oneof_tag::grpc_tag(..)) => true,
            _ => false,
        }
    }

    // Param is passed by value, moved
    pub fn set_grpc_tag(&mut self, v: GrpcTag) {
        self.tag = ::std::option::Option::Some(Tag_oneof_tag::grpc_tag(v))
    }

    // Mutable pointer to the field.
    pub fn mut_grpc_tag(&mut self) -> &mut GrpcTag {
        if let ::std::option::Option::Some(Tag_oneof_tag::grpc_tag(_)) = self.tag {
        } else {
            self.tag = ::std::option::Option::Some(Tag_oneof_tag::grpc_tag(GrpcTag::new()));
        }
        match self.tag {
            ::std::option::Option::Some(Tag_oneof_tag::grpc_tag(ref mut v)) => v,
            _ => panic!(),
        }
    }

    // Take field
    pub fn take_grpc_tag(&mut self) -> GrpcTag {
        if self.has_grpc_tag() {
            match self.tag.take() {
                ::std::option::Option::Some(Tag_oneof_tag::grpc_tag(v)) => v,
                _ => panic!(),
            }
        } else {
            GrpcTag::new()
        }
    }
}

impl ::protobuf::Message for Tag {
    fn is_initialized(&self) -> bool {
        if let Some(Tag_oneof_tag::grpc_tag(ref v)) = self.tag {
            if !v.is_initialized() {
                return false;
            }
        }
        true
    }

    fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
        while !is.eof()? {
            let (field_number, wire_type) = is.read_tag_unpack()?;
            match field_number {
                1 => {
                    if wire_type != ::protobuf::wire_format::WireTypeLengthDelimited {
                        return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
                    }
                    self.tag = ::std::option::Option::Some(Tag_oneof_tag::grpc_tag(is.read_message()?));
                },
                _ => {
                    ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
                },
            };
        }
        ::std::result::Result::Ok(())
    }

    // Compute sizes of nested messages
    #[allow(unused_variables)]
    fn compute_size(&self) -> u32 {
        let mut my_size = 0;
        if let ::std::option::Option::Some(ref v) = self.tag {
            match v {
                &Tag_oneof_tag::grpc_tag(ref v) => {
                    let len = v.compute_size();
                    my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
                },
            };
        }
        my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
        self.cached_size.set(my_size);
        my_size
    }

    fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
        if let ::std::option::Option::Some(ref v) = self.tag {
            match v {
                &Tag_oneof_tag::grpc_tag(ref v) => {
                    os.write_tag(1, ::protobuf::wire_format::WireTypeLengthDelimited)?;
                    os.write_raw_varint32(v.get_cached_size())?;
                    v.write_to_with_cached_sizes(os)?;
                },
            };
        }
        os.write_unknown_fields(self.get_unknown_fields())?;
        ::std::result::Result::Ok(())
    }

    fn get_cached_size(&self) -> u32 {
        self.cached_size.get()
    }

    fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
        &self.unknown_fields
    }

    fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
        &mut self.unknown_fields
    }

    fn as_any(&self) -> &dyn (::std::any::Any) {
        self as &dyn (::std::any::Any)
    }
    fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) {
        self as &mut dyn (::std::any::Any)
    }
    fn into_any(self: Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {
        self
    }

    fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
        Self::descriptor_static()
    }

    fn new() -> Tag {
        Tag::new()
    }

    fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
        static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
            lock: ::protobuf::lazy::ONCE_INIT,
            ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
        };
        unsafe {
            descriptor.get(|| {
                let mut fields = ::std::vec::Vec::new();
                fields.push(::protobuf::reflect::accessor::make_singular_message_accessor::<_, GrpcTag>(
                    "grpc_tag",
                    Tag::has_grpc_tag,
                    Tag::get_grpc_tag,
                ));
                ::protobuf::reflect::MessageDescriptor::new::<Tag>(
                    "Tag",
                    fields,
                    file_descriptor_proto()
                )
            })
        }
    }

    fn default_instance() -> &'static Tag {
        static mut instance: ::protobuf::lazy::Lazy<Tag> = ::protobuf::lazy::Lazy {
            lock: ::protobuf::lazy::ONCE_INIT,
            ptr: 0 as *const Tag,
        };
        unsafe {
            instance.get(Tag::new)
        }
    }
}

impl ::protobuf::Clear for Tag {
    fn clear(&mut self) {
        self.tag = ::std::option::Option::None;
        self.unknown_fields.clear();
    }
}

impl ::std::fmt::Debug for Tag {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        ::protobuf::text_format::fmt(self, f)
    }
}

impl ::protobuf::reflect::ProtobufValue for Tag {
    fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
        ::protobuf::reflect::ProtobufValueRef::Message(self)
    }
}

#[derive(PartialEq,Clone,Default)]
pub struct GrpcTag {
    // message fields
    pub authorization_bearer_token: ::std::vec::Vec<u8>,
    // special fields
    pub unknown_fields: ::protobuf::UnknownFields,
    pub cached_size: ::protobuf::CachedSize,
}

impl<'a> ::std::default::Default for &'a GrpcTag {
    fn default() -> &'a GrpcTag {
        <GrpcTag as ::protobuf::Message>::default_instance()
    }
}

impl GrpcTag {
    pub fn new() -> GrpcTag {
        ::std::default::Default::default()
    }

    // bytes authorization_bearer_token = 1;

    pub fn get_authorization_bearer_token(&self) -> &[u8] {
        &self.authorization_bearer_token
    }
    pub fn clear_authorization_bearer_token(&mut self) {
        self.authorization_bearer_token.clear();
    }

    // Param is passed by value, moved
    pub fn set_authorization_bearer_token(&mut self, v: ::std::vec::Vec<u8>) {
        self.authorization_bearer_token = v;
    }

    // Mutable pointer to the field.
    // If field is not initialized, it is initialized with default value first.
    pub fn mut_authorization_bearer_token(&mut self) -> &mut ::std::vec::Vec<u8> {
        &mut self.authorization_bearer_token
    }

    // Take field
    pub fn take_authorization_bearer_token(&mut self) -> ::std::vec::Vec<u8> {
        ::std::mem::replace(&mut self.authorization_bearer_token, ::std::vec::Vec::new())
    }
}

impl ::protobuf::Message for GrpcTag {
    fn is_initialized(&self) -> bool {
        true
    }

    fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
        while !is.eof()? {
            let (field_number, wire_type) = is.read_tag_unpack()?;
            match field_number {
                1 => {
                    ::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.authorization_bearer_token)?;
                },
                _ => {
                    ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
                },
            };
        }
        ::std::result::Result::Ok(())
    }

    // Compute sizes of nested messages
    #[allow(unused_variables)]
    fn compute_size(&self) -> u32 {
        let mut my_size = 0;
        if !self.authorization_bearer_token.is_empty() {
            my_size += ::protobuf::rt::bytes_size(1, &self.authorization_bearer_token);
        }
        my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
        self.cached_size.set(my_size);
        my_size
    }

    fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
        if !self.authorization_bearer_token.is_empty() {
            os.write_bytes(1, &self.authorization_bearer_token)?;
        }
        os.write_unknown_fields(self.get_unknown_fields())?;
        ::std::result::Result::Ok(())
    }

    fn get_cached_size(&self) -> u32 {
        self.cached_size.get()
    }

    fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
        &self.unknown_fields
    }

    fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
        &mut self.unknown_fields
    }

    fn as_any(&self) -> &dyn (::std::any::Any) {
        self as &dyn (::std::any::Any)
    }
    fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) {
        self as &mut dyn (::std::any::Any)
    }
    fn into_any(self: Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {
        self
    }

    fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
        Self::descriptor_static()
    }

    fn new() -> GrpcTag {
        GrpcTag::new()
    }

    fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
        static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
            lock: ::protobuf::lazy::ONCE_INIT,
            ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
        };
        unsafe {
            descriptor.get(|| {
                let mut fields = ::std::vec::Vec::new();
                fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
                    "authorization_bearer_token",
                    |m: &GrpcTag| { &m.authorization_bearer_token },
                    |m: &mut GrpcTag| { &mut m.authorization_bearer_token },
                ));
                ::protobuf::reflect::MessageDescriptor::new::<GrpcTag>(
                    "GrpcTag",
                    fields,
                    file_descriptor_proto()
                )
            })
        }
    }

    fn default_instance() -> &'static GrpcTag {
        static mut instance: ::protobuf::lazy::Lazy<GrpcTag> = ::protobuf::lazy::Lazy {
            lock: ::protobuf::lazy::ONCE_INIT,
            ptr: 0 as *const GrpcTag,
        };
        unsafe {
            instance.get(GrpcTag::new)
        }
    }
}

impl ::protobuf::Clear for GrpcTag {
    fn clear(&mut self) {
        self.authorization_bearer_token.clear();
        self.unknown_fields.clear();
    }
}

impl ::std::fmt::Debug for GrpcTag {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        ::protobuf::text_format::fmt(self, f)
    }
}

impl ::protobuf::reflect::ProtobufValue for GrpcTag {
    fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
        ::protobuf::reflect::ProtobufValueRef::Message(self)
    }
}

static file_descriptor_proto_data: &'static [u8] = b"\
    \n\x16oak/proto/policy.proto\x12\noak.policy\"s\n\x05Label\x122\n\x0csec\
    recy_tags\x18\x01\x20\x03(\x0b2\x0f.oak.policy.TagR\x0bsecrecyTags\x126\
    \n\x0eintegrity_tags\x18\x02\x20\x03(\x0b2\x0f.oak.policy.TagR\rintegrit\
    yTags\">\n\x03Tag\x120\n\x08grpc_tag\x18\x01\x20\x01(\x0b2\x13.oak.polic\
    y.GrpcTagH\0R\x07grpcTagB\x05\n\x03tag\"G\n\x07GrpcTag\x12<\n\x1aauthori\
    zation_bearer_token\x18\x01\x20\x01(\x0cR\x18authorizationBearerTokenb\
    \x06proto3\
";

static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy {
    lock: ::protobuf::lazy::ONCE_INIT,
    ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto,
};

fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {
    ::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap()
}

pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
    unsafe {
        file_descriptor_proto_lazy.get(|| {
            parse_descriptor_proto()
        })
    }
}
<|endoftext|>


<commit_before><commit_msg>DenseMatrix.transpose()<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed DenseVector::length() and added a test for it! also a new constructor.<commit_after><|endoftext|>


<commit_before><commit_msg>Add example going from *const -> &Foo ref<commit_after><|endoftext|>


<commit_before><commit_msg>Update Arc test<commit_after><|endoftext|>


<commit_before>// Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>

use futures_channel::{mpsc, oneshot};
use futures_core::stream::Stream;
use futures_core::task::Context;
use futures_core::{Async, Future, Never};

use MainContext;
use Source;
use Continue;
use Priority;

/// Represents a `Future` around a `glib::Source`. The future will
/// be resolved once the source has provided a value
pub struct SourceFuture<F, T> {
    create_source: Option<F>,
    source: Option<(Source, oneshot::Receiver<T>)>,
}

impl<F, T: 'static> SourceFuture<F, T>
where
    F: FnOnce(oneshot::Sender<T>) -> Source + Send + 'static,
{
    /// Create a new `SourceFuture`
    ///
    /// The provided closure should return a newly created `glib::Source` when called
    /// and pass the value provided by the source to the oneshot sender that is passed
    /// to the closure.
    pub fn new(create_source: F) -> Box<Future<Item = T, Error = Never>> {
        Box::new(SourceFuture {
            create_source: Some(create_source),
            source: None,
        })
    }
}

impl<F, T> Future for SourceFuture<F, T>
where
    F: FnOnce(oneshot::Sender<T>) -> Source + Send + 'static,
{
    type Item = T;
    type Error = Never;

    fn poll(&mut self, ctx: &mut Context) -> Result<Async<T>, Never> {
        let SourceFuture {
            ref mut create_source,
            ref mut source,
            ..
        } = *self;

        if let Some(create_source) = create_source.take() {
            let main_context = MainContext::ref_thread_default();
            match main_context {
                None => unreachable!(),
                Some(ref main_context) => {
                    assert!(main_context.is_owner());

                    // Channel for sending back the Source result to our future here.
                    //
                    // In theory we could directly continue polling the
                    // corresponding task from the Source callback,
                    // however this would break at the very least
                    // the g_main_current_source() API.
                    let (send, recv) = oneshot::channel();

                    let s = create_source(send);

                    s.attach(Some(main_context));
                    *source = Some((s, recv));
                }
            }
        }

        // At this point we must have a receiver
        let res = {
            let &mut (_, ref mut receiver) = source.as_mut().unwrap();
            receiver.poll(ctx)
        };
        match res {
            Err(_) => unreachable!(),
            Ok(Async::Ready(v)) => {
                // Get rid of the reference to the source, it triggered
                let _ = source.take();
                Ok(Async::Ready(v))
            }
            Ok(Async::Pending) => Ok(Async::Pending),
        }
    }
}

impl<T, F> Drop for SourceFuture<T, F> {
    fn drop(&mut self) {
        // Get rid of the source, we don't care anymore if it still triggers
        if let Some((source, _)) = self.source.take() {
            source.destroy();
        }
    }
}

/// Create a `Future` that will resolve after the given number of milliseconds.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn timeout_future(value: u32) -> Box<Future<Item = (), Error = Never>> {
    timeout_future_with_priority(::PRIORITY_DEFAULT, value)
}

/// Create a `Future` that will resolve after the given number of milliseconds.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn timeout_future_with_priority(priority: Priority, value: u32) -> Box<Future<Item = (), Error = Never>> {
    SourceFuture::new(move |send| {
        let mut send = Some(send);
        ::timeout_source_new(value, None, priority, move || {
            let _ = send.take().unwrap().send(());
            Continue(false)
        })
    })
}

/// Create a `Future` that will resolve after the given number of seconds.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn timeout_future_seconds(value: u32) -> Box<Future<Item = (), Error = Never>> {
    timeout_future_seconds_with_priority(::PRIORITY_DEFAULT, value)
}

/// Create a `Future` that will resolve after the given number of seconds.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn timeout_future_seconds_with_priority(priority: Priority, value: u32) -> Box<Future<Item = (), Error = Never>> {
    SourceFuture::new(move |send| {
        let mut send = Some(send);
        ::timeout_source_new_seconds(value, None, priority, move || {
            let _ = send.take().unwrap().send(());
            Continue(false)
        })
    })
}

/// Create a `Future` that will resolve once the child process with the given pid exits
///
/// The `Future` will resolve to the pid of the child process and the exit code.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn child_watch_future(pid: ::Pid) -> Box<Future<Item = (::Pid, i32), Error = Never>> {
    child_watch_future_with_priority(::PRIORITY_DEFAULT, pid)
}

/// Create a `Future` that will resolve once the child process with the given pid exits
///
/// The `Future` will resolve to the pid of the child process and the exit code.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn child_watch_future_with_priority(priority: Priority, pid: ::Pid) -> Box<Future<Item = (::Pid, i32), Error = Never>> {
    SourceFuture::new(move |send| {
        let mut send = Some(send);
        ::child_watch_source_new(pid, None, priority, move |pid, code| {
            let _ = send.take().unwrap().send((pid, code));
        })
    })
}

#[cfg(any(unix, feature = "dox"))]
/// Create a `Future` that will resolve once the given UNIX signal is raised
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn unix_signal_future(signum: i32) -> Box<Future<Item = (), Error = Never>> {
    unix_signal_future_with_priority(::PRIORITY_DEFAULT, signum)
}

#[cfg(any(unix, feature = "dox"))]
/// Create a `Future` that will resolve once the given UNIX signal is raised
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn unix_signal_future_with_priority(priority: Priority, signum: i32) -> Box<Future<Item = (), Error = Never>> {
    SourceFuture::new(move |send| {
        let mut send = Some(send);
        ::unix_signal_source_new(signum, None, priority, move || {
            let _ = send.take().unwrap().send(());
            Continue(false)
        })
    })
}

/// Represents a `Stream` around a `glib::Source`. The stream will
/// be provide all values that are provided by the source
pub struct SourceStream<F, T> {
    create_source: Option<F>,
    source: Option<(Source, mpsc::UnboundedReceiver<T>)>,
}

impl<F, T: 'static> SourceStream<F, T>
where
    F: FnOnce(mpsc::UnboundedSender<T>) -> Source + Send + 'static,
{
    /// Create a new `SourceStream`
    ///
    /// The provided closure should return a newly created `glib::Source` when called
    /// and pass the values provided by the source to the sender that is passed
    /// to the closure.
    pub fn new(create_source: F) -> Box<Stream<Item = T, Error = Never>> {
        Box::new(SourceStream {
            create_source: Some(create_source),
            source: None,
        })
    }
}

impl<F, T> Stream for SourceStream<F, T>
where
    F: FnOnce(mpsc::UnboundedSender<T>) -> Source + Send + 'static,
{
    type Item = T;
    type Error = Never;

    fn poll_next(&mut self, ctx: &mut Context) -> Result<Async<Option<T>>, Never> {
        let SourceStream {
            ref mut create_source,
            ref mut source,
            ..
        } = *self;

        if let Some(create_source) = create_source.take() {
            let main_context = MainContext::ref_thread_default();
            match main_context {
                None => unreachable!(),
                Some(ref main_context) => {
                    assert!(main_context.is_owner());

                    // Channel for sending back the Source result to our future here.
                    //
                    // In theory we could directly continue polling the
                    // corresponding task from the Source callback,
                    // however this would break at the very least
                    // the g_main_current_source() API.
                    let (send, recv) = mpsc::unbounded();

                    let s = create_source(send);

                    s.attach(Some(main_context));
                    *source = Some((s, recv));
                }
            }
        }

        // At this point we must have a receiver
        let res = {
            let &mut (_, ref mut receiver) = source.as_mut().unwrap();
            receiver.poll_next(ctx)
        };
        match res {
            Err(_) => unreachable!(),
            Ok(Async::Ready(v)) => {
                if v.is_none() {
                    // Get rid of the reference to the source, it triggered
                    let _ = source.take();
                }
                Ok(Async::Ready(v))
            }
            Ok(Async::Pending) => Ok(Async::Pending),
        }
    }
}

impl<T, F> Drop for SourceStream<T, F> {
    fn drop(&mut self) {
        // Get rid of the source, we don't care anymore if it still triggers
        if let Some((source, _)) = self.source.take() {
            source.destroy();
        }
    }
}

/// Create a `Stream` that will provide a value every given number of milliseconds.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn interval_stream(value: u32) -> Box<Stream<Item = (), Error = Never>> {
    interval_stream_with_priority(::PRIORITY_DEFAULT, value)
}

/// Create a `Stream` that will provide a value every given number of milliseconds.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn interval_stream_with_priority(priority: Priority, value: u32) -> Box<Stream<Item = (), Error = Never>> {
    SourceStream::new(move |send| {
        ::timeout_source_new(value, None, priority, move || {
            if send.unbounded_send(()).is_err() {
                Continue(false)
            } else {
                Continue(true)
            }
        })
    })
}

/// Create a `Stream` that will provide a value every given number of seconds.
///
/// The `Stream` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn interval_stream_seconds(value: u32) -> Box<Stream<Item = (), Error = Never>> {
    interval_stream_seconds_with_priority(::PRIORITY_DEFAULT, value)
}

/// Create a `Stream` that will provide a value every given number of seconds.
///
/// The `Stream` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn interval_stream_seconds_with_priority(priority: Priority, value: u32) -> Box<Stream<Item = (), Error = Never>> {
    SourceStream::new(move |send| {
        ::timeout_source_new_seconds(value, None, priority, move || {
            if send.unbounded_send(()).is_err() {
                Continue(false)
            } else {
                Continue(true)
            }
        })
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures_util::FutureExt;
    use futures_util::StreamExt;

    #[test]
    fn test_timeout() {
        let mut c = MainContext::new();

        let res = c.block_on(timeout_future(20)
            .and_then(move |_ctx| {
                Ok(())
            })
        );

        assert_eq!(res, Ok(()));
    }

    #[test]
    fn test_interval() {
        let mut c = MainContext::new();

        let mut count = 0;

        {
            let count = &mut count;
            let res = c.block_on(interval_stream(20)
                .take(2)
                .for_each(move |_ctx| {
                    *count = *count + 1;
                    Ok(())
                })
                .map(|_| ())
            );

            assert_eq!(res, Ok(()));
        }

        assert_eq!(count, 2);
    }
}
<commit_msg>Add a Stream implementation around UNIX signals in addition to the Future<commit_after>// Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>

use futures_channel::{mpsc, oneshot};
use futures_core::stream::Stream;
use futures_core::task::Context;
use futures_core::{Async, Future, Never};

use MainContext;
use Source;
use Continue;
use Priority;

/// Represents a `Future` around a `glib::Source`. The future will
/// be resolved once the source has provided a value
pub struct SourceFuture<F, T> {
    create_source: Option<F>,
    source: Option<(Source, oneshot::Receiver<T>)>,
}

impl<F, T: 'static> SourceFuture<F, T>
where
    F: FnOnce(oneshot::Sender<T>) -> Source + Send + 'static,
{
    /// Create a new `SourceFuture`
    ///
    /// The provided closure should return a newly created `glib::Source` when called
    /// and pass the value provided by the source to the oneshot sender that is passed
    /// to the closure.
    pub fn new(create_source: F) -> Box<Future<Item = T, Error = Never>> {
        Box::new(SourceFuture {
            create_source: Some(create_source),
            source: None,
        })
    }
}

impl<F, T> Future for SourceFuture<F, T>
where
    F: FnOnce(oneshot::Sender<T>) -> Source + Send + 'static,
{
    type Item = T;
    type Error = Never;

    fn poll(&mut self, ctx: &mut Context) -> Result<Async<T>, Never> {
        let SourceFuture {
            ref mut create_source,
            ref mut source,
            ..
        } = *self;

        if let Some(create_source) = create_source.take() {
            let main_context = MainContext::ref_thread_default();
            match main_context {
                None => unreachable!(),
                Some(ref main_context) => {
                    assert!(main_context.is_owner());

                    // Channel for sending back the Source result to our future here.
                    //
                    // In theory we could directly continue polling the
                    // corresponding task from the Source callback,
                    // however this would break at the very least
                    // the g_main_current_source() API.
                    let (send, recv) = oneshot::channel();

                    let s = create_source(send);

                    s.attach(Some(main_context));
                    *source = Some((s, recv));
                }
            }
        }

        // At this point we must have a receiver
        let res = {
            let &mut (_, ref mut receiver) = source.as_mut().unwrap();
            receiver.poll(ctx)
        };
        match res {
            Err(_) => unreachable!(),
            Ok(Async::Ready(v)) => {
                // Get rid of the reference to the source, it triggered
                let _ = source.take();
                Ok(Async::Ready(v))
            }
            Ok(Async::Pending) => Ok(Async::Pending),
        }
    }
}

impl<T, F> Drop for SourceFuture<T, F> {
    fn drop(&mut self) {
        // Get rid of the source, we don't care anymore if it still triggers
        if let Some((source, _)) = self.source.take() {
            source.destroy();
        }
    }
}

/// Create a `Future` that will resolve after the given number of milliseconds.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn timeout_future(value: u32) -> Box<Future<Item = (), Error = Never>> {
    timeout_future_with_priority(::PRIORITY_DEFAULT, value)
}

/// Create a `Future` that will resolve after the given number of milliseconds.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn timeout_future_with_priority(priority: Priority, value: u32) -> Box<Future<Item = (), Error = Never>> {
    SourceFuture::new(move |send| {
        let mut send = Some(send);
        ::timeout_source_new(value, None, priority, move || {
            let _ = send.take().unwrap().send(());
            Continue(false)
        })
    })
}

/// Create a `Future` that will resolve after the given number of seconds.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn timeout_future_seconds(value: u32) -> Box<Future<Item = (), Error = Never>> {
    timeout_future_seconds_with_priority(::PRIORITY_DEFAULT, value)
}

/// Create a `Future` that will resolve after the given number of seconds.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn timeout_future_seconds_with_priority(priority: Priority, value: u32) -> Box<Future<Item = (), Error = Never>> {
    SourceFuture::new(move |send| {
        let mut send = Some(send);
        ::timeout_source_new_seconds(value, None, priority, move || {
            let _ = send.take().unwrap().send(());
            Continue(false)
        })
    })
}

/// Create a `Future` that will resolve once the child process with the given pid exits
///
/// The `Future` will resolve to the pid of the child process and the exit code.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn child_watch_future(pid: ::Pid) -> Box<Future<Item = (::Pid, i32), Error = Never>> {
    child_watch_future_with_priority(::PRIORITY_DEFAULT, pid)
}

/// Create a `Future` that will resolve once the child process with the given pid exits
///
/// The `Future` will resolve to the pid of the child process and the exit code.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn child_watch_future_with_priority(priority: Priority, pid: ::Pid) -> Box<Future<Item = (::Pid, i32), Error = Never>> {
    SourceFuture::new(move |send| {
        let mut send = Some(send);
        ::child_watch_source_new(pid, None, priority, move |pid, code| {
            let _ = send.take().unwrap().send((pid, code));
        })
    })
}

#[cfg(any(unix, feature = "dox"))]
/// Create a `Future` that will resolve once the given UNIX signal is raised
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn unix_signal_future(signum: i32) -> Box<Future<Item = (), Error = Never>> {
    unix_signal_future_with_priority(::PRIORITY_DEFAULT, signum)
}

#[cfg(any(unix, feature = "dox"))]
/// Create a `Future` that will resolve once the given UNIX signal is raised
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn unix_signal_future_with_priority(priority: Priority, signum: i32) -> Box<Future<Item = (), Error = Never>> {
    SourceFuture::new(move |send| {
        let mut send = Some(send);
        ::unix_signal_source_new(signum, None, priority, move || {
            let _ = send.take().unwrap().send(());
            Continue(false)
        })
    })
}

/// Represents a `Stream` around a `glib::Source`. The stream will
/// be provide all values that are provided by the source
pub struct SourceStream<F, T> {
    create_source: Option<F>,
    source: Option<(Source, mpsc::UnboundedReceiver<T>)>,
}

impl<F, T: 'static> SourceStream<F, T>
where
    F: FnOnce(mpsc::UnboundedSender<T>) -> Source + Send + 'static,
{
    /// Create a new `SourceStream`
    ///
    /// The provided closure should return a newly created `glib::Source` when called
    /// and pass the values provided by the source to the sender that is passed
    /// to the closure.
    pub fn new(create_source: F) -> Box<Stream<Item = T, Error = Never>> {
        Box::new(SourceStream {
            create_source: Some(create_source),
            source: None,
        })
    }
}

impl<F, T> Stream for SourceStream<F, T>
where
    F: FnOnce(mpsc::UnboundedSender<T>) -> Source + Send + 'static,
{
    type Item = T;
    type Error = Never;

    fn poll_next(&mut self, ctx: &mut Context) -> Result<Async<Option<T>>, Never> {
        let SourceStream {
            ref mut create_source,
            ref mut source,
            ..
        } = *self;

        if let Some(create_source) = create_source.take() {
            let main_context = MainContext::ref_thread_default();
            match main_context {
                None => unreachable!(),
                Some(ref main_context) => {
                    assert!(main_context.is_owner());

                    // Channel for sending back the Source result to our future here.
                    //
                    // In theory we could directly continue polling the
                    // corresponding task from the Source callback,
                    // however this would break at the very least
                    // the g_main_current_source() API.
                    let (send, recv) = mpsc::unbounded();

                    let s = create_source(send);

                    s.attach(Some(main_context));
                    *source = Some((s, recv));
                }
            }
        }

        // At this point we must have a receiver
        let res = {
            let &mut (_, ref mut receiver) = source.as_mut().unwrap();
            receiver.poll_next(ctx)
        };
        match res {
            Err(_) => unreachable!(),
            Ok(Async::Ready(v)) => {
                if v.is_none() {
                    // Get rid of the reference to the source, it triggered
                    let _ = source.take();
                }
                Ok(Async::Ready(v))
            }
            Ok(Async::Pending) => Ok(Async::Pending),
        }
    }
}

impl<T, F> Drop for SourceStream<T, F> {
    fn drop(&mut self) {
        // Get rid of the source, we don't care anymore if it still triggers
        if let Some((source, _)) = self.source.take() {
            source.destroy();
        }
    }
}

/// Create a `Stream` that will provide a value every given number of milliseconds.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn interval_stream(value: u32) -> Box<Stream<Item = (), Error = Never>> {
    interval_stream_with_priority(::PRIORITY_DEFAULT, value)
}

/// Create a `Stream` that will provide a value every given number of milliseconds.
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn interval_stream_with_priority(priority: Priority, value: u32) -> Box<Stream<Item = (), Error = Never>> {
    SourceStream::new(move |send| {
        ::timeout_source_new(value, None, priority, move || {
            if send.unbounded_send(()).is_err() {
                Continue(false)
            } else {
                Continue(true)
            }
        })
    })
}

/// Create a `Stream` that will provide a value every given number of seconds.
///
/// The `Stream` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn interval_stream_seconds(value: u32) -> Box<Stream<Item = (), Error = Never>> {
    interval_stream_seconds_with_priority(::PRIORITY_DEFAULT, value)
}

/// Create a `Stream` that will provide a value every given number of seconds.
///
/// The `Stream` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn interval_stream_seconds_with_priority(priority: Priority, value: u32) -> Box<Stream<Item = (), Error = Never>> {
    SourceStream::new(move |send| {
        ::timeout_source_new_seconds(value, None, priority, move || {
            if send.unbounded_send(()).is_err() {
                Continue(false)
            } else {
                Continue(true)
            }
        })
    })
}

#[cfg(any(unix, feature = "dox"))]
/// Create a `Stream` that will provide a value whenever the given UNIX signal is raised
///
/// The `Stream` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn unix_signal_stream(signum: i32) -> Box<Stream<Item = (), Error = Never>> {
    unix_signal_stream_with_priority(::PRIORITY_DEFAULT, signum)
}

#[cfg(any(unix, feature = "dox"))]
/// Create a `Stream` that will provide a value whenever the given UNIX signal is raised
///
/// The `Stream` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn unix_signal_stream_with_priority(priority: Priority, signum: i32) -> Box<Stream<Item = (), Error = Never>> {
    SourceStream::new(move |send| {
        ::unix_signal_source_new(signum, None, priority, move || {
            if send.unbounded_send(()).is_err() {
                Continue(false)
            } else {
                Continue(true)
            }
        })
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures_util::FutureExt;
    use futures_util::StreamExt;

    #[test]
    fn test_timeout() {
        let mut c = MainContext::new();

        let res = c.block_on(timeout_future(20)
            .and_then(move |_ctx| {
                Ok(())
            })
        );

        assert_eq!(res, Ok(()));
    }

    #[test]
    fn test_interval() {
        let mut c = MainContext::new();

        let mut count = 0;

        {
            let count = &mut count;
            let res = c.block_on(interval_stream(20)
                .take(2)
                .for_each(move |_ctx| {
                    *count = *count + 1;
                    Ok(())
                })
                .map(|_| ())
            );

            assert_eq!(res, Ok(()));
        }

        assert_eq!(count, 2);
    }
}
<|endoftext|>


<commit_before><commit_msg>ADDED STUFF<commit_after>testtest2<|endoftext|>


<commit_before><commit_msg>Got initial Ogg reader working<commit_after>use std::io::File;
use std::path::posix::Path;
//use std::option::Option;
use std::vec::Vec;

// Prints the byte length of every underlying packet in the stream

// A bitstream is represented by the stream itself (read to a certain point),
// plus any information needed to process the remainder of the stream at that
// point
struct OggBitstream {
    file : File,
    end_of_stream : bool,
    current_segment_lengths : Vec<u8>
}

impl OggBitstream {
    fn new(f : File) -> OggBitstream {
        OggBitstream {
            end_of_stream : false,
            file : f,
            current_segment_lengths : Vec::new() }
    }

    /*
packet header:
OggS: 4 bytes
version: 1 byte
header type: 1 byte (fresh/continued packet, bos, eos)
absolute granule position: 8 bytes
stream serial number: 4 bytes
page sequence number: 4 bytes
page checksum: 4 bytes
segment count: 1 byte
segment table (variable: 1 byte per segment)
*/

    // Returns the bytes of the next packet in the underlying stream, or a
    // suitable null value
    fn next_packet(&mut self) -> Option<Vec<u8>> {
        let mut packet : Vec<u8> = Vec::new();
        loop {
            let segment = self.next_segment();
            if segment.len() < 255 {
                return Some(packet.append(segment.as_slice()));
            } else {
                packet = packet.append(segment.as_slice());
            }
        }
    }

    // Removes the next segment off of the segment list and return it
    fn next_segment(&mut self) -> Vec<u8> {
        if self.current_segment_lengths.len() == 0 {
            self.read_page();
        }

        // TODO: check end of stream

        let mut segment = Vec::from_elem(self.current_segment_lengths.as_slice()[0].to_uint().unwrap(), 0_u8);
        self.current_segment_lengths = Vec::from_slice(self.current_segment_lengths.tail());
        self.file.read(segment.as_mut_slice());
        segment
    }

    // reads the next page of the bitstream (through the segment table, but not
    // the segments themselve), writing it to the struct
    fn read_page(&mut self) {
        println!("Reading a page")
        // 1. read the static-length body
        // 2. read the variable-length current-segments table, write it to struct

        // TODO: figure out how to create the vector to read into without
        // initializing it first (maybe use a BufferedReader)
        let mut header = Vec::from_elem(27, 0_u8);
        self.file.read(header.as_mut_slice());
        let segment_count = header.as_slice()[26].to_uint().unwrap();
        let mut segment_table : Vec<u8> = Vec::from_elem(segment_count, 0_u8);
        self.file.read(segment_table.as_mut_slice());
        self.current_segment_lengths = segment_table;
    }
}

fn main() {
    println!("starting...");
    let mut maybe_f = File::open(&Path::new("star_wars.ogg"));
    match maybe_f {
        Ok(mut f) => {

            //let mut header : Vec<u8> = Vec::from_elem(27, 0_u8);
            // println!("vector reference length: {}", header.len());
            // println!("vector reference capacity: {}", header.capacity());
            // let mut header_slice = header.mut_slice(0, 27);
            // println!("slice length: {}", header_slice.len());
            // match f.read_at_least(3, header_slice) {
            //     Ok(bytes_read) => { println!("bytes read: {}", bytes_read); }
            //     Err(error) => { println!("error {}", error); }
            // }

            //     //println!("{}", header_slice.len());
            let mut bs = OggBitstream::new(f);
            let mut next_packet = bs.next_packet();
            while next_packet.is_some() {
                println!("Packet: {}", next_packet.unwrap().len());
                next_packet = bs.next_packet();
            }
        }
        _ => ()
    }
}
<|endoftext|>