<commit_before>/**
 * Various traits intended to be used with the built in numeric types. These
 * allow one to be more specific with trait bounds when using generics.
 *
 * Note: These traits won't be able to be used to their full potential until
 * trait inheritence is implemented.
 */

trait UnSigned {} // TODO: implement trait inheritence

pub impl u8:   UnSigned {}
pub impl u16:  UnSigned {}
pub impl u32:  UnSigned {}
pub impl u64:  UnSigned {}
pub impl uint: UnSigned {}

trait Signed {} // TODO: implement trait inheritence

pub impl i8:    Signed {}
pub impl i16:   Signed {}
pub impl i32:   Signed {}
pub impl i64:   Signed {}
pub impl int:   Signed {}

pub impl f32:   Signed {}
pub impl f64:   Signed {}
pub impl float: Signed {}

trait Integer {} // TODO: implement trait inheritence

pub impl u8:   Integer {}
pub impl u16:  Integer {}
pub impl u32:  Integer {}
pub impl u64:  Integer {}
pub impl uint: Integer {}

pub impl i8:   Integer {}
pub impl i16:  Integer {}
pub impl i32:  Integer {}
pub impl i64:  Integer {}
pub impl int:  Integer {}

trait FloatingPoint {} // TODO: implement trait inheritence

pub impl f32:   FloatingPoint {}
pub impl f64:   FloatingPoint {}
pub impl float: FloatingPoint {}

pub impl u8    : Add<u8,u8>        { #[inline(always)] pure fn add(rhs: &u8)    -> u8    { self + *rhs } }
pub impl u16   : Add<u16,u16>      { #[inline(always)] pure fn add(rhs: &u16)   -> u16   { self + *rhs } }
pub impl u32   : Add<u32,u32>      { #[inline(always)] pure fn add(rhs: &u32)   -> u32   { self + *rhs } }
pub impl u64   : Add<u64,u64>      { #[inline(always)] pure fn add(rhs: &u64)   -> u64   { self + *rhs } }
pub impl uint  : Add<uint,uint>    { #[inline(always)] pure fn add(rhs: &uint)  -> uint  { self + *rhs } }

pub impl i8    : Add<i8,i8>        { #[inline(always)] pure fn add(rhs: &i8)    -> i8    { self + *rhs } }
pub impl i16   : Add<i16,i16>      { #[inline(always)] pure fn add(rhs: &i16)   -> i16   { self + *rhs } }
pub impl i32   : Add<i32,i32>      { #[inline(always)] pure fn add(rhs: &i32)   -> i32   { self + *rhs } }
pub impl i64   : Add<i64,i64>      { #[inline(always)] pure fn add(rhs: &i64)   -> i64   { self + *rhs } }
pub impl int   : Add<int,int>      { #[inline(always)] pure fn add(rhs: &int)   -> int   { self + *rhs } }

pub impl f32   : Add<f32,f32>      { #[inline(always)] pure fn add(rhs: &f32)   -> f32   { self + *rhs } }
pub impl f64   : Add<f64,f64>      { #[inline(always)] pure fn add(rhs: &f64)   -> f64   { self + *rhs } }
pub impl float : Add<float,float>  { #[inline(always)] pure fn add(rhs: &float) -> float { self + *rhs } }

pub impl u8    : Sub<u8,u8>        { #[inline(always)] pure fn sub(rhs: &u8)    -> u8    { self - *rhs } }
pub impl u16   : Sub<u16,u16>      { #[inline(always)] pure fn sub(rhs: &u16)   -> u16   { self - *rhs } }
pub impl u32   : Sub<u32,u32>      { #[inline(always)] pure fn sub(rhs: &u32)   -> u32   { self - *rhs } }
pub impl u64   : Sub<u64,u64>      { #[inline(always)] pure fn sub(rhs: &u64)   -> u64   { self - *rhs } }
pub impl uint  : Sub<uint,uint>    { #[inline(always)] pure fn sub(rhs: &uint)  -> uint  { self - *rhs } }

pub impl i8    : Sub<i8,i8>        { #[inline(always)] pure fn sub(rhs: &i8)    -> i8    { self - *rhs } }
pub impl i16   : Sub<i16,i16>      { #[inline(always)] pure fn sub(rhs: &i16)   -> i16   { self - *rhs } }
pub impl i32   : Sub<i32,i32>      { #[inline(always)] pure fn sub(rhs: &i32)   -> i32   { self - *rhs } }
pub impl i64   : Sub<i64,i64>      { #[inline(always)] pure fn sub(rhs: &i64)   -> i64   { self - *rhs } }
pub impl int   : Sub<int,int>      { #[inline(always)] pure fn sub(rhs: &int)   -> int   { self - *rhs } }

pub impl f32   : Sub<f32,f32>      { #[inline(always)] pure fn sub(rhs: &f32)   -> f32   { self - *rhs } }
pub impl f64   : Sub<f64,f64>      { #[inline(always)] pure fn sub(rhs: &f64)   -> f64   { self - *rhs } }
pub impl float : Sub<float,float>  { #[inline(always)] pure fn sub(rhs: &float) -> float { self - *rhs } }

pub impl u8    : Mul<u8,u8>        { #[inline(always)] pure fn mul(rhs: &u8)    -> u8    { self * *rhs } }
pub impl u16   : Mul<u16,u16>      { #[inline(always)] pure fn mul(rhs: &u16)   -> u16   { self * *rhs } }
pub impl u32   : Mul<u32,u32>      { #[inline(always)] pure fn mul(rhs: &u32)   -> u32   { self * *rhs } }
pub impl u64   : Mul<u64,u64>      { #[inline(always)] pure fn mul(rhs: &u64)   -> u64   { self * *rhs } }
pub impl uint  : Mul<uint,uint>    { #[inline(always)] pure fn mul(rhs: &uint)  -> uint  { self * *rhs } }

pub impl i8    : Mul<i8,i8>        { #[inline(always)] pure fn mul(rhs: &i8)    -> i8    { self * *rhs } }
pub impl i16   : Mul<i16,i16>      { #[inline(always)] pure fn mul(rhs: &i16)   -> i16   { self * *rhs } }
pub impl i32   : Mul<i32,i32>      { #[inline(always)] pure fn mul(rhs: &i32)   -> i32   { self * *rhs } }
pub impl i64   : Mul<i64,i64>      { #[inline(always)] pure fn mul(rhs: &i64)   -> i64   { self * *rhs } }
pub impl int   : Mul<int,int>      { #[inline(always)] pure fn mul(rhs: &int)   -> int   { self * *rhs } }

pub impl f32   : Mul<f32,f32>      { #[inline(always)] pure fn mul(rhs: &f32)   -> f32   { self * *rhs } }
pub impl f64   : Mul<f64,f64>      { #[inline(always)] pure fn mul(rhs: &f64)   -> f64   { self * *rhs } }
pub impl float : Mul<float,float>  { #[inline(always)] pure fn mul(rhs: &float) -> float { self * *rhs } }

pub impl u8    : Div<u8,u8>        { #[inline(always)] pure fn div(rhs: &u8)    -> u8    { self / *rhs } }
pub impl u16   : Div<u16,u16>      { #[inline(always)] pure fn div(rhs: &u16)   -> u16   { self / *rhs } }
pub impl u32   : Div<u32,u32>      { #[inline(always)] pure fn div(rhs: &u32)   -> u32   { self / *rhs } }
pub impl u64   : Div<u64,u64>      { #[inline(always)] pure fn div(rhs: &u64)   -> u64   { self / *rhs } }
pub impl uint  : Div<uint,uint>    { #[inline(always)] pure fn div(rhs: &uint)  -> uint  { self / *rhs } }

pub impl i8    : Div<i8,i8>        { #[inline(always)] pure fn div(rhs: &i8)    -> i8    { self / *rhs } }
pub impl i16   : Div<i16,i16>      { #[inline(always)] pure fn div(rhs: &i16)   -> i16   { self / *rhs } }
pub impl i32   : Div<i32,i32>      { #[inline(always)] pure fn div(rhs: &i32)   -> i32   { self / *rhs } }
pub impl i64   : Div<i64,i64>      { #[inline(always)] pure fn div(rhs: &i64)   -> i64   { self / *rhs } }
pub impl int   : Div<int,int>      { #[inline(always)] pure fn div(rhs: &int)   -> int   { self / *rhs } }

pub impl f32   : Div<f32,f32>      { #[inline(always)] pure fn div(rhs: &f32)   -> f32   { self / *rhs } }
pub impl f64   : Div<f64,f64>      { #[inline(always)] pure fn div(rhs: &f64)   -> f64   { self / *rhs } }
pub impl float : Div<float,float>  { #[inline(always)] pure fn div(rhs: &float) -> float { self / *rhs } }

pub impl u8    : Modulo<u8,u8>        { #[inline(always)] pure fn modulo(rhs: &u8)    -> u8    { self % *rhs } }
pub impl u16   : Modulo<u16,u16>      { #[inline(always)] pure fn modulo(rhs: &u16)   -> u16   { self % *rhs } }
pub impl u32   : Modulo<u32,u32>      { #[inline(always)] pure fn modulo(rhs: &u32)   -> u32   { self % *rhs } }
pub impl u64   : Modulo<u64,u64>      { #[inline(always)] pure fn modulo(rhs: &u64)   -> u64   { self % *rhs } }
pub impl uint  : Modulo<uint,uint>    { #[inline(always)] pure fn modulo(rhs: &uint)  -> uint  { self % *rhs } }

pub impl i8    : Modulo<i8,i8>        { #[inline(always)] pure fn modulo(rhs: &i8)    -> i8    { self % *rhs } }
pub impl i16   : Modulo<i16,i16>      { #[inline(always)] pure fn modulo(rhs: &i16)   -> i16   { self % *rhs } }
pub impl i32   : Modulo<i32,i32>      { #[inline(always)] pure fn modulo(rhs: &i32)   -> i32   { self % *rhs } }
pub impl i64   : Modulo<i64,i64>      { #[inline(always)] pure fn modulo(rhs: &i64)   -> i64   { self % *rhs } }
pub impl int   : Modulo<int,int>      { #[inline(always)] pure fn modulo(rhs: &int)   -> int   { self % *rhs } }

pub impl f32   : Modulo<f32,f32>      { #[inline(always)] pure fn modulo(rhs: &f32)   -> f32   { self % *rhs } }
pub impl f64   : Modulo<f64,f64>      { #[inline(always)] pure fn modulo(rhs: &f64)   -> f64   { self % *rhs } }
pub impl float : Modulo<float,float>  { #[inline(always)] pure fn modulo(rhs: &float) -> float { self % *rhs } }

pub impl i8    : Neg<i8>    { #[inline(always)] pure fn neg() -> i8    { -self } }
pub impl i16   : Neg<i16>   { #[inline(always)] pure fn neg() -> i16   { -self } }
pub impl i32   : Neg<i32>   { #[inline(always)] pure fn neg() -> i32   { -self } }
pub impl i64   : Neg<i64>   { #[inline(always)] pure fn neg() -> i64   { -self } }
pub impl int   : Neg<int>   { #[inline(always)] pure fn neg() -> int   { -self } }

pub impl f32   : Neg<f32>   { #[inline(always)] pure fn neg() -> f32   { -self } }
pub impl f64   : Neg<f64>   { #[inline(always)] pure fn neg() -> f64   { -self } }
pub impl float : Neg<float> { #[inline(always)] pure fn neg() -> float { -self } }<commit_msg>Rename FloatingPoint to Float for brevity<commit_after>/**
 * Various traits intended to be used with the built in numeric types. These
 * allow one to be more specific with trait bounds when using generics.
 *
 * Note: These traits won't be able to be used to their full potential until
 * trait inheritence is implemented.
 */

trait UnSigned {} // TODO: implement trait inheritence

pub impl u8:   UnSigned {}
pub impl u16:  UnSigned {}
pub impl u32:  UnSigned {}
pub impl u64:  UnSigned {}
pub impl uint: UnSigned {}

trait Signed {} // TODO: implement trait inheritence

pub impl i8:    Signed {}
pub impl i16:   Signed {}
pub impl i32:   Signed {}
pub impl i64:   Signed {}
pub impl int:   Signed {}

pub impl f32:   Signed {}
pub impl f64:   Signed {}
pub impl float: Signed {}

trait Integer {} // TODO: implement trait inheritence

pub impl u8:   Integer {}
pub impl u16:  Integer {}
pub impl u32:  Integer {}
pub impl u64:  Integer {}
pub impl uint: Integer {}

pub impl i8:   Integer {}
pub impl i16:  Integer {}
pub impl i32:  Integer {}
pub impl i64:  Integer {}
pub impl int:  Integer {}

trait Float {} // TODO: implement trait inheritence

pub impl f32:   Float {}
pub impl f64:   Float {}
pub impl float: Float {}

pub impl u8    : Add<u8,u8>        { #[inline(always)] pure fn add(rhs: &u8)    -> u8    { self + *rhs } }
pub impl u16   : Add<u16,u16>      { #[inline(always)] pure fn add(rhs: &u16)   -> u16   { self + *rhs } }
pub impl u32   : Add<u32,u32>      { #[inline(always)] pure fn add(rhs: &u32)   -> u32   { self + *rhs } }
pub impl u64   : Add<u64,u64>      { #[inline(always)] pure fn add(rhs: &u64)   -> u64   { self + *rhs } }
pub impl uint  : Add<uint,uint>    { #[inline(always)] pure fn add(rhs: &uint)  -> uint  { self + *rhs } }

pub impl i8    : Add<i8,i8>        { #[inline(always)] pure fn add(rhs: &i8)    -> i8    { self + *rhs } }
pub impl i16   : Add<i16,i16>      { #[inline(always)] pure fn add(rhs: &i16)   -> i16   { self + *rhs } }
pub impl i32   : Add<i32,i32>      { #[inline(always)] pure fn add(rhs: &i32)   -> i32   { self + *rhs } }
pub impl i64   : Add<i64,i64>      { #[inline(always)] pure fn add(rhs: &i64)   -> i64   { self + *rhs } }
pub impl int   : Add<int,int>      { #[inline(always)] pure fn add(rhs: &int)   -> int   { self + *rhs } }

pub impl f32   : Add<f32,f32>      { #[inline(always)] pure fn add(rhs: &f32)   -> f32   { self + *rhs } }
pub impl f64   : Add<f64,f64>      { #[inline(always)] pure fn add(rhs: &f64)   -> f64   { self + *rhs } }
pub impl float : Add<float,float>  { #[inline(always)] pure fn add(rhs: &float) -> float { self + *rhs } }

pub impl u8    : Sub<u8,u8>        { #[inline(always)] pure fn sub(rhs: &u8)    -> u8    { self - *rhs } }
pub impl u16   : Sub<u16,u16>      { #[inline(always)] pure fn sub(rhs: &u16)   -> u16   { self - *rhs } }
pub impl u32   : Sub<u32,u32>      { #[inline(always)] pure fn sub(rhs: &u32)   -> u32   { self - *rhs } }
pub impl u64   : Sub<u64,u64>      { #[inline(always)] pure fn sub(rhs: &u64)   -> u64   { self - *rhs } }
pub impl uint  : Sub<uint,uint>    { #[inline(always)] pure fn sub(rhs: &uint)  -> uint  { self - *rhs } }

pub impl i8    : Sub<i8,i8>        { #[inline(always)] pure fn sub(rhs: &i8)    -> i8    { self - *rhs } }
pub impl i16   : Sub<i16,i16>      { #[inline(always)] pure fn sub(rhs: &i16)   -> i16   { self - *rhs } }
pub impl i32   : Sub<i32,i32>      { #[inline(always)] pure fn sub(rhs: &i32)   -> i32   { self - *rhs } }
pub impl i64   : Sub<i64,i64>      { #[inline(always)] pure fn sub(rhs: &i64)   -> i64   { self - *rhs } }
pub impl int   : Sub<int,int>      { #[inline(always)] pure fn sub(rhs: &int)   -> int   { self - *rhs } }

pub impl f32   : Sub<f32,f32>      { #[inline(always)] pure fn sub(rhs: &f32)   -> f32   { self - *rhs } }
pub impl f64   : Sub<f64,f64>      { #[inline(always)] pure fn sub(rhs: &f64)   -> f64   { self - *rhs } }
pub impl float : Sub<float,float>  { #[inline(always)] pure fn sub(rhs: &float) -> float { self - *rhs } }

pub impl u8    : Mul<u8,u8>        { #[inline(always)] pure fn mul(rhs: &u8)    -> u8    { self * *rhs } }
pub impl u16   : Mul<u16,u16>      { #[inline(always)] pure fn mul(rhs: &u16)   -> u16   { self * *rhs } }
pub impl u32   : Mul<u32,u32>      { #[inline(always)] pure fn mul(rhs: &u32)   -> u32   { self * *rhs } }
pub impl u64   : Mul<u64,u64>      { #[inline(always)] pure fn mul(rhs: &u64)   -> u64   { self * *rhs } }
pub impl uint  : Mul<uint,uint>    { #[inline(always)] pure fn mul(rhs: &uint)  -> uint  { self * *rhs } }

pub impl i8    : Mul<i8,i8>        { #[inline(always)] pure fn mul(rhs: &i8)    -> i8    { self * *rhs } }
pub impl i16   : Mul<i16,i16>      { #[inline(always)] pure fn mul(rhs: &i16)   -> i16   { self * *rhs } }
pub impl i32   : Mul<i32,i32>      { #[inline(always)] pure fn mul(rhs: &i32)   -> i32   { self * *rhs } }
pub impl i64   : Mul<i64,i64>      { #[inline(always)] pure fn mul(rhs: &i64)   -> i64   { self * *rhs } }
pub impl int   : Mul<int,int>      { #[inline(always)] pure fn mul(rhs: &int)   -> int   { self * *rhs } }

pub impl f32   : Mul<f32,f32>      { #[inline(always)] pure fn mul(rhs: &f32)   -> f32   { self * *rhs } }
pub impl f64   : Mul<f64,f64>      { #[inline(always)] pure fn mul(rhs: &f64)   -> f64   { self * *rhs } }
pub impl float : Mul<float,float>  { #[inline(always)] pure fn mul(rhs: &float) -> float { self * *rhs } }

pub impl u8    : Div<u8,u8>        { #[inline(always)] pure fn div(rhs: &u8)    -> u8    { self / *rhs } }
pub impl u16   : Div<u16,u16>      { #[inline(always)] pure fn div(rhs: &u16)   -> u16   { self / *rhs } }
pub impl u32   : Div<u32,u32>      { #[inline(always)] pure fn div(rhs: &u32)   -> u32   { self / *rhs } }
pub impl u64   : Div<u64,u64>      { #[inline(always)] pure fn div(rhs: &u64)   -> u64   { self / *rhs } }
pub impl uint  : Div<uint,uint>    { #[inline(always)] pure fn div(rhs: &uint)  -> uint  { self / *rhs } }

pub impl i8    : Div<i8,i8>        { #[inline(always)] pure fn div(rhs: &i8)    -> i8    { self / *rhs } }
pub impl i16   : Div<i16,i16>      { #[inline(always)] pure fn div(rhs: &i16)   -> i16   { self / *rhs } }
pub impl i32   : Div<i32,i32>      { #[inline(always)] pure fn div(rhs: &i32)   -> i32   { self / *rhs } }
pub impl i64   : Div<i64,i64>      { #[inline(always)] pure fn div(rhs: &i64)   -> i64   { self / *rhs } }
pub impl int   : Div<int,int>      { #[inline(always)] pure fn div(rhs: &int)   -> int   { self / *rhs } }

pub impl f32   : Div<f32,f32>      { #[inline(always)] pure fn div(rhs: &f32)   -> f32   { self / *rhs } }
pub impl f64   : Div<f64,f64>      { #[inline(always)] pure fn div(rhs: &f64)   -> f64   { self / *rhs } }
pub impl float : Div<float,float>  { #[inline(always)] pure fn div(rhs: &float) -> float { self / *rhs } }

pub impl u8    : Modulo<u8,u8>        { #[inline(always)] pure fn modulo(rhs: &u8)    -> u8    { self % *rhs } }
pub impl u16   : Modulo<u16,u16>      { #[inline(always)] pure fn modulo(rhs: &u16)   -> u16   { self % *rhs } }
pub impl u32   : Modulo<u32,u32>      { #[inline(always)] pure fn modulo(rhs: &u32)   -> u32   { self % *rhs } }
pub impl u64   : Modulo<u64,u64>      { #[inline(always)] pure fn modulo(rhs: &u64)   -> u64   { self % *rhs } }
pub impl uint  : Modulo<uint,uint>    { #[inline(always)] pure fn modulo(rhs: &uint)  -> uint  { self % *rhs } }

pub impl i8    : Modulo<i8,i8>        { #[inline(always)] pure fn modulo(rhs: &i8)    -> i8    { self % *rhs } }
pub impl i16   : Modulo<i16,i16>      { #[inline(always)] pure fn modulo(rhs: &i16)   -> i16   { self % *rhs } }
pub impl i32   : Modulo<i32,i32>      { #[inline(always)] pure fn modulo(rhs: &i32)   -> i32   { self % *rhs } }
pub impl i64   : Modulo<i64,i64>      { #[inline(always)] pure fn modulo(rhs: &i64)   -> i64   { self % *rhs } }
pub impl int   : Modulo<int,int>      { #[inline(always)] pure fn modulo(rhs: &int)   -> int   { self % *rhs } }

pub impl f32   : Modulo<f32,f32>      { #[inline(always)] pure fn modulo(rhs: &f32)   -> f32   { self % *rhs } }
pub impl f64   : Modulo<f64,f64>      { #[inline(always)] pure fn modulo(rhs: &f64)   -> f64   { self % *rhs } }
pub impl float : Modulo<float,float>  { #[inline(always)] pure fn modulo(rhs: &float) -> float { self % *rhs } }

pub impl i8    : Neg<i8>    { #[inline(always)] pure fn neg() -> i8    { -self } }
pub impl i16   : Neg<i16>   { #[inline(always)] pure fn neg() -> i16   { -self } }
pub impl i32   : Neg<i32>   { #[inline(always)] pure fn neg() -> i32   { -self } }
pub impl i64   : Neg<i64>   { #[inline(always)] pure fn neg() -> i64   { -self } }
pub impl int   : Neg<int>   { #[inline(always)] pure fn neg() -> int   { -self } }

pub impl f32   : Neg<f32>   { #[inline(always)] pure fn neg() -> f32   { -self } }
pub impl f64   : Neg<f64>   { #[inline(always)] pure fn neg() -> f64   { -self } }
pub impl float : Neg<float> { #[inline(always)] pure fn neg() -> float { -self } }<|endoftext|>


<commit_before>use common::memory::*;

use programs::common::*;

pub struct MemoryScheme;

impl SessionModule for MemoryScheme {
    fn scheme(&self) -> String {
        return "memory".to_string();
    }

    fn open(&mut self, url: &URL) -> Box<Resource>{
        let string = "Memory Used: ".to_string() + memory_used()/1024/1024 + " MB\n" + "Memory Free: " + memory_free()/1024/1024 + " MB";
        return box VecResource::new(ResourceType::File, string.to_utf8());
    }
}
<commit_msg>Show stack usage<commit_after>use common::memory::*;

use programs::common::*;

pub struct MemoryScheme;

fn stack_used() -> usize {
    unsafe{
        let stack: u32;
        asm!("" : "={esp}"(stack));
        return (0x200000 - stack) as usize;
    }
}

fn stack_free() -> usize {
    unsafe{
        let stack: u32;
        asm!("" : "={esp}"(stack));
        return (stack - 0x100000) as usize;
    }
}

impl SessionModule for MemoryScheme {
    fn scheme(&self) -> String {
        return "memory".to_string();
    }

    fn open(&mut self, url: &URL) -> Box<Resource>{
        let string = "Memory Used: ".to_string() + memory_used()/1024/1024 + " MB\n"
                   + "Memory Free: " + memory_free()/1024/1024 + " MB\n"
                   + "Stack Used: ".to_string() + stack_used()/1024 + " KB\n"
                   + "Stack Free: ".to_string() + stack_free()/1024 + " KB";
        return box VecResource::new(ResourceType::File, string.to_utf8());
    }
}
<|endoftext|>


<commit_before>use parking_lot::RwLock;
use std::{fmt, sync::Arc};

#[derive(Clone, Default)]
pub struct Configuration {
    inner: Arc<RwLock<Inner>>,
}

impl Configuration {
    pub fn channel_max(&self) -> u16 {
        self.inner.read().channel_max
    }

    pub(crate) fn set_channel_max(&self, channel_max: u16) {
        self.inner.write().channel_max = channel_max;
    }

    pub fn frame_max(&self) -> u32 {
        self.inner.read().frame_max
    }

    pub(crate) fn set_frame_max(&self, frame_max: u32) {
        self.inner.write().frame_max = frame_max;
    }

    pub fn heartbeat(&self) -> u16 {
        self.inner.read().heartbeat
    }

    pub(crate) fn set_heartbeat(&self, heartbeat: u16) {
        self.inner.write().heartbeat = heartbeat;
    }
}

#[derive(Default)]
struct Inner {
    channel_max: u16,
    frame_max: u32,
    heartbeat: u16,
}

impl fmt::Debug for Configuration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let inner = self.inner.read();
        f.debug_struct("Configuration")
            .field("channel_max", &inner.channel_max)
            .field("frame_max", &inner.frame_max)
            .field("heartbeat", &inner.heartbeat)
            .finish()
    }
}
<commit_msg>configuration: ensure frame_max is at least MIN_FRAME_SIZE<commit_after>use crate::protocol;
use parking_lot::RwLock;
use std::{fmt, sync::Arc};

#[derive(Clone, Default)]
pub struct Configuration {
    inner: Arc<RwLock<Inner>>,
}

impl Configuration {
    pub fn channel_max(&self) -> u16 {
        self.inner.read().channel_max
    }

    pub(crate) fn set_channel_max(&self, channel_max: u16) {
        self.inner.write().channel_max = channel_max;
    }

    pub fn frame_max(&self) -> u32 {
        self.inner.read().frame_max
    }

    pub(crate) fn set_frame_max(&self, frame_max: u32) {
        let frame_max = std::cmp::max(frame_max, protocol::constants::FRAME_MIN_SIZE as u32);
        self.inner.write().frame_max = frame_max;
    }

    pub fn heartbeat(&self) -> u16 {
        self.inner.read().heartbeat
    }

    pub(crate) fn set_heartbeat(&self, heartbeat: u16) {
        self.inner.write().heartbeat = heartbeat;
    }
}

#[derive(Default)]
struct Inner {
    channel_max: u16,
    frame_max: u32,
    heartbeat: u16,
}

impl fmt::Debug for Configuration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let inner = self.inner.read();
        f.debug_struct("Configuration")
            .field("channel_max", &inner.channel_max)
            .field("frame_max", &inner.frame_max)
            .field("heartbeat", &inner.heartbeat)
            .finish()
    }
}
<|endoftext|>


<commit_before>use cpu::{FReg, Reg};

pub const REG_COUNT: usize = 31;
pub static REG_PARAMS: [Reg; 8] = [R0, R1, R2, R3, R4, R5, R6, R7];
pub static SCRATCH: [Reg; 2] = [R16, R17];

pub const REG_RESULT: Reg = R0;
pub const REG_TMP1: Reg = R10;
pub const REG_TMP2: Reg = R11;
pub const REG_FP: Reg = R29;
pub const REG_LR: Reg = R30;
pub const REG_THREAD: Reg = R28;

pub const REG_SP: Reg = Reg(32);
pub const REG_ZERO: Reg = Reg(33);

pub const R0: Reg = Reg(0);
pub const R1: Reg = Reg(1);
pub const R2: Reg = Reg(2);
pub const R3: Reg = Reg(3);
pub const R4: Reg = Reg(4);
pub const R5: Reg = Reg(5);
pub const R6: Reg = Reg(6);
pub const R7: Reg = Reg(7);
pub const R8: Reg = Reg(8);
pub const R9: Reg = Reg(9);
pub const R10: Reg = Reg(10);
pub const R11: Reg = Reg(11);
pub const R12: Reg = Reg(12);
pub const R13: Reg = Reg(13);
pub const R14: Reg = Reg(14);
pub const R15: Reg = Reg(15);
pub const R16: Reg = Reg(16);
pub const R17: Reg = Reg(17);
pub const R18: Reg = Reg(18);
pub const R19: Reg = Reg(19);
pub const R20: Reg = Reg(20);
pub const R21: Reg = Reg(21);
pub const R22: Reg = Reg(22);
pub const R23: Reg = Reg(23);
pub const R24: Reg = Reg(24);
pub const R25: Reg = Reg(25);
pub const R26: Reg = Reg(26);
pub const R27: Reg = Reg(27);
pub const R28: Reg = Reg(28);
pub const R29: Reg = Reg(29);
pub const R30: Reg = Reg(30);

pub const FREG_RESULT: FReg = F0;
pub const FREG_TMP1: FReg = F1;
pub static FREG_PARAMS: [FReg; 8] = [F0, F1, F2, F3, F4, F5, F6, F7];

pub const F0: FReg = FReg(0);
pub const F1: FReg = FReg(1);
pub const F2: FReg = FReg(2);
pub const F3: FReg = FReg(3);
pub const F4: FReg = FReg(4);
pub const F5: FReg = FReg(5);
pub const F6: FReg = FReg(6);
pub const F7: FReg = FReg(7);
pub const F8: FReg = FReg(8);
pub const F9: FReg = FReg(9);
pub const F10: FReg = FReg(10);
pub const F11: FReg = FReg(11);
pub const F12: FReg = FReg(12);
pub const F13: FReg = FReg(13);
pub const F14: FReg = FReg(14);
pub const F15: FReg = FReg(15);
pub const F16: FReg = FReg(16);
pub const F17: FReg = FReg(17);
pub const F18: FReg = FReg(18);
pub const F19: FReg = FReg(19);
pub const F20: FReg = FReg(20);
pub const F21: FReg = FReg(21);
pub const F22: FReg = FReg(22);
pub const F23: FReg = FReg(23);
pub const F24: FReg = FReg(24);
pub const F25: FReg = FReg(25);
pub const F26: FReg = FReg(26);
pub const F27: FReg = FReg(27);
pub const F28: FReg = FReg(28);
pub const F29: FReg = FReg(29);
pub const F30: FReg = FReg(30);
pub const F31: FReg = FReg(31);

impl Reg {
    pub fn asm(self) -> u32 {
        match self {
            REG_SP => 31,
            REG_ZERO => 31,
            _ => self.0 as u32,
        }
    }

    pub fn is_gpr(self) -> bool {
        self.0 <= 30
    }

    pub fn is_gpr_or_zero(self) -> bool {
        self.is_gpr() || self == REG_ZERO
    }

    pub fn is_gpr_or_sp(self) -> bool {
        self.is_gpr() || self == REG_SP
    }
}

impl FReg {
    pub fn asm(self) -> u32 {
        match self.0 {
            0...31 => self.0 as u32,
            _ => panic!("invalid fp register."),
        }
    }
}
<commit_msg>arm64: more scratch registers<commit_after>use cpu::{FReg, Reg};

pub const REG_COUNT: usize = 31;
pub static REG_PARAMS: [Reg; 8] = [R0, R1, R2, R3, R4, R5, R6, R7];
pub static SCRATCH: [Reg; 5] = [R9, R12, R13, R14, R15];

pub const REG_RESULT: Reg = R0;
pub const REG_TMP1: Reg = R10;
pub const REG_TMP2: Reg = R11;
pub const REG_FP: Reg = R29;
pub const REG_LR: Reg = R30;
pub const REG_THREAD: Reg = R28;

pub const REG_SP: Reg = Reg(32);
pub const REG_ZERO: Reg = Reg(33);

pub const R0: Reg = Reg(0);
pub const R1: Reg = Reg(1);
pub const R2: Reg = Reg(2);
pub const R3: Reg = Reg(3);
pub const R4: Reg = Reg(4);
pub const R5: Reg = Reg(5);
pub const R6: Reg = Reg(6);
pub const R7: Reg = Reg(7);
pub const R8: Reg = Reg(8);
pub const R9: Reg = Reg(9);
pub const R10: Reg = Reg(10);
pub const R11: Reg = Reg(11);
pub const R12: Reg = Reg(12);
pub const R13: Reg = Reg(13);
pub const R14: Reg = Reg(14);
pub const R15: Reg = Reg(15);
pub const R16: Reg = Reg(16);
pub const R17: Reg = Reg(17);
pub const R18: Reg = Reg(18);
pub const R19: Reg = Reg(19);
pub const R20: Reg = Reg(20);
pub const R21: Reg = Reg(21);
pub const R22: Reg = Reg(22);
pub const R23: Reg = Reg(23);
pub const R24: Reg = Reg(24);
pub const R25: Reg = Reg(25);
pub const R26: Reg = Reg(26);
pub const R27: Reg = Reg(27);
pub const R28: Reg = Reg(28);
pub const R29: Reg = Reg(29);
pub const R30: Reg = Reg(30);

pub const FREG_RESULT: FReg = F0;
pub const FREG_TMP1: FReg = F1;
pub static FREG_PARAMS: [FReg; 8] = [F0, F1, F2, F3, F4, F5, F6, F7];

pub const F0: FReg = FReg(0);
pub const F1: FReg = FReg(1);
pub const F2: FReg = FReg(2);
pub const F3: FReg = FReg(3);
pub const F4: FReg = FReg(4);
pub const F5: FReg = FReg(5);
pub const F6: FReg = FReg(6);
pub const F7: FReg = FReg(7);
pub const F8: FReg = FReg(8);
pub const F9: FReg = FReg(9);
pub const F10: FReg = FReg(10);
pub const F11: FReg = FReg(11);
pub const F12: FReg = FReg(12);
pub const F13: FReg = FReg(13);
pub const F14: FReg = FReg(14);
pub const F15: FReg = FReg(15);
pub const F16: FReg = FReg(16);
pub const F17: FReg = FReg(17);
pub const F18: FReg = FReg(18);
pub const F19: FReg = FReg(19);
pub const F20: FReg = FReg(20);
pub const F21: FReg = FReg(21);
pub const F22: FReg = FReg(22);
pub const F23: FReg = FReg(23);
pub const F24: FReg = FReg(24);
pub const F25: FReg = FReg(25);
pub const F26: FReg = FReg(26);
pub const F27: FReg = FReg(27);
pub const F28: FReg = FReg(28);
pub const F29: FReg = FReg(29);
pub const F30: FReg = FReg(30);
pub const F31: FReg = FReg(31);

impl Reg {
    pub fn asm(self) -> u32 {
        match self {
            REG_SP => 31,
            REG_ZERO => 31,
            _ => self.0 as u32,
        }
    }

    pub fn is_gpr(self) -> bool {
        self.0 <= 30
    }

    pub fn is_gpr_or_zero(self) -> bool {
        self.is_gpr() || self == REG_ZERO
    }

    pub fn is_gpr_or_sp(self) -> bool {
        self.is_gpr() || self == REG_SP
    }
}

impl FReg {
    pub fn asm(self) -> u32 {
        match self.0 {
            0...31 => self.0 as u32,
            _ => panic!("invalid fp register."),
        }
    }
}
<|endoftext|>


<commit_before>#![feature(tcp)]

use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io;
use std::env;
use std::mem;
use std::str::FromStr;
use std::io::Read;
use std::io::Write;

fn main() {
    let port_ : Option<String> = env::args().skip(2).next();
    if let None = port_ {
        println!("usage: {} -p port", env::args().next().unwrap());
        return;
    }

    let port = u16::from_str(&port_.unwrap());
    if let Err(ref e) = port {
        println!("invalid port number given: {}", e);
        return;
    }

    let listener = TcpListener::bind(("127.0.0.1", port.unwrap()));
    if let Err(ref e) = listener {
        println!("failed to listen on port: {}", e);
        return;
    }

    for stream in listener.unwrap().incoming() {
        match stream {
            Ok(stream) => {
                thread::spawn(move|| {
                    handle_client(stream)
                });
            }
            Err(e) => {
                println!("failed to accept connection: {}", e);
            }
        }
    }
}

fn handle_client(mut stream: TcpStream) {
    let mut challenge : u32 = 0;
    let buf : &mut [u8; 4] = unsafe{ mem::transmute(&mut challenge) };
    let mut nread;

    let _ = stream.set_nodelay(true);

    loop {
        nread = 0;
        while nread < buf.len() {
            match stream.read(&mut buf[nread..]) {
                Ok(n) if n == 0 => return,
                Ok(n) => nread += n,
                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
                Err(e) => {
                    println!("{}", e);
                    return;
                }
            }
        }

        challenge = u32::from_be(challenge);
        if challenge == 0 {
            std::process::exit(0);
        }
        challenge = u32::to_be(challenge + 1);

        let mut nwritten = 0;
        while nwritten < buf.len() {
            match stream.write(&buf[nwritten..]) {
                Ok(n) => nwritten += n,
                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
                Err(e) => {
                    println!("{}", e);
                    return;
                }
            }
        }

        let _ = stream.flush();
    }
}
<commit_msg>Flushing TcpStream is a noop in Rust.<commit_after>#![feature(tcp)]

use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io;
use std::env;
use std::mem;
use std::str::FromStr;
use std::io::Read;
use std::io::Write;

fn main() {
    let port_ : Option<String> = env::args().skip(2).next();
    if let None = port_ {
        println!("usage: {} -p port", env::args().next().unwrap());
        return;
    }

    let port = u16::from_str(&port_.unwrap());
    if let Err(ref e) = port {
        println!("invalid port number given: {}", e);
        return;
    }

    let listener = TcpListener::bind(("127.0.0.1", port.unwrap()));
    if let Err(ref e) = listener {
        println!("failed to listen on port: {}", e);
        return;
    }

    for stream in listener.unwrap().incoming() {
        match stream {
            Ok(stream) => {
                thread::spawn(move|| {
                    handle_client(stream)
                });
            }
            Err(e) => {
                println!("failed to accept connection: {}", e);
            }
        }
    }
}

fn handle_client(mut stream: TcpStream) {
    let mut challenge : u32 = 0;
    let buf : &mut [u8; 4] = unsafe{ mem::transmute(&mut challenge) };
    let mut nread;

    let _ = stream.set_nodelay(true);

    loop {
        nread = 0;
        while nread < buf.len() {
            match stream.read(&mut buf[nread..]) {
                Ok(n) if n == 0 => return,
                Ok(n) => nread += n,
                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
                Err(e) => {
                    println!("{}", e);
                    return;
                }
            }
        }

        challenge = u32::from_be(challenge);
        if challenge == 0 {
            std::process::exit(0);
        }
        challenge = u32::to_be(challenge + 1);

        let mut nwritten = 0;
        while nwritten < buf.len() {
            match stream.write(&buf[nwritten..]) {
                Ok(n) => nwritten += n,
                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
                Err(e) => {
                    println!("{}", e);
                    return;
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2018 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use failure::SyncFailure;
use handlebars::Handlebars;
use clap;
use std::io::Write;
use std::path::Path;
use std::process::Command;

use common::ui::{UI, Status};
use export_docker::Result;
use error::Error;

pub const DEFAULT_OPERATOR_VERSION: &'static str = "0.5.1";
pub const OPERATOR_REPO_URL: &'static str = "https://kinvolk.github.io/habitat-operator\
                                             /helm/charts/stable/";

// Helm requirements.yaml template
const DEPSFILE: &'static str = include_str!("../defaults/HelmDeps.hbs");

pub struct Deps {
    operator_version: String,
    update: bool,
}

impl Deps {
    pub fn new_for_cli_matches(matches: &clap::ArgMatches) -> Self {
        Deps {
            operator_version: matches
                .value_of("OPERATOR_VERSION")
                .unwrap_or(DEFAULT_OPERATOR_VERSION)
                .to_owned(),
            update: matches.is_present("DOWNLOAD_DEPS"),
        }
    }

    pub fn generate(&mut self, write: &mut Write) -> Result<()> {
        let out = self.into_string()?;
        write.write(out.as_bytes())?;

        Ok(())
    }

    pub fn download<P: AsRef<Path>>(&self, dir: P, ui: &mut UI) -> Result<()> {
        if !self.update {
            return Ok(());
        }

        Command::new("helm")
            .arg("repo")
            .arg("add")
            .arg("habitat-operator")
            .arg(OPERATOR_REPO_URL)
            .spawn()
            .map_err(|_| Error::HelmLaunchFailed)
            .and_then(|mut c| if !c.wait()
                .map_err(|_| Error::HelmLaunchFailed)?
                .success()
            {
                Err(Error::HelmNotSetup(
                    String::from("Failed to update chart dependencies"),
                ))?
            } else {
                Ok(())
            })?;

        ui.status(Status::Downloading, "dependencies")?;

        Command::new("helm")
            .arg("dep")
            .arg("up")
            .arg(dir.as_ref().as_os_str())
            .spawn()?
            .wait()
            .map(|_| ())
            .map_err(From::from)
    }

    // TODO: Implement TryInto trait instead when it's in stable std crate
    fn into_string(&self) -> Result<String> {
        let json = json!({
            "operator_version": self.operator_version,
            "operator_repo_url": OPERATOR_REPO_URL,
        });

        Handlebars::new()
            .template_render(DEPSFILE, &json)
            .map_err(SyncFailure::new)
            .map_err(From::from)
    }
}
<commit_msg>pkg-export-helm: Update URL to habitat-operator<commit_after>// Copyright (c) 2018 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use failure::SyncFailure;
use handlebars::Handlebars;
use clap;
use std::io::Write;
use std::path::Path;
use std::process::Command;

use common::ui::{UI, Status};
use export_docker::Result;
use error::Error;

pub const DEFAULT_OPERATOR_VERSION: &'static str = "0.5.1";
pub const OPERATOR_REPO_URL: &'static str = "https://habitat-sh.github.io/\
                                             habitat-operator/helm/charts/stable/";

// Helm requirements.yaml template
const DEPSFILE: &'static str = include_str!("../defaults/HelmDeps.hbs");

pub struct Deps {
    operator_version: String,
    update: bool,
}

impl Deps {
    pub fn new_for_cli_matches(matches: &clap::ArgMatches) -> Self {
        Deps {
            operator_version: matches
                .value_of("OPERATOR_VERSION")
                .unwrap_or(DEFAULT_OPERATOR_VERSION)
                .to_owned(),
            update: matches.is_present("DOWNLOAD_DEPS"),
        }
    }

    pub fn generate(&mut self, write: &mut Write) -> Result<()> {
        let out = self.into_string()?;
        write.write(out.as_bytes())?;

        Ok(())
    }

    pub fn download<P: AsRef<Path>>(&self, dir: P, ui: &mut UI) -> Result<()> {
        if !self.update {
            return Ok(());
        }

        Command::new("helm")
            .arg("repo")
            .arg("add")
            .arg("habitat-operator")
            .arg(OPERATOR_REPO_URL)
            .spawn()
            .map_err(|_| Error::HelmLaunchFailed)
            .and_then(|mut c| if !c.wait()
                .map_err(|_| Error::HelmLaunchFailed)?
                .success()
            {
                Err(Error::HelmNotSetup(
                    String::from("Failed to update chart dependencies"),
                ))?
            } else {
                Ok(())
            })?;

        ui.status(Status::Downloading, "dependencies")?;

        Command::new("helm")
            .arg("dep")
            .arg("up")
            .arg(dir.as_ref().as_os_str())
            .spawn()?
            .wait()
            .map(|_| ())
            .map_err(From::from)
    }

    // TODO: Implement TryInto trait instead when it's in stable std crate
    fn into_string(&self) -> Result<String> {
        let json = json!({
            "operator_version": self.operator_version,
            "operator_repo_url": OPERATOR_REPO_URL,
        });

        Handlebars::new()
            .template_render(DEPSFILE, &json)
            .map_err(SyncFailure::new)
            .map_err(From::from)
    }
}
<|endoftext|>


<commit_before>// Copyright 2018 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use rand_core;
use rand_core::le::read_u32_into;
use rand_core::impls::{fill_bytes_via_next, next_u64_via_u32};
use rand_core::{RngCore, SeedableRng};

/// A Xoroshiro64** random number generator.
///
/// The xoshiro64** algorithm is not suitable for cryptographic purposes, but
/// is very fast and has excellent statistical properties.
///
/// The algorithm used here is translated from [the `xoroshiro64starstar.c`
/// reference source code](http://xoshiro.di.unimi.it/xoroshiro64starstar.c) by
/// David Blackman and Sebastiano Vigna.
#[allow(missing_copy_implementations)]
#[derive(Debug, Clone)]
pub struct Xoroshiro64StarStar {
    s0: u32,
    s1: u32,
}

impl RngCore for Xoroshiro64StarStar {
    #[inline]
    fn next_u32(&mut self) -> u32 {
        let r = starstar_u32!(self.s0);
        impl_xoroshiro_u32!(self);
        r
    }

    #[inline]
    fn next_u64(&mut self) -> u64 {
        next_u64_via_u32(self)
    }

    #[inline]
    fn fill_bytes(&mut self, dest: &mut [u8]) {
        fill_bytes_via_next(self, dest);
    }

    #[inline]
    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
        self.fill_bytes(dest);
        Ok(())
    }
}

impl SeedableRng for Xoroshiro64StarStar {
    type Seed = [u8; 8];

    /// Create a new `Xoroshiro64StarStar`.  If `seed` is entirely 0, it will be
    /// mapped to a different seed.
    fn from_seed(seed: [u8; 8]) -> Xoroshiro64StarStar {
        deal_with_zero_seed!(seed, Self);
        let mut s = [0; 2];
        read_u32_into(&seed, &mut s);

        Xoroshiro64StarStar {
            s0: s[0],
            s1: s[1],
        }
    }

    /// Seed a `Xoroshiro64StarStar` from a `u64` using `SplitMix64`.
    fn seed_from_u64(seed: u64) -> Xoroshiro64StarStar {
        from_splitmix!(seed)
    }
}

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

    #[test]
    fn reference() {
        let mut rng = Xoroshiro64StarStar::from_seed([1, 0, 0, 0, 2, 0, 0, 0]);
        // These values were produced with the reference implementation:
        // http://xoshiro.di.unimi.it/xoshiro64starstar.c
        let expected = [
            3802928447, 813792938, 1618621494, 2955957307, 3252880261,
            1129983909, 2539651700, 1327610908, 1757650787, 2763843748,
        ];
        for &e in &expected {
            assert_eq!(rng.next_u32(), e);
        }
    }

    #[test]
    fn zero_seed() {
        let mut rng = Xoroshiro64StarStar::seed_from_u64(0);
        assert_ne!(rng.next_u64(), 0);
    }
}
<commit_msg>rand_xoshiro: More consistent spelling<commit_after>// Copyright 2018 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use rand_core;
use rand_core::le::read_u32_into;
use rand_core::impls::{fill_bytes_via_next, next_u64_via_u32};
use rand_core::{RngCore, SeedableRng};

/// A xoroshiro64** random number generator.
///
/// The xoshiro64** algorithm is not suitable for cryptographic purposes, but
/// is very fast and has excellent statistical properties.
///
/// The algorithm used here is translated from [the `xoroshiro64starstar.c`
/// reference source code](http://xoshiro.di.unimi.it/xoroshiro64starstar.c) by
/// David Blackman and Sebastiano Vigna.
#[allow(missing_copy_implementations)]
#[derive(Debug, Clone)]
pub struct Xoroshiro64StarStar {
    s0: u32,
    s1: u32,
}

impl RngCore for Xoroshiro64StarStar {
    #[inline]
    fn next_u32(&mut self) -> u32 {
        let r = starstar_u32!(self.s0);
        impl_xoroshiro_u32!(self);
        r
    }

    #[inline]
    fn next_u64(&mut self) -> u64 {
        next_u64_via_u32(self)
    }

    #[inline]
    fn fill_bytes(&mut self, dest: &mut [u8]) {
        fill_bytes_via_next(self, dest);
    }

    #[inline]
    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
        self.fill_bytes(dest);
        Ok(())
    }
}

impl SeedableRng for Xoroshiro64StarStar {
    type Seed = [u8; 8];

    /// Create a new `Xoroshiro64StarStar`.  If `seed` is entirely 0, it will be
    /// mapped to a different seed.
    fn from_seed(seed: [u8; 8]) -> Xoroshiro64StarStar {
        deal_with_zero_seed!(seed, Self);
        let mut s = [0; 2];
        read_u32_into(&seed, &mut s);

        Xoroshiro64StarStar {
            s0: s[0],
            s1: s[1],
        }
    }

    /// Seed a `Xoroshiro64StarStar` from a `u64` using `SplitMix64`.
    fn seed_from_u64(seed: u64) -> Xoroshiro64StarStar {
        from_splitmix!(seed)
    }
}

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

    #[test]
    fn reference() {
        let mut rng = Xoroshiro64StarStar::from_seed([1, 0, 0, 0, 2, 0, 0, 0]);
        // These values were produced with the reference implementation:
        // http://xoshiro.di.unimi.it/xoshiro64starstar.c
        let expected = [
            3802928447, 813792938, 1618621494, 2955957307, 3252880261,
            1129983909, 2539651700, 1327610908, 1757650787, 2763843748,
        ];
        for &e in &expected {
            assert_eq!(rng.next_u32(), e);
        }
    }

    #[test]
    fn zero_seed() {
        let mut rng = Xoroshiro64StarStar::seed_from_u64(0);
        assert_ne!(rng.next_u64(), 0);
    }
}
<|endoftext|>


<commit_before>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{gl, Texture, Sampler};
use super::gl::types::{GLenum, GLuint, GLint, GLfloat, GLsizei, GLvoid};
use tex::*;
use Blob;

fn kind_to_gl(t: ::tex::TextureKind) -> GLenum {
    match t {
        Texture1D => gl::TEXTURE_1D,
        Texture1DArray => gl::TEXTURE_1D_ARRAY,
        Texture2D => gl::TEXTURE_2D,
        Texture2DArray => gl::TEXTURE_2D_ARRAY,
        TextureCube => gl::TEXTURE_CUBE_MAP,
        Texture3D => gl::TEXTURE_3D,
    }
}

fn format_to_gl(t: ::tex::TextureFormat) -> GLenum {
    match t {
        RGB8 => gl::RGB8,
        RGBA8 => gl::RGBA8,
    }
}

fn format_to_glpixel(t: ::tex::TextureFormat) -> GLenum {
    match t {
        RGB8 => gl::RGB,
        RGBA8 => gl::RGBA
    }
}

fn format_to_gltype(t: ::tex::TextureFormat) -> GLenum {
    match t {
        RGB8 | RGBA8 => gl::UNSIGNED_BYTE,
    }
}

/// Create a texture, assuming TexStorage* isn't available.
pub fn make_without_storage(info: ::tex::TextureInfo) -> Texture {
    let name = make_texture(info);

    let fmt = format_to_gl(info.format) as GLint;
    let pix = format_to_glpixel(info.format);
    let typ = format_to_gltype(info.format);

    let kind = kind_to_gl(info.kind);

    unsafe {
        match info.kind {
            Texture1D => {
                gl::TexImage1D(
                    kind,
                    0,
                    fmt,
                    info.width as GLsizei,
                    0,
                    pix,
                    typ,
                    ::std::ptr::null(),
                );
            },
            Texture1DArray => {
                gl::TexImage2D(
                    kind,
                    0,
                    fmt,
                    info.width as GLsizei,
                    info.height as GLsizei,
                    0,
                    pix,
                    typ,
                    ::std::ptr::null(),
                );
            },
            Texture2D => {
                gl::TexImage2D(
                    kind,
                    0,
                    fmt,
                    info.width as GLsizei,
                    info.height as GLsizei,
                    0,
                    pix,
                    typ,
                    ::std::ptr::null(),
                );
            },
            TextureCube => unimplemented!(),
            Texture2DArray | Texture3D => {
                gl::TexImage3D(
                    kind,
                    0,
                    fmt,
                    info.width as GLsizei,
                    info.height as GLsizei,
                    info.depth as GLsizei,
                    0,
                    pix,
                    typ,
                    ::std::ptr::null(),
                );
            },
        }
    }

    name
}

/// Create a texture, assuming TexStorage is available.
pub fn make_with_storage(info: ::tex::TextureInfo) -> Texture {
    use std::cmp::max;

    fn min(a: u8, b: u8) -> GLint {
        ::std::cmp::min(a, b) as GLint
    }

    fn mip_level1(w: u16) -> u8 {
        ((w as f32).log2() + 1.0) as u8
    }

    fn mip_level2(w: u16, h: u16) -> u8 {
        ((max(w, h) as f32).log2() + 1.0) as u8
    }

    fn mip_level3(w: u16, h: u16, d: u16) -> u8 {
        ((max(w, max(h, d)) as f32).log2() + 1.0) as u8
    }

    let name = make_texture(info);

    let fmt = format_to_gl(info.format);
    let kind = kind_to_gl(info.kind);

    match info.kind {
        Texture1D => {
            gl::TexStorage1D(
                kind,
                min(info.mipmap_range.val1(), mip_level1(info.width)),
                fmt,
                info.width as GLsizei
            );
        },
        Texture1DArray => {
            gl::TexStorage2D(
                kind,
                min(info.mipmap_range.val1(), mip_level1(info.width)),
                fmt,
                info.width as GLsizei,
                info.height as GLsizei,
            );
        },
        Texture2D => {
            gl::TexStorage2D(
                kind,
                min(info.mipmap_range.val1(), mip_level2(info.width, info.height)),
                fmt,
                info.width as GLsizei,
                info.height as GLsizei,
            );
        },
        TextureCube => unimplemented!(),
        Texture2DArray => {
            gl::TexStorage3D(
                kind,
                min(info.mipmap_range.val1(), mip_level2(info.width, info.height)),
                fmt,
                info.width as GLsizei,
                info.height as GLsizei,
                info.depth as GLsizei,
            );
        },
        Texture3D => {
            gl::TexStorage3D(
                kind,
                min(info.mipmap_range.val1(), mip_level3(info.width, info.height, info.depth)),
                fmt,
                info.width as GLsizei,
                info.height as GLsizei,
                info.depth as GLsizei,
            );
        },
    }

    name
}

/// Bind a texture + sampler to a given slot.
pub fn bind_texture(loc: GLuint, tex: Texture, sam: Sampler, info: ::tex::TextureInfo) {
    gl::ActiveTexture(gl::TEXTURE0 + loc as GLenum);
    gl::BindSampler(loc, sam);
    gl::BindTexture(kind_to_gl(info.kind), tex);
}

pub fn update_texture(tex: Texture, img: ::tex::ImageInfo, tex_info: ::tex::TextureInfo,
                      data: Box<Blob + Send>) {
    debug_assert!(img.width as u32 * img.height as u32 * img.depth as u32 == data.get_size() as u32);

    let data = data.get_address() as *const GLvoid;
    let pix = format_to_glpixel(tex_info.format);
    let typ = format_to_gltype(tex_info.format);

    gl::BindTexture(kind_to_gl(tex_info.kind), tex);

    unsafe {
        match tex_info.kind {
            Texture1D => {
                gl::TexSubImage1D(
                    kind_to_gl(tex_info.kind),
                    img.mipmap as GLint,
                    img.xoffset as GLint,
                    img.width as GLint,
                    pix,
                    typ,
                    data,
                );
            },
            Texture1DArray | Texture2D => {
                gl::TexSubImage2D(
                    kind_to_gl(tex_info.kind),
                    img.mipmap as GLint,
                    img.xoffset as GLint,
                    img.yoffset as GLint,
                    img.width as GLint,
                    img.height as GLint,
                    pix,
                    typ,
                    data,
                );
            },
            TextureCube => unimplemented!(),
            Texture2DArray | Texture3D => {
                gl::TexSubImage3D(
                    kind_to_gl(tex_info.kind),
                    img.mipmap as GLint,
                    img.xoffset as GLint,
                    img.yoffset as GLint,
                    img.zoffset as GLint,
                    img.width as GLint,
                    img.height as GLint,
                    img.depth as GLint,
                    pix,
                    typ,
                    data,
                );
            }
        }
    }
}

/// Common texture creation routine, just binds and sets mipmap ranges.
fn make_texture(info: ::tex::TextureInfo) -> Texture {
    let mut name = 0 as Texture;
    unsafe {
        gl::GenTextures(1, &mut name);
    }

    let k = kind_to_gl(info.kind);
    gl::BindTexture(k, name);

    name
}

fn wrap_to_gl(w: WrapMode) -> GLenum {
    match w {
        Tile => gl::REPEAT,
        Mirror => gl::MIRRORED_REPEAT,
        Clamp => gl::CLAMP_TO_EDGE
    }
}

pub fn make_sampler(info: ::tex::SamplerInfo) -> Sampler {
    let mut name = 0 as Sampler;
    unsafe {
        gl::GenSamplers(1, &mut name);
    }

    let (min, mag) = match info.filtering {
        Scale => (gl::NEAREST, gl::NEAREST),
        Mipmap => (gl::NEAREST_MIPMAP_NEAREST, gl::NEAREST),
        Bilinear => (gl::LINEAR_MIPMAP_NEAREST, gl::LINEAR),
        Trilinear => (gl::LINEAR_MIPMAP_LINEAR, gl::LINEAR),
        Anisotropic(fac) => {
            gl::SamplerParameterf(name, gl::TEXTURE_MAX_ANISOTROPY_EXT, fac as GLfloat);
            (gl::LINEAR_MIPMAP_LINEAR, gl::LINEAR)
        }
    };

    gl::SamplerParameteri(name, gl::TEXTURE_MIN_FILTER, min as GLint);
    gl::SamplerParameteri(name, gl::TEXTURE_MAG_FILTER, mag as GLint);

    let (s, t, r) = info.wrap_mode;
    gl::SamplerParameteri(name, gl::TEXTURE_WRAP_S, wrap_to_gl(s) as GLint);
    gl::SamplerParameteri(name, gl::TEXTURE_WRAP_T, wrap_to_gl(t) as GLint);
    gl::SamplerParameteri(name, gl::TEXTURE_WRAP_R, wrap_to_gl(r) as GLint);

    gl::SamplerParameterf(name, gl::TEXTURE_LOD_BIAS, info.lod_bias);

    let (base, max) = info.mipmap_range;
    gl::SamplerParameteri(name, gl::TEXTURE_BASE_LEVEL, base as GLint);
    gl::SamplerParameteri(name, gl::TEXTURE_MAX_LEVEL, max as GLint);

    name
}
<commit_msg>Tighten up whitespace<commit_after>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{gl, Texture, Sampler};
use super::gl::types::{GLenum, GLuint, GLint, GLfloat, GLsizei, GLvoid};
use tex::*;
use Blob;

fn kind_to_gl(t: ::tex::TextureKind) -> GLenum {
    match t {
        Texture1D => gl::TEXTURE_1D,
        Texture1DArray => gl::TEXTURE_1D_ARRAY,
        Texture2D => gl::TEXTURE_2D,
        Texture2DArray => gl::TEXTURE_2D_ARRAY,
        TextureCube => gl::TEXTURE_CUBE_MAP,
        Texture3D => gl::TEXTURE_3D,
    }
}

fn format_to_gl(t: ::tex::TextureFormat) -> GLenum {
    match t {
        RGB8 => gl::RGB8,
        RGBA8 => gl::RGBA8,
    }
}

fn format_to_glpixel(t: ::tex::TextureFormat) -> GLenum {
    match t {
        RGB8 => gl::RGB,
        RGBA8 => gl::RGBA
    }
}

fn format_to_gltype(t: ::tex::TextureFormat) -> GLenum {
    match t {
        RGB8 | RGBA8 => gl::UNSIGNED_BYTE,
    }
}

/// Create a texture, assuming TexStorage* isn't available.
pub fn make_without_storage(info: ::tex::TextureInfo) -> Texture {
    let name = make_texture(info);

    let fmt = format_to_gl(info.format) as GLint;
    let pix = format_to_glpixel(info.format);
    let typ = format_to_gltype(info.format);

    let kind = kind_to_gl(info.kind);

    unsafe {
        match info.kind {
            Texture1D => {
                gl::TexImage1D(
                    kind,
                    0,
                    fmt,
                    info.width as GLsizei,
                    0,
                    pix,
                    typ,
                    ::std::ptr::null(),
                );
            },
            Texture1DArray => {
                gl::TexImage2D(
                    kind,
                    0,
                    fmt,
                    info.width as GLsizei,
                    info.height as GLsizei,
                    0,
                    pix,
                    typ,
                    ::std::ptr::null(),
                );
            },
            Texture2D => {
                gl::TexImage2D(
                    kind,
                    0,
                    fmt,
                    info.width as GLsizei,
                    info.height as GLsizei,
                    0,
                    pix,
                    typ,
                    ::std::ptr::null(),
                );
            },
            TextureCube => unimplemented!(),
            Texture2DArray | Texture3D => {
                gl::TexImage3D(
                    kind,
                    0,
                    fmt,
                    info.width as GLsizei,
                    info.height as GLsizei,
                    info.depth as GLsizei,
                    0,
                    pix,
                    typ,
                    ::std::ptr::null(),
                );
            },
        }
    }

    name
}

/// Create a texture, assuming TexStorage is available.
pub fn make_with_storage(info: ::tex::TextureInfo) -> Texture {
    use std::cmp::max;

    fn min(a: u8, b: u8) -> GLint {
        ::std::cmp::min(a, b) as GLint
    }

    fn mip_level1(w: u16) -> u8 {
        ((w as f32).log2() + 1.0) as u8
    }

    fn mip_level2(w: u16, h: u16) -> u8 {
        ((max(w, h) as f32).log2() + 1.0) as u8
    }

    fn mip_level3(w: u16, h: u16, d: u16) -> u8 {
        ((max(w, max(h, d)) as f32).log2() + 1.0) as u8
    }

    let name = make_texture(info);

    let fmt = format_to_gl(info.format);
    let kind = kind_to_gl(info.kind);

    match info.kind {
        Texture1D => {
            gl::TexStorage1D(
                kind,
                min(info.mipmap_range.val1(), mip_level1(info.width)),
                fmt,
                info.width as GLsizei
            );
        },
        Texture1DArray => {
            gl::TexStorage2D(
                kind,
                min(info.mipmap_range.val1(), mip_level1(info.width)),
                fmt,
                info.width as GLsizei,
                info.height as GLsizei,
            );
        },
        Texture2D => {
            gl::TexStorage2D(
                kind,
                min(info.mipmap_range.val1(), mip_level2(info.width, info.height)),
                fmt,
                info.width as GLsizei,
                info.height as GLsizei,
            );
        },
        TextureCube => unimplemented!(),
        Texture2DArray => {
            gl::TexStorage3D(
                kind,
                min(info.mipmap_range.val1(), mip_level2(info.width, info.height)),
                fmt,
                info.width as GLsizei,
                info.height as GLsizei,
                info.depth as GLsizei,
            );
        },
        Texture3D => {
            gl::TexStorage3D(
                kind,
                min(info.mipmap_range.val1(), mip_level3(info.width, info.height, info.depth)),
                fmt,
                info.width as GLsizei,
                info.height as GLsizei,
                info.depth as GLsizei,
            );
        },
    }

    name
}

/// Bind a texture + sampler to a given slot.
pub fn bind_texture(loc: GLuint, tex: Texture, sam: Sampler, info: ::tex::TextureInfo) {
    gl::ActiveTexture(gl::TEXTURE0 + loc as GLenum);
    gl::BindSampler(loc, sam);
    gl::BindTexture(kind_to_gl(info.kind), tex);
}

pub fn update_texture(tex: Texture, img: ::tex::ImageInfo, tex_info: ::tex::TextureInfo,
                      data: Box<Blob + Send>) {
    debug_assert!(img.width as u32 * img.height as u32 * img.depth as u32 == data.get_size() as u32);

    let data = data.get_address() as *const GLvoid;
    let pix = format_to_glpixel(tex_info.format);
    let typ = format_to_gltype(tex_info.format);

    gl::BindTexture(kind_to_gl(tex_info.kind), tex);

    unsafe {
        match tex_info.kind {
            Texture1D => {
                gl::TexSubImage1D(
                    kind_to_gl(tex_info.kind),
                    img.mipmap as GLint,
                    img.xoffset as GLint,
                    img.width as GLint,
                    pix,
                    typ,
                    data,
                );
            },
            Texture1DArray | Texture2D => {
                gl::TexSubImage2D(
                    kind_to_gl(tex_info.kind),
                    img.mipmap as GLint,
                    img.xoffset as GLint,
                    img.yoffset as GLint,
                    img.width as GLint,
                    img.height as GLint,
                    pix,
                    typ,
                    data,
                );
            },
            TextureCube => unimplemented!(),
            Texture2DArray | Texture3D => {
                gl::TexSubImage3D(
                    kind_to_gl(tex_info.kind),
                    img.mipmap as GLint,
                    img.xoffset as GLint,
                    img.yoffset as GLint,
                    img.zoffset as GLint,
                    img.width as GLint,
                    img.height as GLint,
                    img.depth as GLint,
                    pix,
                    typ,
                    data,
                );
            }
        }
    }
}

/// Common texture creation routine, just binds and sets mipmap ranges.
fn make_texture(info: ::tex::TextureInfo) -> Texture {
    let mut name = 0 as Texture;
    unsafe {
        gl::GenTextures(1, &mut name);
    }

    let k = kind_to_gl(info.kind);
    gl::BindTexture(k, name);

    name
}

fn wrap_to_gl(w: WrapMode) -> GLenum {
    match w {
        Tile => gl::REPEAT,
        Mirror => gl::MIRRORED_REPEAT,
        Clamp => gl::CLAMP_TO_EDGE
    }
}

pub fn make_sampler(info: ::tex::SamplerInfo) -> Sampler {
    let mut name = 0 as Sampler;
    unsafe {
        gl::GenSamplers(1, &mut name);
    }

    let (min, mag) = match info.filtering {
        Scale => (gl::NEAREST, gl::NEAREST),
        Mipmap => (gl::NEAREST_MIPMAP_NEAREST, gl::NEAREST),
        Bilinear => (gl::LINEAR_MIPMAP_NEAREST, gl::LINEAR),
        Trilinear => (gl::LINEAR_MIPMAP_LINEAR, gl::LINEAR),
        Anisotropic(fac) => {
            gl::SamplerParameterf(name, gl::TEXTURE_MAX_ANISOTROPY_EXT, fac as GLfloat);
            (gl::LINEAR_MIPMAP_LINEAR, gl::LINEAR)
        }
    };

    gl::SamplerParameteri(name, gl::TEXTURE_MIN_FILTER, min as GLint);
    gl::SamplerParameteri(name, gl::TEXTURE_MAG_FILTER, mag as GLint);

    let (s, t, r) = info.wrap_mode;
    gl::SamplerParameteri(name, gl::TEXTURE_WRAP_S, wrap_to_gl(s) as GLint);
    gl::SamplerParameteri(name, gl::TEXTURE_WRAP_T, wrap_to_gl(t) as GLint);
    gl::SamplerParameteri(name, gl::TEXTURE_WRAP_R, wrap_to_gl(r) as GLint);

    gl::SamplerParameterf(name, gl::TEXTURE_LOD_BIAS, info.lod_bias);

    let (base, max) = info.mipmap_range;
    gl::SamplerParameteri(name, gl::TEXTURE_BASE_LEVEL, base as GLint);
    gl::SamplerParameteri(name, gl::TEXTURE_MAX_LEVEL, max as GLint);

    name
}
<|endoftext|>


<commit_before>use time;
use std::io::timer::sleep;

use GameWindow;
use keyboard;
use mouse;
use event;

/// Render argument.
#[deriving(Clone)]
pub struct RenderArgs {
    /// Extrapolated time in seconds, used to do smooth animation.
    pub ext_dt: f64,
    /// The width of rendered area.
    pub width: u32,
    /// The height of rendered area.
    pub height: u32,
}

/// Update argument.
#[deriving(Clone)]
pub struct UpdateArgs {
    /// Delta time in seconds.
    pub dt: f64,
}

/// Key press arguments.
#[deriving(Clone)]
pub struct KeyPressArgs {
    /// Keyboard key.
    pub key: keyboard::Key,
}

/// Key release arguments.
#[deriving(Clone)]
pub struct KeyReleaseArgs {
    /// Keyboard key.
    pub key: keyboard::Key,
}

/// Mouse press arguments.
#[deriving(Clone)]
pub struct MousePressArgs {
    /// Mouse button.
    pub button: mouse::Button,
}

/// Mouse release arguments.
#[deriving(Clone)]
pub struct MouseReleaseArgs {
    /// Mouse button.
    pub button: mouse::Button,
}

/// Mouse move arguments.
#[deriving(Clone)]
pub struct MouseMoveArgs {
    /// x.
    pub x: f64,
    /// y.
    pub y: f64,
}

/// Mouse relative move arguments.
#[deriving(Clone)]
pub struct MouseRelativeMoveArgs {
    /// Delta x.
    pub dx: f64,
    /// Delta y.
    pub dy: f64,
}

/// Mouse scroll arguments.
#[deriving(Clone)]
pub struct MouseScrollArgs {
    /// x.
    pub x: f64,
    /// y.
    pub y: f64,
}

/// Contains the different game events.
#[deriving(Clone)]
pub enum GameEvent {
    /// Render graphics.
    Render(RenderArgs),
    /// Update physical state of the game.
    Update(UpdateArgs),
    /// Pressed a keyboard key.
    KeyPress(KeyPressArgs),
    /// Released a keyboard key.
    KeyRelease(KeyReleaseArgs),
    /// Pressed a mouse button.
    MousePress(MousePressArgs),
    /// Released a mouse button.
    MouseRelease(MouseReleaseArgs),
    /// Moved mouse cursor.
    MouseMove(MouseMoveArgs),
    /// Moved mouse relative, not bounded by cursor.
    MouseRelativeMove(MouseRelativeMoveArgs),
    /// Scrolled mouse.
    MouseScroll(MouseScrollArgs)
}

enum GameIteratorState {
    RenderState,
    SwapBuffersState,
    PrepareUpdateLoopState,
    UpdateLoopState,
    HandleEventsState,
    MouseRelativeMoveState(f64, f64),
    UpdateState,
}

/// Settings for the game loop behavior.
#[deriving(Clone)]
pub struct GameIteratorSettings {
    /// The number of updates per second (UPS).
    pub updates_per_second: u64,
    /// The maximum number of frames per second (FPS target).
    pub max_frames_per_second: u64,
}

/// A game loop iterator.
///
/// Example:
///
/// ```Rust
/// let game_iter_settings = GameIteratorSettings {
///     updates_per_second: 120,
///     max_frames_per_second: 60,
/// };
/// let mut game_iter = GameIterator::new(&mut window, &game_iter_settings);
/// loop {
///     match game_iter.next() {
///         None => break,
///         Some(mut e) => match e {
///             Render(ref mut args) => {
///                 // Create graphics context with absolute coordinates.
///                 let c = Context::abs(args.width as f64, args.height as f64);
///                 // Do rendering here.
///             },
///             _ => {},
///         },
///     }
/// }
/// ```
pub struct GameIterator<'a, W> {
    game_window: &'a mut W,
    state: GameIteratorState,
    last_update: u64,
    update_time_in_ns: u64,
    dt: f64,
    min_updates_per_frame: u64,
    min_ns_per_frame: u64,
    start_render: u64,
    next_render: u64,
    updated: u64,
}

static billion: u64 = 1_000_000_000;

impl<'a, W: GameWindow> GameIterator<'a, W> {
    /// Creates a new game iterator.
    pub fn new(
        game_window: &'a mut W,
        settings: &GameIteratorSettings
    ) -> GameIterator<'a, W> {
        let updates_per_second: u64 = settings.updates_per_second;
        let max_frames_per_second: u64 = settings.max_frames_per_second;

        let start = time::precise_time_ns();
        GameIterator {
            game_window: game_window,
            state: RenderState,
            last_update: start,
            update_time_in_ns: billion / updates_per_second,
            dt: 1.0 / updates_per_second as f64,
            // You can make this lower if needed.
            min_updates_per_frame: updates_per_second / max_frames_per_second,
            min_ns_per_frame: billion / max_frames_per_second,
            start_render: start,
            next_render: start,
            updated: 0,
        }
    }
}

impl<'a, W: GameWindow>
Iterator<GameEvent>
for GameIterator<'a, W> {
    /// Returns the next game event.
    fn next(&mut self) -> Option<GameEvent> {
        match self.state {
            RenderState => {
                if self.game_window.should_close() { return None; }

                self.start_render = time::precise_time_ns();
                // Rendering code
                let (w, h) = self.game_window.get_size();
                if w != 0 && h != 0 {
                    // Swap buffers next time.
                    self.state = SwapBuffersState;
                    return Some(Render(RenderArgs {
                            // Extrapolate time forward to allow smooth motion.
                            // 'start_render' is always bigger than 'last_update'.
                            ext_dt: (self.start_render - self.last_update) as f64 / billion as f64,
                            width: w,
                            height: h,
                        }
                    ));
                }

                self.state = PrepareUpdateLoopState;
                return self.next();
            },
            SwapBuffersState => {
                self.game_window.swap_buffers();
                self.state = PrepareUpdateLoopState;
                return self.next();
            },
            PrepareUpdateLoopState => {
                self.updated = 0;
                self.next_render = self.start_render + self.min_ns_per_frame;
                self.state = UpdateLoopState;
                return self.next();
            },
            UpdateLoopState => {
                let got_min_updates = self.updated < self.min_updates_per_frame;
                let got_time_to_update = time::precise_time_ns() < self.next_render;
                let before_next_frame = self.last_update + self.update_time_in_ns < self.next_render;

                if ( got_time_to_update || got_min_updates ) && before_next_frame {
                    self.state = HandleEventsState;
                    return self.next();
                }

                // Wait if possible.
                // Convert to ms because that is what the sleep function takes.
                let t = (self.next_render - time::precise_time_ns() ) / 1_000_000;
                if t > 1 && t < 1000000 { // The second half just checks if it overflowed,
                                          // which tells us that t should have been negative
                                          // and we are running slow and shouldn't sleep.
                    sleep( t );
                }
                self.state = RenderState;
                return self.next();
            },
            HandleEventsState => {
                // Handle all events before updating.
                return match self.game_window.poll_event() {
                    event::KeyPressed(key) => {
                        Some(KeyPress(KeyPressArgs {
                            key: key,
                        }))
                    },
                    event::KeyReleased(key) => {
                        Some(KeyRelease(KeyReleaseArgs {
                            key: key,
                        }))
                    },
                    event::MouseButtonPressed(mouse_button) => {
                        Some(MousePress(MousePressArgs {
                            button: mouse_button,
                        }))
                    },
                    event::MouseButtonReleased(mouse_button) => {
                        Some(MouseRelease(MouseReleaseArgs {
                            button: mouse_button,
                        }))
                    },
                    event::MouseMoved(x, y, relative_move) => {
                        match relative_move {
                            Some((dx, dy)) =>
                                self.state = MouseRelativeMoveState(dx, dy),
                            None => {},
                        };
                        Some(MouseMove(MouseMoveArgs {
                            x: x,
                            y: y,
                        }))
                    },
                    event::MouseScrolled(x, y) => {
                        Some(MouseScroll(MouseScrollArgs {
                            x: x,
                            y: y
                        }))
                    },
                    event::NoEvent => {
                        self.state = UpdateState;
                        self.next()
                    },
                }
            },
            MouseRelativeMoveState(dx, dy) => {
                self.state = HandleEventsState;
                return Some(MouseRelativeMove(MouseRelativeMoveArgs {
                    dx: dx,
                    dy: dy,
                }));
            },
            UpdateState => {
                self.updated += 1;
                self.state = UpdateLoopState;
                self.last_update += self.update_time_in_ns;
                return Some(Update(UpdateArgs{
                    dt: self.dt,
                }));
            },
        };

        /*
        // copied.

        while !self.should_close(game_window) {

            let start_render = time::precise_time_ns();

            // Rendering code
            let (w, h) = game_window.get_size();
            if w != 0 && h != 0 {
                self.viewport(game_window);
                let mut gl = Gl::new(&mut gl_data, asset_store);
                bg.clear(&mut gl);
                // Extrapolate time forward to allow smooth motion.
                // 'now' is always bigger than 'last_update'.
                let ext_dt = (start_render - last_update) as f64 / billion as f64;
                self.render(
                    ext_dt,
                    &context
                        .trans(-1.0, 1.0)
                        .scale(2.0 / w as f64, -2.0 / h as f64)
                        .store_view(),
                    &mut gl
                        );
                self.swap_buffers(game_window);
            }

            let next_render = start_render + min_ns_per_frame;

            // Update gamestate
            let mut updated = 0;

            while // If we haven't reached the required number of updates yet
                  ( updated < min_updates_per_frame ||
                    // Or we have the time to update further
                    time::precise_time_ns() < next_render ) &&
                  //And we haven't already progressed time to far
                  last_update + update_time_in_ns < next_render {

                self.handle_events(game_window, asset_store);
                self.update(dt, asset_store);

                updated += 1;
                last_update += update_time_in_ns;
            }

            // Wait if possible

            let t = (next_render - time::precise_time_ns() ) / 1_000_000;
            if t > 1 && t < 1000000 { // The second half just checks if it overflowed,
                                      // which tells us that t should have been negative
                                      // and we are running slow and shouldn't sleep.
                sleep( t );
            }

        }
        */
    }
}
<commit_msg>Made `game_window` public<commit_after>use time;
use std::io::timer::sleep;

use GameWindow;
use keyboard;
use mouse;
use event;

/// Render argument.
#[deriving(Clone)]
pub struct RenderArgs {
    /// Extrapolated time in seconds, used to do smooth animation.
    pub ext_dt: f64,
    /// The width of rendered area.
    pub width: u32,
    /// The height of rendered area.
    pub height: u32,
}

/// Update argument.
#[deriving(Clone)]
pub struct UpdateArgs {
    /// Delta time in seconds.
    pub dt: f64,
}

/// Key press arguments.
#[deriving(Clone)]
pub struct KeyPressArgs {
    /// Keyboard key.
    pub key: keyboard::Key,
}

/// Key release arguments.
#[deriving(Clone)]
pub struct KeyReleaseArgs {
    /// Keyboard key.
    pub key: keyboard::Key,
}

/// Mouse press arguments.
#[deriving(Clone)]
pub struct MousePressArgs {
    /// Mouse button.
    pub button: mouse::Button,
}

/// Mouse release arguments.
#[deriving(Clone)]
pub struct MouseReleaseArgs {
    /// Mouse button.
    pub button: mouse::Button,
}

/// Mouse move arguments.
#[deriving(Clone)]
pub struct MouseMoveArgs {
    /// x.
    pub x: f64,
    /// y.
    pub y: f64,
}

/// Mouse relative move arguments.
#[deriving(Clone)]
pub struct MouseRelativeMoveArgs {
    /// Delta x.
    pub dx: f64,
    /// Delta y.
    pub dy: f64,
}

/// Mouse scroll arguments.
#[deriving(Clone)]
pub struct MouseScrollArgs {
    /// x.
    pub x: f64,
    /// y.
    pub y: f64,
}

/// Contains the different game events.
#[deriving(Clone)]
pub enum GameEvent {
    /// Render graphics.
    Render(RenderArgs),
    /// Update physical state of the game.
    Update(UpdateArgs),
    /// Pressed a keyboard key.
    KeyPress(KeyPressArgs),
    /// Released a keyboard key.
    KeyRelease(KeyReleaseArgs),
    /// Pressed a mouse button.
    MousePress(MousePressArgs),
    /// Released a mouse button.
    MouseRelease(MouseReleaseArgs),
    /// Moved mouse cursor.
    MouseMove(MouseMoveArgs),
    /// Moved mouse relative, not bounded by cursor.
    MouseRelativeMove(MouseRelativeMoveArgs),
    /// Scrolled mouse.
    MouseScroll(MouseScrollArgs)
}

enum GameIteratorState {
    RenderState,
    SwapBuffersState,
    PrepareUpdateLoopState,
    UpdateLoopState,
    HandleEventsState,
    MouseRelativeMoveState(f64, f64),
    UpdateState,
}

/// Settings for the game loop behavior.
#[deriving(Clone)]
pub struct GameIteratorSettings {
    /// The number of updates per second (UPS).
    pub updates_per_second: u64,
    /// The maximum number of frames per second (FPS target).
    pub max_frames_per_second: u64,
}

/// A game loop iterator.
///
/// Example:
///
/// ```Rust
/// let game_iter_settings = GameIteratorSettings {
///     updates_per_second: 120,
///     max_frames_per_second: 60,
/// };
/// let mut game_iter = GameIterator::new(&mut window, &game_iter_settings);
/// loop {
///     match game_iter.next() {
///         None => break,
///         Some(mut e) => match e {
///             Render(ref mut args) => {
///                 // Create graphics context with absolute coordinates.
///                 let c = Context::abs(args.width as f64, args.height as f64);
///                 // Do rendering here.
///             },
///             _ => {},
///         },
///     }
/// }
/// ```
pub struct GameIterator<'a, W> {
    /// The game window used by iterator.
    pub game_window: &'a mut W,
    state: GameIteratorState,
    last_update: u64,
    update_time_in_ns: u64,
    dt: f64,
    min_updates_per_frame: u64,
    min_ns_per_frame: u64,
    start_render: u64,
    next_render: u64,
    updated: u64,
}

static billion: u64 = 1_000_000_000;

impl<'a, W: GameWindow> GameIterator<'a, W> {
    /// Creates a new game iterator.
    pub fn new(
        game_window: &'a mut W,
        settings: &GameIteratorSettings
    ) -> GameIterator<'a, W> {
        let updates_per_second: u64 = settings.updates_per_second;
        let max_frames_per_second: u64 = settings.max_frames_per_second;

        let start = time::precise_time_ns();
        GameIterator {
            game_window: game_window,
            state: RenderState,
            last_update: start,
            update_time_in_ns: billion / updates_per_second,
            dt: 1.0 / updates_per_second as f64,
            // You can make this lower if needed.
            min_updates_per_frame: updates_per_second / max_frames_per_second,
            min_ns_per_frame: billion / max_frames_per_second,
            start_render: start,
            next_render: start,
            updated: 0,
        }
    }
}

impl<'a, W: GameWindow>
Iterator<GameEvent>
for GameIterator<'a, W> {
    /// Returns the next game event.
    fn next(&mut self) -> Option<GameEvent> {
        match self.state {
            RenderState => {
                if self.game_window.should_close() { return None; }

                self.start_render = time::precise_time_ns();
                // Rendering code
                let (w, h) = self.game_window.get_size();
                if w != 0 && h != 0 {
                    // Swap buffers next time.
                    self.state = SwapBuffersState;
                    return Some(Render(RenderArgs {
                            // Extrapolate time forward to allow smooth motion.
                            // 'start_render' is always bigger than 'last_update'.
                            ext_dt: (self.start_render - self.last_update) as f64 / billion as f64,
                            width: w,
                            height: h,
                        }
                    ));
                }

                self.state = PrepareUpdateLoopState;
                return self.next();
            },
            SwapBuffersState => {
                self.game_window.swap_buffers();
                self.state = PrepareUpdateLoopState;
                return self.next();
            },
            PrepareUpdateLoopState => {
                self.updated = 0;
                self.next_render = self.start_render + self.min_ns_per_frame;
                self.state = UpdateLoopState;
                return self.next();
            },
            UpdateLoopState => {
                let got_min_updates = self.updated < self.min_updates_per_frame;
                let got_time_to_update = time::precise_time_ns() < self.next_render;
                let before_next_frame = self.last_update + self.update_time_in_ns < self.next_render;

                if ( got_time_to_update || got_min_updates ) && before_next_frame {
                    self.state = HandleEventsState;
                    return self.next();
                }

                // Wait if possible.
                // Convert to ms because that is what the sleep function takes.
                let t = (self.next_render - time::precise_time_ns() ) / 1_000_000;
                if t > 1 && t < 1000000 { // The second half just checks if it overflowed,
                                          // which tells us that t should have been negative
                                          // and we are running slow and shouldn't sleep.
                    sleep( t );
                }
                self.state = RenderState;
                return self.next();
            },
            HandleEventsState => {
                // Handle all events before updating.
                return match self.game_window.poll_event() {
                    event::KeyPressed(key) => {
                        Some(KeyPress(KeyPressArgs {
                            key: key,
                        }))
                    },
                    event::KeyReleased(key) => {
                        Some(KeyRelease(KeyReleaseArgs {
                            key: key,
                        }))
                    },
                    event::MouseButtonPressed(mouse_button) => {
                        Some(MousePress(MousePressArgs {
                            button: mouse_button,
                        }))
                    },
                    event::MouseButtonReleased(mouse_button) => {
                        Some(MouseRelease(MouseReleaseArgs {
                            button: mouse_button,
                        }))
                    },
                    event::MouseMoved(x, y, relative_move) => {
                        match relative_move {
                            Some((dx, dy)) =>
                                self.state = MouseRelativeMoveState(dx, dy),
                            None => {},
                        };
                        Some(MouseMove(MouseMoveArgs {
                            x: x,
                            y: y,
                        }))
                    },
                    event::MouseScrolled(x, y) => {
                        Some(MouseScroll(MouseScrollArgs {
                            x: x,
                            y: y
                        }))
                    },
                    event::NoEvent => {
                        self.state = UpdateState;
                        self.next()
                    },
                }
            },
            MouseRelativeMoveState(dx, dy) => {
                self.state = HandleEventsState;
                return Some(MouseRelativeMove(MouseRelativeMoveArgs {
                    dx: dx,
                    dy: dy,
                }));
            },
            UpdateState => {
                self.updated += 1;
                self.state = UpdateLoopState;
                self.last_update += self.update_time_in_ns;
                return Some(Update(UpdateArgs{
                    dt: self.dt,
                }));
            },
        };

        /*
        // copied.

        while !self.should_close(game_window) {

            let start_render = time::precise_time_ns();

            // Rendering code
            let (w, h) = game_window.get_size();
            if w != 0 && h != 0 {
                self.viewport(game_window);
                let mut gl = Gl::new(&mut gl_data, asset_store);
                bg.clear(&mut gl);
                // Extrapolate time forward to allow smooth motion.
                // 'now' is always bigger than 'last_update'.
                let ext_dt = (start_render - last_update) as f64 / billion as f64;
                self.render(
                    ext_dt,
                    &context
                        .trans(-1.0, 1.0)
                        .scale(2.0 / w as f64, -2.0 / h as f64)
                        .store_view(),
                    &mut gl
                        );
                self.swap_buffers(game_window);
            }

            let next_render = start_render + min_ns_per_frame;

            // Update gamestate
            let mut updated = 0;

            while // If we haven't reached the required number of updates yet
                  ( updated < min_updates_per_frame ||
                    // Or we have the time to update further
                    time::precise_time_ns() < next_render ) &&
                  //And we haven't already progressed time to far
                  last_update + update_time_in_ns < next_render {

                self.handle_events(game_window, asset_store);
                self.update(dt, asset_store);

                updated += 1;
                last_update += update_time_in_ns;
            }

            // Wait if possible

            let t = (next_render - time::precise_time_ns() ) / 1_000_000;
            if t > 1 && t < 1000000 { // The second half just checks if it overflowed,
                                      // which tells us that t should have been negative
                                      // and we are running slow and shouldn't sleep.
                sleep( t );
            }

        }
        */
    }
}
<|endoftext|>


<commit_before>#[cfg(feature = "async-std-runtime")]
use async_std::task as rt_task;
#[cfg(feature = "tokio-runtime")]
use tokio::task as rt_task;

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

use super::JoinError;

pub struct JoinHandle<T>(rt_task::JoinHandle<T>);
impl<T> Future for JoinHandle<T> {
    type Output = Result<T, JoinError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // In async-std, the program aborts on panic so results arent returned. To
        // unify with tokio, we simply make an `Ok` result.
        let result = rt_task::JoinHandle::poll(Pin::new(&mut self.0), cx);
        #[cfg(feature = "async-std-runtime")]
        return result.map(|p| Ok(p));
        #[cfg(feature = "tokio-runtime")]
        return result.map_err(|e| e.into());
    }
}
impl<T> From<rt_task::JoinHandle<T>> for JoinHandle<T> {
    fn from(h: rt_task::JoinHandle<T>) -> Self {
        Self(h)
    }
}
<commit_msg>Fixes for clippy<commit_after>#[cfg(feature = "async-std-runtime")]
use async_std::task as rt_task;
#[cfg(feature = "tokio-runtime")]
use tokio::task as rt_task;

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

use super::JoinError;

pub struct JoinHandle<T>(rt_task::JoinHandle<T>);
impl<T> Future for JoinHandle<T> {
    type Output = Result<T, JoinError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // In async-std, the program aborts on panic so results arent returned. To
        // unify with tokio, we simply make an `Ok` result.
        let result = rt_task::JoinHandle::poll(Pin::new(&mut self.0), cx);
        #[cfg(feature = "async-std-runtime")]
        return result.map(Ok);
        #[cfg(feature = "tokio-runtime")]
        return result.map_err(|e| e.into());
    }
}
impl<T> From<rt_task::JoinHandle<T>> for JoinHandle<T> {
    fn from(h: rt_task::JoinHandle<T>) -> Self {
        Self(h)
    }
}
<|endoftext|>


<commit_before>#![feature(cfg_target_feature, test)]

extern crate simd;
extern crate test;
extern crate teddy;

use simd::u8x16;
use test::Bencher;
use teddy::Teddy;

#[cfg(target_feature="avx2")]
use simd::x86::avx::u8x32;

static HAYSTACK: &'static str = include_str!("data/sherlock.txt");

macro_rules! sherlock {
    ($name:ident, $simd_type: ident, $pats:expr, $count:expr) => {
        #[bench]
        fn $name(b: &mut Bencher) {
            let pats: Vec<Vec<u8>> = $pats.into_iter().map(|s| s.as_bytes().to_vec()).collect();
            let ted = Teddy::<$simd_type>::new(&pats).unwrap();
            b.bytes = HAYSTACK.len() as u64;

            b.iter(|| {
                let mut hay = HAYSTACK.as_bytes();
                let mut count = 0;
                while let Some(mat) = ted.find(hay) {
                    count += 1;
                    hay = &hay[(mat.start + 1)..];
                }
                assert_eq!(count, $count);
            });
        }
    }
}

sherlock!(names_128, u8x16, &["Sherlock", "Holmes"], 558);
#[cfg(target_feature="avx2")]
sherlock!(names_256, u8x32, &["Sherlock", "Holmes"], 558);

// This one doesn't have any matches, but the fingerprints should match a log.
sherlock!(names_lower_128, u8x16, &["sherlock", "holmes"], 0);
#[cfg(target_feature="avx2")]
sherlock!(names_lower_256, u8x32, &["sherlock", "holmes"], 0);

sherlock!(words_long_128, u8x16, &["pull", "cabby", "three", "side"], 348);
#[cfg(target_feature="avx2")]
sherlock!(words_long_256, u8x32, &["pull", "cabby", "three", "side"], 348);

sherlock!(words_short_128, u8x16, &["pu", "ca", "th", "si"], 15202);
#[cfg(target_feature="avx2")]
sherlock!(words_short_256, u8x32, &["pu", "ca", "th", "si"], 15202);

sherlock!(chars_128, u8x16, &["S", "H"], 2115);
#[cfg(target_feature="avx2")]
sherlock!(chars_256, u8x32, &["S", "H"], 2115);

sherlock!(chars_rare_128, u8x16, &["Z", "X"], 12);
#[cfg(target_feature="avx2")]
sherlock!(chars_rare_256, u8x32, &["Z", "X"], 12);

// The fingerprints here shouldn't match anything.
sherlock!(rare_128, u8x16, &["xyzxyz"], 0);
#[cfg(target_feature="avx2")]
sherlock!(rare_256, u8x32, &["xyzxyz"], 0);
<commit_msg>Add sherlock prefix.<commit_after>#![feature(cfg_target_feature, test)]

extern crate simd;
extern crate test;
extern crate teddy;

use simd::u8x16;
use test::Bencher;
use teddy::Teddy;

#[cfg(target_feature="avx2")]
use simd::x86::avx::u8x32;

static HAYSTACK: &'static str = include_str!("data/sherlock.txt");

macro_rules! sherlock {
    ($name:ident, $simd_type: ident, $pats:expr, $count:expr) => {
        #[bench]
        fn $name(b: &mut Bencher) {
            let pats: Vec<Vec<u8>> = $pats.into_iter().map(|s| s.as_bytes().to_vec()).collect();
            let ted = Teddy::<$simd_type>::new(&pats).unwrap();
            b.bytes = HAYSTACK.len() as u64;

            b.iter(|| {
                let mut hay = HAYSTACK.as_bytes();
                let mut count = 0;
                while let Some(mat) = ted.find(hay) {
                    count += 1;
                    hay = &hay[(mat.start + 1)..];
                }
                assert_eq!(count, $count);
            });
        }
    }
}

sherlock!(sherlock_names_128, u8x16, &["Sherlock", "Holmes"], 558);
#[cfg(target_feature="avx2")]
sherlock!(sherlock_names_256, u8x32, &["Sherlock", "Holmes"], 558);

// This one doesn't have any matches, but the fingerprints should match a lot.
sherlock!(sherlock_names_lower_128, u8x16, &["sherlock", "holmes"], 0);
#[cfg(target_feature="avx2")]
sherlock!(sherlock_names_lower_256, u8x32, &["sherlock", "holmes"], 0);

sherlock!(sherlock_words_long_128, u8x16, &["pull", "cabby", "three", "side"], 348);
#[cfg(target_feature="avx2")]
sherlock!(sherlock_words_long_256, u8x32, &["pull", "cabby", "three", "side"], 348);

sherlock!(sherlock_words_short_128, u8x16, &["pu", "ca", "th", "si"], 15202);
#[cfg(target_feature="avx2")]
sherlock!(sherlock_words_short_256, u8x32, &["pu", "ca", "th", "si"], 15202);

sherlock!(sherlock_chars_128, u8x16, &["S", "H"], 2115);
#[cfg(target_feature="avx2")]
sherlock!(sherlock_chars_256, u8x32, &["S", "H"], 2115);

sherlock!(sherlock_chars_rare_128, u8x16, &["Z", "X"], 12);
#[cfg(target_feature="avx2")]
sherlock!(sherlock_chars_rare_256, u8x32, &["Z", "X"], 12);

// The fingerprints here shouldn't match anything.
sherlock!(sherlock_rare_128, u8x16, &["xyzxyz"], 0);
#[cfg(target_feature="avx2")]
sherlock!(sherlock_rare_256, u8x32, &["xyzxyz"], 0);
<|endoftext|>