<commit_before>use alloc::boxed::Box;

use collections::vec::Vec;

use core::intrinsics::volatile_load;
use core::{mem, slice};

use drivers::mmio::Mmio;
use drivers::pci::config::PciConfig;

use schemes::KScheme;

use super::hci::{UsbHci, UsbMsg};
use super::setup::Setup;

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Gtd {
    flags: u32,
    buffer: u32,
    next: u32,
    end: u32,
}

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Ed {
    flags: u32,
    tail: u32,
    head: u32,
    next: u32,
}

const CTRL_CBSR: u32 = 0b11;
const CTRL_PLE: u32 = 1 << 2;
const CTRL_IE: u32 = 1 << 3;
const CTRL_CLE: u32 = 1 << 4;
const CTRL_BLE: u32 = 1 << 5;
const CTRL_HCFS: u32 = 0b11 << 6;
const CTRL_IR: u32 = 1 << 8;
const CTRL_RWC: u32 = 1 << 9;
const CTRL_RWE: u32 = 1 << 10;

const CMD_STS_HCR: u32 = 1;
const CMD_STS_CLF: u32 = 1 << 1;
const CMD_STS_BLF: u32 = 1 << 2;
const CMD_STS_OCR: u32 = 1 << 3;

const PORT_STS_CCS: u32 = 1;
const PORT_STS_PES: u32 = 1 << 1;
const PORT_STS_PSS: u32 = 1 << 2;
const PORT_STS_POCI: u32 = 1 << 3;
const PORT_STS_PPS: u32 = 1 << 8;
const PORT_STS_LSDA: u32 = 1 << 9;
const PORT_STS_CSC: u32 = 1 << 16;
const PORT_STS_PESC: u32 = 1 << 17;
const PORT_STS_PSSC: u32 = 1 << 18;
const PORT_STS_OCIC: u32 = 1 << 19;
const PORT_STS_PRSC: u32 = 1 << 20;

#[repr(packed)]
pub struct OhciRegs {
    pub revision: Mmio<u32>,
    pub control: Mmio<u32>,
    pub cmd_sts: Mmio<u32>,
    pub int_sts: Mmio<u32>,
    pub int_en: Mmio<u32>,
    pub int_dis: Mmio<u32>,
    pub hcca: Mmio<u32>,
    pub period_current: Mmio<u32>,
    pub control_head: Mmio<u32>,
    pub control_current: Mmio<u32>,
    pub bulk_head: Mmio<u32>,
    pub bulk_current: Mmio<u32>,
    pub done_head: Mmio<u32>,
    pub fm_interval: Mmio<u32>,
    pub fm_remain: Mmio<u32>,
    pub fm_num: Mmio<u32>,
    pub periodic_start: Mmio<u32>,
    pub ls_thresh: Mmio<u32>,
    pub rh_desc_a: Mmio<u32>,
    pub rh_desc_b: Mmio<u32>,
    pub rh_sts: Mmio<u32>,
    pub port_sts: [Mmio<u32>; 15],
}

pub struct Ohci {
    pub regs: &'static mut OhciRegs,
    pub irq: u8,
}

impl KScheme for Ohci {
    fn on_irq(&mut self, irq: u8) {
        if irq == self.irq {
            // d("OHCI IRQ\n");
        }
    }

    fn on_poll(&mut self) {
    }
}

impl Ohci {
    pub unsafe fn new(mut pci: PciConfig) -> Box<Self> {
        pci.flag(4, 4, true); // Bus mastering

        let base = pci.read(0x10) as usize & 0xFFFFFFF0;
        let regs = &mut *(base as *mut OhciRegs);

        let mut module = box Ohci {
            regs: regs,
            irq: pci.read(0x3C) as u8 & 0xF,
        };

        module.init();

        return module;
    }

    pub unsafe fn init(&mut self) {
        debugln!("OHCI on: {:X}, IRQ: {:X}", (self.regs as *mut OhciRegs) as usize, self.irq);

        let ctrl = self.regs.control.read();
        self.regs.control.write(ctrl & (0xFFFFFFFF - CTRL_HCFS) | 0b10 << 6);

        let ndp = self.regs.rh_desc_a.read() & 0xF;
        for i in 0..ndp as usize {
            debugln!("Port {}: {:X}", i, self.regs.port_sts[i].read());

            if self.regs.port_sts[i].readf(PORT_STS_CCS) {
                debugln!("Device");

                debugln!("Enable");
                while ! self.regs.port_sts[i].readf(PORT_STS_PES) {
                    self.regs.port_sts[i].writef(PORT_STS_PES, true);
                }

                self.device(i as u8);
            }
        }
    }
}

impl UsbHci for Ohci {
    fn msg(&mut self, address: u8, endpoint: u8, msgs: &[UsbMsg]) -> usize {
        let mut tds = Vec::new();
        for msg in msgs.iter().rev() {
            let link_ptr = match tds.last() {
                Some(td) => (td as *const Gtd) as u32,
                None => 0
            };

            match *msg {
                UsbMsg::Setup(setup) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b00 << 19,
                    buffer: (setup as *const Setup) as u32,
                    next: link_ptr,
                    end: (setup as *const Setup) as u32 + mem::size_of::<Setup>() as u32
                }),
                UsbMsg::In(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::InIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::Out(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::OutIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                })
            }
        }

        let mut count = 0;

        if ! tds.is_empty() {
            let ed = box Ed {
                flags: 1024 << 16 | (endpoint as u32) << 7 | address as u32,
                tail: 0,
                head: (tds.last().unwrap() as *const Gtd) as u32,
                next: 0
            };

            //TODO: Calculate actual bytes
            for td in tds.iter().rev() {
                count += (td.end - td.buffer) as usize;
            }

            /*
            self.regs.control_head.write((&*ed as *const Ed) as u32);
            while ! self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, true);
            }
            while ! self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, true);
            }

            for td in tds.iter().rev() {
                while unsafe { volatile_load(td as *const Gtd).flags } & 0b1111 << 28 == 0b1111 << 28 {
                    //unsafe { context_switch(false) };
                }
            }

            while self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, false);
            }
            while self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, false);
            }
            self.regs.control_head.write(0);
            */
        }

        count
    }
}
<commit_msg>Getting stall condition<commit_after>use alloc::boxed::Box;

use collections::vec::Vec;

use core::intrinsics::volatile_load;
use core::{mem, slice};

use drivers::mmio::Mmio;
use drivers::pci::config::PciConfig;

use schemes::KScheme;

use super::hci::{UsbHci, UsbMsg};
use super::setup::Setup;

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Gtd {
    flags: u32,
    buffer: u32,
    next: u32,
    end: u32,
}

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Ed {
    flags: u32,
    tail: u32,
    head: u32,
    next: u32,
}

const CTRL_CBSR: u32 = 0b11;
const CTRL_PLE: u32 = 1 << 2;
const CTRL_IE: u32 = 1 << 3;
const CTRL_CLE: u32 = 1 << 4;
const CTRL_BLE: u32 = 1 << 5;
const CTRL_HCFS: u32 = 0b11 << 6;
const CTRL_IR: u32 = 1 << 8;
const CTRL_RWC: u32 = 1 << 9;
const CTRL_RWE: u32 = 1 << 10;

const CMD_STS_HCR: u32 = 1;
const CMD_STS_CLF: u32 = 1 << 1;
const CMD_STS_BLF: u32 = 1 << 2;
const CMD_STS_OCR: u32 = 1 << 3;

const PORT_STS_CCS: u32 = 1;
const PORT_STS_PES: u32 = 1 << 1;
const PORT_STS_PSS: u32 = 1 << 2;
const PORT_STS_POCI: u32 = 1 << 3;
const PORT_STS_PPS: u32 = 1 << 8;
const PORT_STS_LSDA: u32 = 1 << 9;
const PORT_STS_CSC: u32 = 1 << 16;
const PORT_STS_PESC: u32 = 1 << 17;
const PORT_STS_PSSC: u32 = 1 << 18;
const PORT_STS_OCIC: u32 = 1 << 19;
const PORT_STS_PRSC: u32 = 1 << 20;

#[repr(packed)]
pub struct OhciRegs {
    pub revision: Mmio<u32>,
    pub control: Mmio<u32>,
    pub cmd_sts: Mmio<u32>,
    pub int_sts: Mmio<u32>,
    pub int_en: Mmio<u32>,
    pub int_dis: Mmio<u32>,
    pub hcca: Mmio<u32>,
    pub period_current: Mmio<u32>,
    pub control_head: Mmio<u32>,
    pub control_current: Mmio<u32>,
    pub bulk_head: Mmio<u32>,
    pub bulk_current: Mmio<u32>,
    pub done_head: Mmio<u32>,
    pub fm_interval: Mmio<u32>,
    pub fm_remain: Mmio<u32>,
    pub fm_num: Mmio<u32>,
    pub periodic_start: Mmio<u32>,
    pub ls_thresh: Mmio<u32>,
    pub rh_desc_a: Mmio<u32>,
    pub rh_desc_b: Mmio<u32>,
    pub rh_sts: Mmio<u32>,
    pub port_sts: [Mmio<u32>; 15],
}

pub struct Ohci {
    pub regs: &'static mut OhciRegs,
    pub irq: u8,
}

impl KScheme for Ohci {
    fn on_irq(&mut self, irq: u8) {
        if irq == self.irq {
            // d("OHCI IRQ\n");
        }
    }

    fn on_poll(&mut self) {
    }
}

impl Ohci {
    pub unsafe fn new(mut pci: PciConfig) -> Box<Self> {
        pci.flag(4, 4, true); // Bus mastering

        let base = pci.read(0x10) as usize & 0xFFFFFFF0;
        let regs = &mut *(base as *mut OhciRegs);

        let mut module = box Ohci {
            regs: regs,
            irq: pci.read(0x3C) as u8 & 0xF,
        };

        module.init();

        return module;
    }

    pub unsafe fn init(&mut self) {
        debugln!("OHCI on: {:X}, IRQ: {:X}", (self.regs as *mut OhciRegs) as usize, self.irq);

        debugln!("Reset: {:X}", self.regs.control.read());
        loop {
            let ctrl = self.regs.control.read();
            let desired_ctrl = ctrl & (0xFFFFFFFF - CTRL_HCFS);
            if ctrl != desired_ctrl {
                self.regs.control.write(desired_ctrl);
            } else {
                break;
            }
        }

        debugln!("Enable: {:X}", self.regs.control.read());
        loop {
            let ctrl = self.regs.control.read();
            let desired_ctrl = (ctrl & (0xFFFFFFFF - CTRL_HCFS)) | 0b10 << 6;
            if ctrl != desired_ctrl {
                self.regs.control.write(desired_ctrl);
            } else {
                break;
            }
        }

        debugln!("Port Enumeration: {:X}", self.regs.control.read());

        let ndp = self.regs.rh_desc_a.read() & 0xF;
        for i in 0..ndp as usize {
            debugln!("Port {}: {:X}", i, self.regs.port_sts[i].read());

            if self.regs.port_sts[i].readf(PORT_STS_CCS) {
                debugln!("Device");

                debugln!("Enable");
                while ! self.regs.port_sts[i].readf(PORT_STS_PES) {
                    self.regs.port_sts[i].writef(PORT_STS_PES, true);
                }

                self.device(i as u8);
            }
        }
    }
}

impl UsbHci for Ohci {
    fn msg(&mut self, address: u8, endpoint: u8, msgs: &[UsbMsg]) -> usize {
        let mut tds = Vec::new();
        for msg in msgs.iter().rev() {
            let link_ptr = match tds.last() {
                Some(td) => (td as *const Gtd) as u32,
                None => 0
            };

            match *msg {
                UsbMsg::Setup(setup) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b00 << 19,
                    buffer: (setup as *const Setup) as u32,
                    next: link_ptr,
                    end: (setup as *const Setup) as u32 + mem::size_of::<Setup>() as u32
                }),
                UsbMsg::In(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::InIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::Out(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::OutIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                })
            }
        }

        let mut count = 0;

        if ! tds.is_empty() {
            let ed = box Ed {
                //TODO: Remove 1 << 13, it sets it to low speed
                flags: 0x3FF << 16 | 1 << 13 | (endpoint as u32) << 7 | address as u32,
                tail: 0,
                head: (tds.last().unwrap() as *const Gtd) as u32,
                next: 0
            };

            //TODO: Calculate actual bytes
            for td in tds.iter().rev() {
                count += (td.end - td.buffer) as usize;
            }

            self.regs.control_head.write((&*ed as *const Ed) as u32);
            while ! self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, true);
            }
            while ! self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, true);
            }

            for td in tds.iter().rev() {
                while unsafe { volatile_load(td as *const Gtd).flags } & 0b1111 << 28 == 0b1111 << 28 {
                    //unsafe { context_switch(false) };
                }
                let condition = (unsafe { volatile_load(td as *const Gtd).flags } & 0b1111 << 28) >> 28;
                if condition != 0 {
                    debugln!("Condition: {:X}", condition);
                    break;
                }
            }

            while self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, false);
            }
            while self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, false);
            }
            self.regs.control_head.write(0);
        }

        count
    }
}
<|endoftext|>


<commit_before><commit_msg>Add solution to problem 60<commit_after>#![feature(core)]
#[macro_use] extern crate libeuler;

use libeuler::prime::SieveOfAtkin;
/// The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating
/// them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and
/// 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four
/// primes with this property.
///
/// Find the lowest sum for a set of five primes for which any two primes concatenate to
/// produce another prime.
fn main() {
    solutions! {
        sol naive {
            let sieve = SieveOfAtkin::new(100_000_000);

            match find_remarkable_set(&sieve, vec![13], 1000, 5) {
                Some(set) => set.iter().map(|&a| a).sum(),
                _ => 0u64
            }
        }
    }
}

fn find_remarkable_set(sieve: &SieveOfAtkin, mut set: Vec<u64>, start: u64, needed: usize) -> Option<Vec<u64>> {
    for prim in sieve.iter().filter(|&p| p > start).filter(|&p| p < 9000) {
        // print!("Add {} to {:?}? ", prim, set);
        let mut valid = true;
        for i in set.iter() {
            if !sieve.is_prime(format!("{}{}", i, prim).parse().unwrap()) ||
               !sieve.is_prime(format!("{}{}", prim, i).parse().unwrap()) {
                valid = false;
                // println!("No");
                break;
            }
        }

        if valid {
            // println!("Yes");
            set.push(prim);

            if set.len() >= needed {
                return Some(set);
            }

            match find_remarkable_set(sieve, set.clone(), prim, needed) {
                Some(v) => return Some(v),
                _ => {}
            }

            set.pop();
        }
    }

    None
}
<|endoftext|>


<commit_before><commit_msg>hello world<commit_after>fn main() {
    println!("Hello World!");
}<|endoftext|>


<commit_before>// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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.

//! Private callback support functions.

use libc::{c_double, c_int, c_uint};
use std::mem;
use std::sync::mpsc::Sender;

use super::*;

macro_rules! callback(
    (
        type Args = ($($arg:ident: $arg_ty:ty),*);
        type Callback = $Callback:ident;
        let ext_set = $ext_set:expr;
        fn callback($($ext_arg:ident: $ext_arg_ty:ty),*) $call:expr
    ) => (
        thread_local!(static CALLBACK_KEY: RefCell<Option<Box<Object<Args> + 'static>>> = RefCell::new(None));

        type Args = ($($arg_ty),*,);

        trait Object<T> {
            fn call(&self, args: T);
        }

        impl<UserData> Object<Args> for ::Callback<fn($($arg_ty),*, &UserData), UserData> {
            fn call(&self, ($($arg),*,): Args) {
                (self.f)($($arg),*, &self.data);
            }
        }

        pub fn set<UserData: 'static>(f: ::$Callback<UserData>) {
            let mut boxed_cb = Some(box f as Box<Object<Args> + 'static>);
            CALLBACK_KEY.with(|cb| {
                *cb.borrow_mut() = boxed_cb.take();
            });
            ($ext_set)(Some(callback as extern "C" fn($($ext_arg: $ext_arg_ty),*)));
        }

        pub fn unset() {
            CALLBACK_KEY.with(|cb| {
                *cb.borrow_mut() = None;
            });
            ($ext_set)(None);
        }

        extern "C" fn callback($($ext_arg: $ext_arg_ty),*) {
            CALLBACK_KEY.with(|cb| {
                match *cb.borrow() {
                    Some(ref cb) => unsafe { cb.call($call) },
                    _ => {}
                }
            })
        }
    )
);

pub mod error {
    use libc::{c_int, c_char};
    use std::cell::RefCell;
    use std::mem;

    callback!(
        type Args = (error: ::Error, description: String);
        type Callback = ErrorCallback;
        let ext_set = |&: cb| unsafe { ::ffi::glfwSetErrorCallback(cb) };
        fn callback(error: c_int, description: *const c_char) {
            (mem::transmute(error), ::string_from_c_str(description))
        }
    );
}

pub mod monitor {
    use libc::{c_int};
    use std::cell::RefCell;
    use std::mem;

    callback!(
        type Args = (monitor: ::Monitor, event: ::MonitorEvent);
        type Callback = MonitorCallback;
        let ext_set = |&: cb| unsafe { ::ffi::glfwSetMonitorCallback(cb) };
        fn callback(monitor: *mut ::ffi::GLFWmonitor, event: c_int) {
            let monitor = ::Monitor {
                ptr: monitor
            };
            (monitor, mem::transmute(event))
        }
    );
}

unsafe fn get_sender<'a>(window: &'a *mut ffi::GLFWwindow) -> &'a Sender<(f64, WindowEvent)> {
    mem::transmute(ffi::glfwGetWindowUserPointer(*window))
}

// Note that this macro creates a static function pointer rather than a plain function.
// This makes it more ergonomic to embed in an Option; see set_window_callback! in lib.rs
macro_rules! window_callback(
    (fn $name:ident () => $event:ident) => (
        pub static $name: (extern "C" fn(window: *mut ffi::GLFWwindow)) = {
            extern "C" fn actual_callback(window: *mut ffi::GLFWwindow) {
                unsafe { get_sender(&window).send((ffi::glfwGetTime() as f64, WindowEvent::$event)).unwrap();}
            }
            actual_callback
        };
     );
    (fn $name:ident ($($ext_arg:ident: $ext_arg_ty:ty),*) => $event:ident($($arg_conv:expr),*)) => (
        pub static $name: (extern "C" fn(window: *mut ffi::GLFWwindow $(, $ext_arg: $ext_arg_ty)*)) = {
            extern "C" fn actual_callback(window: *mut ffi::GLFWwindow $(, $ext_arg: $ext_arg_ty)*) {
                unsafe { get_sender(&window).send((ffi::glfwGetTime() as f64, WindowEvent::$event($($arg_conv),*))).unwrap(); }
            }
            actual_callback
        };
     );
);

window_callback!(fn window_pos_callback(xpos: c_int, ypos: c_int)                           => Pos(xpos as i32, ypos as i32));
window_callback!(fn window_size_callback(width: c_int, height: c_int)                       => Size(width as i32, height as i32));
window_callback!(fn window_close_callback()                                                 => Close);
window_callback!(fn window_refresh_callback()                                               => Refresh);
window_callback!(fn window_focus_callback(focused: c_int)                                   => Focus(focused == ffi::TRUE));
window_callback!(fn window_iconify_callback(iconified: c_int)                               => Iconify(iconified == ffi::TRUE));
window_callback!(fn framebuffer_size_callback(width: c_int, height: c_int)                  => FramebufferSize(width as i32, height as i32));
window_callback!(fn mouse_button_callback(button: c_int, action: c_int, mods: c_int)        => MouseButton(mem::transmute(button), mem::transmute(action), Modifiers::from_bits(mods).unwrap()));
window_callback!(fn cursor_pos_callback(xpos: c_double, ypos: c_double)                     => CursorPos(xpos as f64, ypos as f64));
window_callback!(fn cursor_enter_callback(entered: c_int)                                   => CursorEnter(entered == ffi::TRUE));
window_callback!(fn scroll_callback(xpos: c_double, ypos: c_double)                         => Scroll(xpos as f64, ypos as f64));
window_callback!(fn key_callback(key: c_int, scancode: c_int, action: c_int, mods: c_int)   => Key(mem::transmute(key), scancode, mem::transmute(action), Modifiers::from_bits(mods).unwrap()));
window_callback!(fn char_callback(character: c_uint)                                        => Char(::std::char::from_u32(character).unwrap()));
<commit_msg>closure inference fix for the current nightly<commit_after>// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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.

//! Private callback support functions.

use libc::{c_double, c_int, c_uint};
use std::mem;
use std::sync::mpsc::Sender;

use super::*;

macro_rules! callback(
    (
        type Args = ($($arg:ident: $arg_ty:ty),*);
        type Callback = $Callback:ident;
        let ext_set = $ext_set:expr;
        fn callback($($ext_arg:ident: $ext_arg_ty:ty),*) $call:expr
    ) => (
        thread_local!(static CALLBACK_KEY: RefCell<Option<Box<Object<Args> + 'static>>> = RefCell::new(None));

        type Args = ($($arg_ty),*,);

        trait Object<T> {
            fn call(&self, args: T);
        }

        impl<UserData> Object<Args> for ::Callback<fn($($arg_ty),*, &UserData), UserData> {
            fn call(&self, ($($arg),*,): Args) {
                (self.f)($($arg),*, &self.data);
            }
        }

        pub fn set<UserData: 'static>(f: ::$Callback<UserData>) {
            let mut boxed_cb = Some(box f as Box<Object<Args> + 'static>);
            CALLBACK_KEY.with(|cb| {
                *cb.borrow_mut() = boxed_cb.take();
            });
            ($ext_set)(Some(callback as extern "C" fn($($ext_arg: $ext_arg_ty),*)));
        }

        pub fn unset() {
            CALLBACK_KEY.with(|cb| {
                *cb.borrow_mut() = None;
            });
            ($ext_set)(None);
        }

        extern "C" fn callback($($ext_arg: $ext_arg_ty),*) {
            CALLBACK_KEY.with(|cb| {
                match *cb.borrow() {
                    Some(ref cb) => unsafe { cb.call($call) },
                    _ => {}
                }
            })
        }
    )
);

pub mod error {
    use libc::{c_int, c_char};
    use std::cell::RefCell;
    use std::mem;

    callback!(
        type Args = (error: ::Error, description: String);
        type Callback = ErrorCallback;
        let ext_set = |cb| unsafe { ::ffi::glfwSetErrorCallback(cb) };
        fn callback(error: c_int, description: *const c_char) {
            (mem::transmute(error), ::string_from_c_str(description))
        }
    );
}

pub mod monitor {
    use libc::{c_int};
    use std::cell::RefCell;
    use std::mem;

    callback!(
        type Args = (monitor: ::Monitor, event: ::MonitorEvent);
        type Callback = MonitorCallback;
        let ext_set = |cb| unsafe { ::ffi::glfwSetMonitorCallback(cb) };
        fn callback(monitor: *mut ::ffi::GLFWmonitor, event: c_int) {
            let monitor = ::Monitor {
                ptr: monitor
            };
            (monitor, mem::transmute(event))
        }
    );
}

unsafe fn get_sender<'a>(window: &'a *mut ffi::GLFWwindow) -> &'a Sender<(f64, WindowEvent)> {
    mem::transmute(ffi::glfwGetWindowUserPointer(*window))
}

// Note that this macro creates a static function pointer rather than a plain function.
// This makes it more ergonomic to embed in an Option; see set_window_callback! in lib.rs
macro_rules! window_callback(
    (fn $name:ident () => $event:ident) => (
        pub static $name: (extern "C" fn(window: *mut ffi::GLFWwindow)) = {
            extern "C" fn actual_callback(window: *mut ffi::GLFWwindow) {
                unsafe { get_sender(&window).send((ffi::glfwGetTime() as f64, WindowEvent::$event)).unwrap();}
            }
            actual_callback
        };
     );
    (fn $name:ident ($($ext_arg:ident: $ext_arg_ty:ty),*) => $event:ident($($arg_conv:expr),*)) => (
        pub static $name: (extern "C" fn(window: *mut ffi::GLFWwindow $(, $ext_arg: $ext_arg_ty)*)) = {
            extern "C" fn actual_callback(window: *mut ffi::GLFWwindow $(, $ext_arg: $ext_arg_ty)*) {
                unsafe { get_sender(&window).send((ffi::glfwGetTime() as f64, WindowEvent::$event($($arg_conv),*))).unwrap(); }
            }
            actual_callback
        };
     );
);

window_callback!(fn window_pos_callback(xpos: c_int, ypos: c_int)                           => Pos(xpos as i32, ypos as i32));
window_callback!(fn window_size_callback(width: c_int, height: c_int)                       => Size(width as i32, height as i32));
window_callback!(fn window_close_callback()                                                 => Close);
window_callback!(fn window_refresh_callback()                                               => Refresh);
window_callback!(fn window_focus_callback(focused: c_int)                                   => Focus(focused == ffi::TRUE));
window_callback!(fn window_iconify_callback(iconified: c_int)                               => Iconify(iconified == ffi::TRUE));
window_callback!(fn framebuffer_size_callback(width: c_int, height: c_int)                  => FramebufferSize(width as i32, height as i32));
window_callback!(fn mouse_button_callback(button: c_int, action: c_int, mods: c_int)        => MouseButton(mem::transmute(button), mem::transmute(action), Modifiers::from_bits(mods).unwrap()));
window_callback!(fn cursor_pos_callback(xpos: c_double, ypos: c_double)                     => CursorPos(xpos as f64, ypos as f64));
window_callback!(fn cursor_enter_callback(entered: c_int)                                   => CursorEnter(entered == ffi::TRUE));
window_callback!(fn scroll_callback(xpos: c_double, ypos: c_double)                         => Scroll(xpos as f64, ypos as f64));
window_callback!(fn key_callback(key: c_int, scancode: c_int, action: c_int, mods: c_int)   => Key(mem::transmute(key), scancode, mem::transmute(action), Modifiers::from_bits(mods).unwrap()));
window_callback!(fn char_callback(character: c_uint)                                        => Char(::std::char::from_u32(character).unwrap()));
<|endoftext|>


<commit_before><commit_msg>removed commented code<commit_after><|endoftext|>


<commit_before><commit_msg>missing file<commit_after>use ffi::*;
use libc::{self, int32_t};
use std::ffi::CStr;
use petgraph;
use daggy::{Dag,EdgeIndex,NodeIndex};

//pub struct Graph{}
pub struct Node {}
pub type Graph = Dag<Node,EdgeKind>;

pub fn print_to_stdout(c: *mut Context, g: &Graph) -> bool {
    true
}

pub fn create(context: *mut Context,
                         max_edges: u32,
                         max_nodes: u32,
                         max_info_bytes: u32,
                         growth_factor: f32)
                         -> Graph {
    Graph::with_capacity(max_nodes as usize, max_edges as usize)
}

pub fn edge_create(c: *mut Context,
                   g: &mut Graph,
                   from: i32,
                   to: i32,
                   kind: EdgeKind) -> i32 {
  //edges are nodeindex, not just u32
  //FIXME: error management. We should return something else than i32
  // we should also get index as U32 instead of i32
  g.add_edge(NodeIndex::new(from as usize), NodeIndex::new(to as usize), kind).unwrap_or(EdgeIndex::new(0usize)).index() as i32
}

pub fn node_create_decoder(c: *mut Context,
                                g: &mut Graph,
                                prev_node: i32,
                                placeholder_id: i32) -> i32 {
    0
}

pub fn node_create_canvas(c: *mut Context,
                                   g: &mut Graph,
                                   prev_node: i32,
                                   format: PixelFormat,
                                   width: usize,
                                   height: usize,
                                   bgcolor: u32)
                                   -> i32 {
    0
}

pub fn node_create_scale(c: *mut Context,
                                  g: &mut Graph,
                                  prev_node: i32,
                                  width: usize,
                                  height: usize,
                                  downscale_filter: i32,
                                  upscale_filter: i32,
                                  flags: usize,
                                  sharpen: f32)
                                  -> i32 {
    0
}

pub fn node_create_expand_canvas(c: *mut Context,
                                          g: &mut Graph,
                                          prev_node: i32,
                                          left: u32,
                                          top: u32,
                                          right: u32,
                                          bottom: u32,
                                          canvas_color_srgb: u32)
                                          -> i32 {
    0
}

pub fn node_create_fill_rect(c: *mut Context,
                                      g: &mut Graph,
                                      prev_node: i32,
                                      x1: u32,
                                      y1: u32,
                                      x2: u32,
                                      y2: u32,
                                      color_srgb: u32)
                                      -> i32 { 0 }

pub fn node_create_rotate_90(c: *mut Context, g: &mut Graph, prev_node: i32) -> i32 { 0 }
pub fn node_create_rotate_180(c: *mut Context, g: &mut Graph, prev_node: i32) -> i32 { 0 }
pub fn node_create_rotate_270(c: *mut Context, g: &mut Graph, prev_node: i32) -> i32 { 0 }

pub fn node_create_transpose(c: *mut Context, g: &mut Graph, prev_node: i32) -> i32 { 0 }

pub fn node_create_primitive_copy_rect_to_canvas(c: *mut Context,
                                                          g: &mut Graph,
                                                          prev_node: i32,
                                                          from_x: u32,
                                                          from_y: u32,
                                                          width: u32,
                                                          height: u32,
                                                          x: u32,
                                                          y: u32)
                                                          -> i32 { 0 }

pub fn node_create_encoder(c: *mut Context,
                                    g: &mut Graph,
                                    prev_node: i32,
                                    placeholder_id: i32,
                                    desired_encoder_id: i64,
                                    hints: *const EncoderHints)
                                    -> i32 { 0 }

pub fn node_create_primitive_flip_vertical(c: *mut Context,
                                                    g: &mut Graph,
                                                    prev_node: i32)
                                                    -> i32 { 0 }

pub fn node_create_primitive_flip_horizontal(c: *mut Context,
                                                      g: &mut Graph,
                                                      prev_node: i32)
                                                      -> i32 { 0 }

pub fn node_create_primitive_crop(c: *mut Context,
                                           g: &mut Graph,
                                           prev_node: i32,
                                           x1: u32,
                                           y1: u32,
                                           x2: u32,
                                           y2: u32)
                                           -> i32 { 0 }

extern "C" {
/*
    fn flow_graph_print_to_stdout(c: *mut Context, g: *const Graph) -> bool;

    fn flow_graph_create(context: *mut Context,
                             max_edges: u32,
                             max_nodes: u32,
                             max_info_bytes: u32,
                             growth_factor: f32)
                             -> *mut Graph;

    fn flow_edge_create(c: *mut Context,
                            g: *mut *mut Graph,
                            from: i32,
                            to: i32,
                            kind: EdgeKind)
                            -> i32;
    fn flow_node_create_decoder(c: *mut Context,
                                    g: *mut *mut Graph,
                                    prev_node: i32,
                                    placeholder_id: i32)
                                    -> i32;
    fn flow_node_create_canvas(c: *mut Context,
                                   g: *mut *mut Graph,
                                   prev_node: i32,
                                   format: PixelFormat,
                                   width: usize,
                                   height: usize,
                                   bgcolor: u32)
                                   -> i32;

    fn flow_node_create_scale(c: *mut Context,
                                  g: *mut *mut Graph,
                                  prev_node: i32,
                                  width: usize,
                                  height: usize,
                                  downscale_filter: i32,
                                  upscale_filter: i32,
                                  flags: usize,
                                  sharpen: f32)
                                  -> i32;

    fn flow_node_create_expand_canvas(c: *mut Context,
                                          g: *mut *mut Graph,
                                          prev_node: i32,
                                          left: u32,
                                          top: u32,
                                          right: u32,
                                          bottom: u32,
                                          canvas_color_srgb: u32)
                                          -> i32;

    fn flow_node_create_fill_rect(c: *mut Context,
                                      g: *mut *mut Graph,
                                      prev_node: i32,
                                      x1: u32,
                                      y1: u32,
                                      x2: u32,
                                      y2: u32,
                                      color_srgb: u32)
                                      -> i32;

    fn flow_node_create_rotate_90(c: *mut Context, g: *mut *mut Graph, prev_node: i32) -> i32;
    fn flow_node_create_rotate_180(c: *mut Context, g: *mut *mut Graph, prev_node: i32) -> i32;
    fn flow_node_create_rotate_270(c: *mut Context, g: *mut *mut Graph, prev_node: i32) -> i32;

    fn flow_node_create_transpose(c: *mut Context, g: *mut *mut Graph, prev_node: i32) -> i32;

    fn flow_node_create_primitive_copy_rect_to_canvas(c: *mut Context,
                                                          g: *mut *mut Graph,
                                                          prev_node: i32,
                                                          from_x: u32,
                                                          from_y: u32,
                                                          width: u32,
                                                          height: u32,
                                                          x: u32,
                                                          y: u32)
                                                          -> i32;

    fn flow_node_create_encoder(c: *mut Context,
                                    g: *mut *mut Graph,
                                    prev_node: i32,
                                    placeholder_id: i32,
                                    desired_encoder_id: i64,
                                    hints: *const EncoderHints)
                                    -> i32;

    fn flow_node_create_primitive_flip_vertical(c: *mut Context,
                                                    g: *mut *mut Graph,
                                                    prev_node: i32)
                                                    -> i32;

    fn flow_node_create_primitive_flip_horizontal(c: *mut Context,
                                                      g: *mut *mut Graph,
                                                      prev_node: i32)
                                                      -> i32;

    fn flow_node_create_primitive_crop(c: *mut Context,
                                           g: *mut *mut Graph,
                                           prev_node: i32,
                                           x1: u32,
                                           y1: u32,
                                           x2: u32,
                                           y2: u32)
                                           -> i32;
*/
}

<|endoftext|>


<commit_before><commit_msg>dynamically generate example assets with cfg! platform switch<commit_after><|endoftext|>


<commit_before>use std::env;

use serenity::{
    async_trait,
    model::{channel::Message, gateway::Ready},
    prelude::*,
};

struct Handler;

#[async_trait]
impl EventHandler for Handler {
    async fn message(&self, ctx: Context, msg: Message) {
        if msg.content == "!hello" {
            // The create message builder allows you to easily create embeds and messages
            // using a builder syntax.
            // This example will create a message that says "Hello, World!", with an embed that has
            // a title, description, an image, three fields, and a footer.
            let msg = msg
                .channel_id
                .send_message(&ctx.http, |m| {
                    m.content("Hello, World!")
                        .embed(|e| {
                            e.title("This is a title")
                                .description("This is a description")
                                .image("attachment://ferris_eyes.png")
                                .fields(vec![
                                    ("This is the first field", "This is a field body", true),
                                    ("This is the second field", "Both fields are inline", true),
                                ])
                                .field("This is the third field", "This is not an inline field", false)
                                .footer(|f| f.text("This is a footer"))
                                // Add a timestamp for the current time
                                // This also accepts a rfc3339 Timestamp
                                .timestamp(chrono::Utc::now())
                        })
                        .add_file("./ferris_eyes.png")
                })
                .await;

            if let Err(why) = msg {
                println!("Error sending message: {:?}", why);
            }
        }
    }

    async fn ready(&self, _: Context, ready: Ready) {
        println!("{} is connected!", ready.user.name);
    }
}

#[tokio::main]
async fn main() {
    // Configure the client with your Discord bot token in the environment.
    let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
    let mut client =
        Client::builder(&token).event_handler(Handler).await.expect("Err creating client");

    if let Err(why) = client.start().await {
        println!("Client error: {:?}", why);
    }
}
<commit_msg>Fix the `e09_create_message_builder` example when the `time` feature is enabled (#1693)<commit_after>use std::env;

use serenity::{
    async_trait,
    model::Timestamp,
    model::{channel::Message, gateway::Ready},
    prelude::*,
};

struct Handler;

#[async_trait]
impl EventHandler for Handler {
    async fn message(&self, ctx: Context, msg: Message) {
        if msg.content == "!hello" {
            // The create message builder allows you to easily create embeds and messages
            // using a builder syntax.
            // This example will create a message that says "Hello, World!", with an embed that has
            // a title, description, an image, three fields, and a footer.
            let msg = msg
                .channel_id
                .send_message(&ctx.http, |m| {
                    m.content("Hello, World!")
                        .embed(|e| {
                            e.title("This is a title")
                                .description("This is a description")
                                .image("attachment://ferris_eyes.png")
                                .fields(vec![
                                    ("This is the first field", "This is a field body", true),
                                    ("This is the second field", "Both fields are inline", true),
                                ])
                                .field("This is the third field", "This is not an inline field", false)
                                .footer(|f| f.text("This is a footer"))
                                // Add a timestamp for the current time
                                // This also accepts a rfc3339 Timestamp
                                .timestamp(Timestamp::now())
                        })
                        .add_file("./ferris_eyes.png")
                })
                .await;

            if let Err(why) = msg {
                println!("Error sending message: {:?}", why);
            }
        }
    }

    async fn ready(&self, _: Context, ready: Ready) {
        println!("{} is connected!", ready.user.name);
    }
}

#[tokio::main]
async fn main() {
    // Configure the client with your Discord bot token in the environment.
    let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
    let mut client =
        Client::builder(&token).event_handler(Handler).await.expect("Err creating client");

    if let Err(why) = client.start().await {
        println!("Client error: {:?}", why);
    }
}
<|endoftext|>


<commit_before>use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use gdk_pixbuf::{Colorspace, Pixbuf};

use librsvg::surface_utils::shared_surface::SharedImageSurface;

fn bench_surface_from_pixbuf(c: &mut Criterion) {
    let mut group = c.benchmark_group("surface_from_pixbuf");

    for input in [false, true].iter() {
        group.bench_with_input(
            BenchmarkId::from_parameter(format!("{:?}", input)),
            input,
            |b, alpha| {
                let pixbuf = Pixbuf::new(Colorspace::Rgb, *alpha, 8, 256, 256).unwrap();

                // Fill the surface with interesting data
                for y in 0..pixbuf.get_width() {
                    for x in 0..pixbuf.get_height() {
                        pixbuf.put_pixel(x, y, x as u8, y as u8, x.max(y) as u8, 0xff);
                    }
                }

                b.iter(|| SharedImageSurface::from_pixbuf(&pixbuf, None, None).unwrap())
            },
        );
    }
}

criterion_group!(benches, bench_surface_from_pixbuf);
criterion_main!(benches);
<commit_msg>Fix the surface_from_pixbuf benchmark<commit_after>use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use gdk_pixbuf::{Colorspace, Pixbuf};

use librsvg::surface_utils::shared_surface::SharedImageSurface;

fn bench_surface_from_pixbuf(c: &mut Criterion) {
    let mut group = c.benchmark_group("surface_from_pixbuf");

    for input in [false, true].iter() {
        group.bench_with_input(
            BenchmarkId::from_parameter(format!("{:?}", input)),
            input,
            |b, alpha| {
                let pixbuf = Pixbuf::new(Colorspace::Rgb, *alpha, 8, 256, 256).unwrap();

                // Fill the surface with interesting data
                for y in 0..pixbuf.get_width() {
                    for x in 0..pixbuf.get_height() {
                        pixbuf.put_pixel(
                            x as u32,
                            y as u32,
                            x as u8,
                            y as u8,
                            x.max(y) as u8,
                            0xff,
                        );
                    }
                }

                b.iter(|| SharedImageSurface::from_pixbuf(&pixbuf, None, None).unwrap())
            },
        );
    }
}

criterion_group!(benches, bench_surface_from_pixbuf);
criterion_main!(benches);
<|endoftext|>


<commit_before><commit_msg>Operation from_str done<commit_after><|endoftext|>


<commit_before>use std::{io, fs};

macro_rules! readln {
    () => {
        {
            let mut line = String::new();
            match io::stdin().read_line(&mut line) {
                Ok(n) => Some(line.trim().to_string()),
                Err(e) => None
            }
        }
    };
}

fn console_title(title: &str){

}

#[no_mangle]
pub fn main() {
    console_title("Test");

    println!("Type help for a command list");
    while let Some(line) = readln!() {
        let args: Vec<String> = line.split(' ').map(|arg| arg.to_string()).collect();

        if let Some(command) = args.get(0) {
            println!("# {}", line);

            match &command[..]
            {
                "panic" => panic!("Test panic"),
                "ls" => {
                    // TODO: when libredox is completed
                    //fs::read_dir("/").unwrap().map(|dir| println!("{}", dir));
                }
                _ => println!("Commands: panic"),
            }
        }
    }
}
<commit_msg>Use an array to label all commands and add `ptr_write` command<commit_after>#![feature(alloc)]
#![feature(core)]

extern crate alloc;
extern crate core;

use alloc::boxed::Box;
use std::{io, fs, rand};
use core::ptr;

macro_rules! readln {
    () => {
        {
            let mut line = String::new();
            match io::stdin().read_line(&mut line) {
                Ok(n) => Some(line.trim().to_string()),
                Err(e) => None
            }
        }
    };
}

fn console_title(title: &str){

}

#[no_mangle]
pub fn main() {
    console_title("Test");

    println!("Type help for a command list");
    while let Some(line) = readln!() {
        let args: Vec<String> = line.split(' ').map(|arg| arg.to_string()).collect();

        if let Some(command) = args.get(0) {
            println!("# {}", line);
            let console_commands = ["panic", "ls", "ptr_write"];

            match &command[..]
            {
                command if command == console_commands[0] => panic!("Test panic"),
                command if command == console_commands[1] => {
                    // TODO: import std::fs functions into libredox
                    //fs::read_dir("/").unwrap().map(|dir| println!("{}", dir));
                }
                command if command == console_commands[2] => {
                    let a_ptr = rand() as *mut u8;
                    // TODO: import Box::{from_raw, to_raw} methods in libredox
                    //let mut a_box = Box::new(rand() as u8);
                    unsafe {
                        ptr::write(a_ptr, rand() as u8);
                        //ptr::write(a_box.to_raw(), rand() as u8);
                    }
                }
                _ => println!("Commands: {}", console_commands.join(" ")),
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Unused error variant removed<commit_after><|endoftext|>


<commit_before><commit_msg>Add missing file<commit_after>use std::sync::{Arc};
use std::sync::atomic::{AtomicUsize, Ordering};

use mioco::{CoroutineControl, Handler, Scheduler, SchedulerThread};
use mioco::mio::{EventLoop};

pub struct BalancingScheduler {
	thread_counter: AtomicUsize,
	length_refs: Arc<Vec<AtomicUsize>>,
}

impl BalancingScheduler {
	pub fn new(num_threads: usize) -> BalancingScheduler {
		let mut length_refs = Vec::new();
		for _ in 0..num_threads { length_refs.push(AtomicUsize::new(0)); }

		BalancingScheduler {
			thread_counter: AtomicUsize::new(0),
			length_refs: Arc::new(length_refs),
		}
	}
}

unsafe impl Send for BalancingScheduler {}
unsafe impl Sync for BalancingScheduler {}

impl Scheduler for BalancingScheduler {
	fn spawn_thread(&self) -> Box<SchedulerThread> {
		let thread_id = self.thread_counter.fetch_add(1, Ordering::Relaxed);

		let thread = Box::new(BalancingSchedulerThread {
			counter:     0,
			thread_id:   thread_id,
			q:           Vec::new(),
			length_refs: self.length_refs.clone(),
		});

		thread
	}
}

struct BalancingSchedulerThread {
	counter:     usize,
	thread_id:   usize,
	q:           Vec<CoroutineControl>,
	length_refs: Arc<Vec<AtomicUsize>>,
}

impl SchedulerThread for BalancingSchedulerThread {
	fn spawned(&mut self, event_loop: &mut EventLoop<Handler>, coroutine_ctrl: CoroutineControl) {
		let (thread_id, min) = self.length_refs.iter().enumerate().fold(
			(0, usize::max_value()),
			|(min_id, min), (thread_id, length)| {
				let len = length.load(Ordering::Relaxed);

				if len < min { (thread_id, len) }
				else         { (min_id,    min) }
			}
		);

		let thread_id = if min == 0 {
			self.counter = (self.counter + 1) % self.length_refs.len();
			self.counter
		} else {
			thread_id
		};

		if thread_id == self.thread_id { coroutine_ctrl.resume(event_loop); }
		else                           { coroutine_ctrl.migrate(event_loop, thread_id); }
	}

	fn ready(&mut self, event_loop: &mut EventLoop<Handler>, coroutine_ctrl: CoroutineControl) {
		if coroutine_ctrl.is_yielding() {
			self.q.push(coroutine_ctrl);
			self.length_refs[self.thread_id].fetch_add(1, Ordering::Relaxed);
		} else {
/*			self.counter = (self.counter + 1) % self.length_refs.len();
			if self.counter == self.thread_id { coroutine_ctrl.resume(event_loop); }
			else                              { coroutine_ctrl.migrate(event_loop, self.counter); }
*/			coroutine_ctrl.resume(event_loop);
		}
	}

	fn tick(&mut self, event_loop: &mut EventLoop<Handler>) {
		while let Some(coroutine_ctrl) = self.q.pop() {
			coroutine_ctrl.resume(event_loop); // or migrate them here
			self.length_refs[self.thread_id].fetch_sub(1, Ordering::Relaxed);
		}
	}

	fn timeout(&mut self) -> Option<u64> { None }
}
<|endoftext|>


<commit_before><commit_msg>Fixing tests<commit_after><|endoftext|>


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

// revisions: rpass1 rpass2

#![feature(rustc_attrs)]
#![allow(private_no_mangle_fns)]

#![rustc_partition_reused(module="change_symbol_export_status", cfg="rpass2")]
#![rustc_partition_translated(module="change_symbol_export_status-mod1", cfg="rpass2")]

// This test case makes sure that a change in symbol visibility is detected by
// our dependency tracking. We do this by changing a module's visibility to
// `private` in rpass2, causing the contained function to go from `default` to
// `hidden` visibility.
// The function is marked with #[no_mangle] so it is considered for exporting
// even from an executable. Plain Rust functions are only exported from Rust
// libraries, which our test infrastructure does not support.

#[cfg(rpass1)]
pub mod mod1 {
    #[no_mangle]
    pub fn foo() {}
}

#[cfg(rpass2)]
mod mod1 {
    #[no_mangle]
    pub fn foo() {}
}

fn main() {
    mod1::foo();
}
<|endoftext|>


<commit_before><commit_msg>Make the number of pregenerated dice rolls public<commit_after><|endoftext|>


<commit_before><commit_msg>remove PmError<commit_after><|endoftext|>


<commit_before><commit_msg>Always inline DepFn::call<commit_after><|endoftext|>


<commit_before>use std::fmt;
use std::io;
//use std::net::SocketAddr;

use futures::{Future, Poll, Async};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio::reactor::Handle;
use tokio::net::{TcpStream, TcpStreamNew};
use tokio_service::Service;
use Uri;

use super::dns;

/// A connector creates an Io to a remote address..
///
/// This trait is not implemented directly, and only exists to make
/// the intent clearer. A connector should implement `Service` with
/// `Request=Uri` and `Response: Io` instead.
pub trait Connect: Service<Request=Uri, Error=io::Error> + 'static {
    /// The connected Io Stream.
    type Output: AsyncRead + AsyncWrite + 'static;
    /// A Future that will resolve to the connected Stream.
    type Future: Future<Item=Self::Output, Error=io::Error> + 'static;
    /// Connect to a remote address.
    fn connect(&self, Uri) -> <Self as Connect>::Future;
}

impl<T> Connect for T
where T: Service<Request=Uri, Error=io::Error> + 'static,
      T::Response: AsyncRead + AsyncWrite,
      T::Future: Future<Error=io::Error>,
{
    type Output = T::Response;
    type Future = T::Future;

    fn connect(&self, url: Uri) -> <Self as Connect>::Future {
        self.call(url)
    }
}

/// A connector for the `http` scheme.
#[derive(Clone)]
pub struct HttpConnector {
    dns: dns::Dns,
    handle: Handle,
}

impl HttpConnector {

    /// Construct a new HttpConnector.
    ///
    /// Takes number of DNS worker threads.
    pub fn new(threads: usize, handle: &Handle) -> HttpConnector {
        HttpConnector {
            dns: dns::Dns::new(threads),
            handle: handle.clone(),
        }
    }
}

impl fmt::Debug for HttpConnector {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("HttpConnector")
            .finish()
    }
}

impl Service for HttpConnector {
    type Request = Uri;
    type Response = TcpStream;
    type Error = io::Error;
    type Future = HttpConnecting;

    fn call(&self, url: Uri) -> Self::Future {
        debug!("Http::connect({:?})", url);
        let host = match url.host() {
            Some(s) => s,
            None => return HttpConnecting {
                state: State::Error(Some(io::Error::new(io::ErrorKind::InvalidInput, "invalid url"))),
                handle: self.handle.clone(),
            },
        };
        let port = url.port().unwrap_or(80);

        HttpConnecting {
            state: State::Resolving(self.dns.resolve(host.into(), port)),
            handle: self.handle.clone(),
        }
    }

}

/// A Future representing work to connect to a URL.
pub struct HttpConnecting {
    state: State,
    handle: Handle,
}

enum State {
    Resolving(dns::Query),
    Connecting(ConnectingTcp),
    Error(Option<io::Error>),
}

impl Future for HttpConnecting {
    type Item = TcpStream;
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            let state;
            match self.state {
                State::Resolving(ref mut query) => {
                    match try!(query.poll()) {
                        Async::NotReady => return Ok(Async::NotReady),
                        Async::Ready(addrs) => {
                            state = State::Connecting(ConnectingTcp {
                                addrs: addrs,
                                current: None,
                            })
                        }
                    };
                },
                State::Connecting(ref mut c) => return c.poll(&self.handle).map_err(From::from),
                State::Error(ref mut e) => return Err(e.take().expect("polled more than once")),
            }
            self.state = state;
        }
    }
}

impl fmt::Debug for HttpConnecting {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("HttpConnecting")
    }
}

struct ConnectingTcp {
    addrs: dns::IpAddrs,
    current: Option<TcpStreamNew>,
}

impl ConnectingTcp {
    // not a Future, since passing a &Handle to poll
    fn poll(&mut self, handle: &Handle) -> Poll<TcpStream, io::Error> {
        let mut err = None;
        loop {
            if let Some(ref mut current) = self.current {
                match current.poll() {
                    Ok(ok) => return Ok(ok),
                    Err(e) => {
                        trace!("connect error {:?}", e);
                        err = Some(e);
                        if let Some(addr) = self.addrs.next() {
                            debug!("connecting to {:?}", addr);
                            *current = TcpStream::connect(&addr, handle);
                            continue;
                        }
                    }
                }
            } else if let Some(addr) = self.addrs.next() {
                debug!("connecting to {:?}", addr);
                self.current = Some(TcpStream::connect(&addr, handle));
                continue;
            }

            return Err(err.take().expect("missing connect error"));
        }
    }
}

/*
impl<S: SslClient> HttpsConnector<S> {
    /// Create a new connector using the provided SSL implementation.
    pub fn new(s: S) -> HttpsConnector<S> {
        HttpsConnector {
            http: HttpConnector::default(),
            ssl: s,
        }
    }
}
*/

#[cfg(test)]
mod tests {
    use std::io;
    use tokio::reactor::Core;
    use super::{Connect, HttpConnector};

    #[test]
    fn test_non_http_url() {
        let mut core = Core::new().unwrap();
        let url = "/foo/bar?baz".parse().unwrap();
        let connector = HttpConnector::new(1, &core.handle());

        assert_eq!(core.run(connector.connect(url)).unwrap_err().kind(), io::ErrorKind::InvalidInput);
    }

}
<commit_msg>fix(client): get default port for https with Uri<commit_after>use std::fmt;
use std::io;
//use std::net::SocketAddr;

use futures::{Future, Poll, Async};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio::reactor::Handle;
use tokio::net::{TcpStream, TcpStreamNew};
use tokio_service::Service;
use Uri;

use super::dns;

/// A connector creates an Io to a remote address..
///
/// This trait is not implemented directly, and only exists to make
/// the intent clearer. A connector should implement `Service` with
/// `Request=Uri` and `Response: Io` instead.
pub trait Connect: Service<Request=Uri, Error=io::Error> + 'static {
    /// The connected Io Stream.
    type Output: AsyncRead + AsyncWrite + 'static;
    /// A Future that will resolve to the connected Stream.
    type Future: Future<Item=Self::Output, Error=io::Error> + 'static;
    /// Connect to a remote address.
    fn connect(&self, Uri) -> <Self as Connect>::Future;
}

impl<T> Connect for T
where T: Service<Request=Uri, Error=io::Error> + 'static,
      T::Response: AsyncRead + AsyncWrite,
      T::Future: Future<Error=io::Error>,
{
    type Output = T::Response;
    type Future = T::Future;

    fn connect(&self, url: Uri) -> <Self as Connect>::Future {
        self.call(url)
    }
}

/// A connector for the `http` scheme.
#[derive(Clone)]
pub struct HttpConnector {
    dns: dns::Dns,
    handle: Handle,
}

impl HttpConnector {

    /// Construct a new HttpConnector.
    ///
    /// Takes number of DNS worker threads.
    pub fn new(threads: usize, handle: &Handle) -> HttpConnector {
        HttpConnector {
            dns: dns::Dns::new(threads),
            handle: handle.clone(),
        }
    }
}

impl fmt::Debug for HttpConnector {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("HttpConnector")
            .finish()
    }
}

impl Service for HttpConnector {
    type Request = Uri;
    type Response = TcpStream;
    type Error = io::Error;
    type Future = HttpConnecting;

    fn call(&self, uri: Uri) -> Self::Future {
        debug!("Http::connect({:?})", uri);
        let host = match uri.host() {
            Some(s) => s,
            None => return HttpConnecting {
                state: State::Error(Some(io::Error::new(io::ErrorKind::InvalidInput, "invalid url"))),
                handle: self.handle.clone(),
            },
        };
        let port = match uri.port() {
            Some(port) => port,
            None => match uri.scheme() {
                Some("http") => 80,
                Some("https") => 443,
                _ => 80,
            },
        };

        HttpConnecting {
            state: State::Resolving(self.dns.resolve(host.into(), port)),
            handle: self.handle.clone(),
        }
    }

}

/// A Future representing work to connect to a URL.
pub struct HttpConnecting {
    state: State,
    handle: Handle,
}

enum State {
    Resolving(dns::Query),
    Connecting(ConnectingTcp),
    Error(Option<io::Error>),
}

impl Future for HttpConnecting {
    type Item = TcpStream;
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            let state;
            match self.state {
                State::Resolving(ref mut query) => {
                    match try!(query.poll()) {
                        Async::NotReady => return Ok(Async::NotReady),
                        Async::Ready(addrs) => {
                            state = State::Connecting(ConnectingTcp {
                                addrs: addrs,
                                current: None,
                            })
                        }
                    };
                },
                State::Connecting(ref mut c) => return c.poll(&self.handle).map_err(From::from),
                State::Error(ref mut e) => return Err(e.take().expect("polled more than once")),
            }
            self.state = state;
        }
    }
}

impl fmt::Debug for HttpConnecting {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("HttpConnecting")
    }
}

struct ConnectingTcp {
    addrs: dns::IpAddrs,
    current: Option<TcpStreamNew>,
}

impl ConnectingTcp {
    // not a Future, since passing a &Handle to poll
    fn poll(&mut self, handle: &Handle) -> Poll<TcpStream, io::Error> {
        let mut err = None;
        loop {
            if let Some(ref mut current) = self.current {
                match current.poll() {
                    Ok(ok) => return Ok(ok),
                    Err(e) => {
                        trace!("connect error {:?}", e);
                        err = Some(e);
                        if let Some(addr) = self.addrs.next() {
                            debug!("connecting to {:?}", addr);
                            *current = TcpStream::connect(&addr, handle);
                            continue;
                        }
                    }
                }
            } else if let Some(addr) = self.addrs.next() {
                debug!("connecting to {:?}", addr);
                self.current = Some(TcpStream::connect(&addr, handle));
                continue;
            }

            return Err(err.take().expect("missing connect error"));
        }
    }
}

/*
impl<S: SslClient> HttpsConnector<S> {
    /// Create a new connector using the provided SSL implementation.
    pub fn new(s: S) -> HttpsConnector<S> {
        HttpsConnector {
            http: HttpConnector::default(),
            ssl: s,
        }
    }
}
*/

#[cfg(test)]
mod tests {
    use std::io;
    use tokio::reactor::Core;
    use super::{Connect, HttpConnector};

    #[test]
    fn test_non_http_url() {
        let mut core = Core::new().unwrap();
        let url = "/foo/bar?baz".parse().unwrap();
        let connector = HttpConnector::new(1, &core.handle());

        assert_eq!(core.run(connector.connect(url)).unwrap_err().kind(), io::ErrorKind::InvalidInput);
    }

}
<|endoftext|>


<commit_before><commit_msg>Created the pwd builtin<commit_after>use rsh::State;

pub fn pwd(s: &mut State) -> i32 {
    println!("{}", s.cwd.display());

    0
}
<|endoftext|>


<commit_before><commit_msg>Fix ABI storing in AST.<commit_after><|endoftext|>


<commit_before><commit_msg>added todo comment<commit_after><|endoftext|>


<commit_before><commit_msg>Tweak values of default simulation<commit_after><|endoftext|>


<commit_before><commit_msg>Remove default constructor from RethinkDb<commit_after><|endoftext|>


<commit_before><commit_msg>Cosmetic changes.<commit_after><|endoftext|>


<commit_before><commit_msg>else-if conditional added<commit_after><|endoftext|>


<commit_before><commit_msg>Add example.<commit_after>extern crate hlc;
use hlc::Clock;
use std::thread::sleep;
use std::time::Duration;

fn main() {
    let mut clock_a = Clock::wall();
    let mut clock_b = Clock::wall();

    let b0 = clock_b.on_send();
    let a0 = clock_a.on_send();
    let a1 = clock_a.on_recv(&b0);

    println!("a0: {:?}", a0);
    println!("b0: {:?}", b0);
    println!("recv {:?} -> {:?}", b0, a1);
}
<|endoftext|>


<commit_before>use std::path::PathBuf;
use std::process::exit;

use libimagdiary::diary::Diary;
use libimagdiary::error::DiaryError as DE;
use libimagdiary::error::DiaryErrorKind as DEK;
use libimagentrylist::listers::core::CoreLister;
use libimagentrylist::lister::Lister;
use libimagrt::runtime::Runtime;
use libimagstore::store::Entry;
use libimagstore::storeid::StoreId;
use libimagerror::trace::trace_error;

use util::get_diary_name;

pub fn list(rt: &Runtime) {
    let diaryname = get_diary_name(rt);
    if diaryname.is_none() {
        warn!("No diary selected. Use either the configuration file or the commandline option");
        exit(1);
    }
    let diaryname = diaryname.unwrap();

    fn location_to_listing_string(id: &StoreId, base: &PathBuf) -> String {
        id.strip_prefix(base)
            .map_err(|e| trace_error(&e))
            .ok()
            .and_then(|p| p.to_str().map(String::from))
            .unwrap_or(String::from("<<Path Parsing Error>>"))
    }

    let diary = Diary::open(rt.store(), &diaryname[..]);
    debug!("Diary opened: {:?}", diary);
    diary.entries()
        .and_then(|es| {
            debug!("Iterator for listing: {:?}", es);

            let es = es.filter_map(|a| {
                debug!("Filtering: {:?}", a);
                a.ok()
            }).map(|e| e.into());

            let base = rt.store().path();

            CoreLister::new(&move |e: &Entry| location_to_listing_string(e.get_location(), base))
                .list(es) // TODO: Do not ignore non-ok()s
                .map_err(|e| DE::new(DEK::IOError, Some(Box::new(e))))
        })
        .map(|_| debug!("Ok"))
        .map_err(|e| trace_error(&e))
        .ok();
}

<commit_msg>Fix imag-diary::list::* for new StoreId Interface<commit_after>use std::process::exit;

use libimagdiary::diary::Diary;
use libimagdiary::error::DiaryError as DE;
use libimagdiary::error::DiaryErrorKind as DEK;
use libimagentrylist::listers::core::CoreLister;
use libimagentrylist::lister::Lister;
use libimagrt::runtime::Runtime;
use libimagstore::store::Entry;
use libimagerror::trace::trace_error;

use util::get_diary_name;

pub fn list(rt: &Runtime) {
    let diaryname = get_diary_name(rt);
    if diaryname.is_none() {
        warn!("No diary selected. Use either the configuration file or the commandline option");
        exit(1);
    }
    let diaryname = diaryname.unwrap();

    fn entry_to_location_listing_string(e: &Entry) -> String {
        e.get_location().clone()
            .without_base()
            .to_str()
            .map_err(|e| trace_error(&e))
            .unwrap_or(String::from("<<Path Parsing Error>>"))
    }

    let diary = Diary::open(rt.store(), &diaryname[..]);
    debug!("Diary opened: {:?}", diary);
    diary.entries()
        .and_then(|es| {
            debug!("Iterator for listing: {:?}", es);

            let es = es.filter_map(|a| {
                debug!("Filtering: {:?}", a);
                a.ok()
            }).map(|e| e.into());

            CoreLister::new(&entry_to_location_listing_string)
                .list(es) // TODO: Do not ignore non-ok()s
                .map_err(|e| DE::new(DEK::IOError, Some(Box::new(e))))
        })
        .map(|_| debug!("Ok"))
        .map_err(|e| trace_error(&e))
        .ok();
}

<|endoftext|>


<commit_before><commit_msg>command line work<commit_after><|endoftext|>


<commit_before><commit_msg>Revert "Make Debug fancy again and handle #[cfg] properly."<commit_after><|endoftext|>


<commit_before><commit_msg>Remove iter from trait<commit_after><|endoftext|>


<commit_before><commit_msg>Add pretty metadata in json<commit_after><|endoftext|>


<commit_before><commit_msg>Adjust comments for ty::fun stuff<commit_after><|endoftext|>


<commit_before><commit_msg>Added separate and expanded tests for vector monomials, including vector_mons_of_deg_le tests.<commit_after>use common::*;
use monomial::{Mon2d, Mon3d, Mon4d};
use vector_monomial::*;

#[test]
fn test_construction() {
  let x = Mon2d { exps: [Deg(1), Deg(0)] };
  let _: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(1), x);
}

#[test]
#[should_fail]
fn test_improper_construction() {
  let x = Mon2d { exps: [Deg(1), Deg(0)] };
  let _: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(3), x);
}

#[test]
fn test_divergence() {
  let one = Mon2d { exps: [Deg(0), Deg(0)] };
  let x = Mon2d { exps: [Deg(1), Deg(0)] };
  let y = Mon2d { exps: [Deg(0), Deg(1)] };

  let x_dim0_vmon: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(0), x);
  assert_eq!(x_dim0_vmon.divergence_coef_and_mon(), (1.,one));

  let y_dim0_vmon: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(0), y);
  assert_eq!(y_dim0_vmon.divergence_coef_and_mon(), (0.,y));

  let y_dim1_vmon: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(1), y);
  assert_eq!(y_dim1_vmon.divergence_coef_and_mon(), (1.,one));

  let xy_dim0_vmon: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(0), x*y);
  assert_eq!(xy_dim0_vmon.divergence_coef_and_mon(), (1.,y));

  let x2y3_dim1_vmon: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(1), x*x*y*y*y);
  assert_eq!(x2y3_dim1_vmon.divergence_coef_and_mon(), (3., x*x*y*y));
}

#[test]
fn test_vector_mons_of_deg_le_2d() {
  let one = Mon2d { exps: [Deg(0), Deg(0)] };
  let x = Mon2d { exps: [Deg(1), Deg(0)] };
  let y = Mon2d { exps: [Deg(0), Deg(1)] };
  let one_dim0: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(0), one);
  let y_dim0: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(0), y);
  let y2_dim0: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(0), y*y);
  let x_dim0: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(0), x);
  let xy_dim0: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(0), x*y);
  let x2_dim0: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(0), x*x);
  let one_dim1: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(1), one);
  let y_dim1: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(1), y);
  let y2_dim1: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(1), y*y);
  let x_dim1: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(1), x);
  let xy_dim1: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(1), x*y);
  let x2_dim1: VectorMonomial<Mon2d> = VectorMonomial::new(Dim(1), x*x);

  let vmons_deg0: ~[VectorMonomial<Mon2d>] = VectorMonomial::vector_mons_of_deg_le(Deg(0));
  assert_eq!(&vmons_deg0, &~[one_dim0, one_dim1]);

  let vmons_deg1: ~[VectorMonomial<Mon2d>] = VectorMonomial::vector_mons_of_deg_le(Deg(1));
  assert_eq!(&vmons_deg1,
             &~[one_dim0, y_dim0, x_dim0,
                one_dim1, y_dim1, x_dim1]);

  let vmons_deg2: ~[VectorMonomial<Mon2d>] = VectorMonomial::vector_mons_of_deg_le(Deg(2));
  assert_eq!(&vmons_deg2,
             &~[one_dim0, y_dim0, y2_dim0, x_dim0, xy_dim0, x2_dim0,
                one_dim1, y_dim1, y2_dim1, x_dim1, xy_dim1, x2_dim1]);
}

#[test]
fn test_vector_mons_of_deg_le_3d() {
  let one = Mon3d { exps: [Deg(0), Deg(0), Deg(0)] };
  let x = Mon3d { exps: [Deg(1), Deg(0), Deg(0)] };
  let y = Mon3d { exps: [Deg(0), Deg(1), Deg(0)] };
  let z = Mon3d { exps: [Deg(0), Deg(0), Deg(1)] };
  let one_dim0: VectorMonomial<Mon3d> = VectorMonomial::new(Dim(0), one);
  let z_dim0: VectorMonomial<Mon3d> = VectorMonomial::new(Dim(0), z);
  let y_dim0: VectorMonomial<Mon3d> = VectorMonomial::new(Dim(0), y);
  let x_dim0: VectorMonomial<Mon3d> = VectorMonomial::new(Dim(0), x);
  let one_dim1: VectorMonomial<Mon3d> = VectorMonomial::new(Dim(1), one);
  let z_dim1: VectorMonomial<Mon3d> = VectorMonomial::new(Dim(1), z);
  let y_dim1: VectorMonomial<Mon3d> = VectorMonomial::new(Dim(1), y);
  let x_dim1: VectorMonomial<Mon3d> = VectorMonomial::new(Dim(1), x);
  let one_dim2: VectorMonomial<Mon3d> = VectorMonomial::new(Dim(2), one);
  let z_dim2: VectorMonomial<Mon3d> = VectorMonomial::new(Dim(2), z);
  let y_dim2: VectorMonomial<Mon3d> = VectorMonomial::new(Dim(2), y);
  let x_dim2: VectorMonomial<Mon3d> = VectorMonomial::new(Dim(2), x);

  let vmons_deg0: ~[VectorMonomial<Mon3d>] = VectorMonomial::vector_mons_of_deg_le(Deg(0));
  assert_eq!(&vmons_deg0, &~[one_dim0, one_dim1, one_dim2]);

  let vmons_deg1: ~[VectorMonomial<Mon3d>] = VectorMonomial::vector_mons_of_deg_le(Deg(1));
  assert_eq!(&vmons_deg1,
             &~[one_dim0, z_dim0, y_dim0, x_dim0,
                one_dim1, z_dim1, y_dim1, x_dim1,
                one_dim2, z_dim2, y_dim2, x_dim2]);
}

#[test]
fn test_vector_mons_of_deg_le_4d() {
  let one = Mon4d { exps: [Deg(0), Deg(0), Deg(0), Deg(0)] };
  let x = Mon4d { exps: [Deg(1), Deg(0), Deg(0), Deg(0)] };
  let y = Mon4d { exps: [Deg(0), Deg(1), Deg(0), Deg(0)] };
  let z = Mon4d { exps: [Deg(0), Deg(0), Deg(1), Deg(0)] };
  let t = Mon4d { exps: [Deg(0), Deg(0), Deg(0), Deg(1)] };
  let one_dim0: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(0), one);
  let t_dim0: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(0), t);
  let z_dim0: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(0), z);
  let y_dim0: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(0), y);
  let x_dim0: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(0), x);
  let one_dim1: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(1), one);
  let t_dim1: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(1), t);
  let z_dim1: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(1), z);
  let y_dim1: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(1), y);
  let x_dim1: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(1), x);
  let one_dim2: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(2), one);
  let t_dim2: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(2), t);
  let z_dim2: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(2), z);
  let y_dim2: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(2), y);
  let x_dim2: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(2), x);
  let one_dim3: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(3), one);
  let t_dim3: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(3), t);
  let z_dim3: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(3), z);
  let y_dim3: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(3), y);
  let x_dim3: VectorMonomial<Mon4d> = VectorMonomial::new(Dim(3), x);

  let vmons_deg0: ~[VectorMonomial<Mon4d>] = VectorMonomial::vector_mons_of_deg_le(Deg(0));
  assert_eq!(&vmons_deg0, &~[one_dim0, one_dim1, one_dim2, one_dim3]);

  let vmons_deg1: ~[VectorMonomial<Mon4d>] = VectorMonomial::vector_mons_of_deg_le(Deg(1));
  assert_eq!(&vmons_deg1,
             &~[one_dim0, t_dim0, z_dim0, y_dim0, x_dim0,
                one_dim1, t_dim1, z_dim1, y_dim1, x_dim1,
                one_dim2, t_dim2, z_dim2, y_dim2, x_dim2,
                one_dim3, t_dim3, z_dim3, y_dim3, x_dim3]);
}

<|endoftext|>


<commit_before><commit_msg>Add basic tests for Matrix::try_inverse<commit_after>#[macro_use]
extern crate approx;

extern crate nalgebra as na;

use na::{Matrix1, Matrix2, Matrix3, Matrix5};

#[test]
fn matrix1_try_inverse() {
    let a = Matrix1::new(3.0);
    let a_inv = a.try_inverse().expect("Matrix is invertible");

    assert_relative_eq!(a_inv, Matrix1::new(1.0 / 3.0));
}

#[test]
fn matrix2_try_inverse() {
    let a = Matrix2::new(  5.0,  -2.0,
                         -10.0,   1.0);
    let expected_inverse = Matrix2::new(-0.2 / 3.0, -2.0 / 15.0,
                                        -2.0 / 3.0, -1.0 / 3.0);
    let a_inv = a.try_inverse()
                 .expect("Matrix is invertible");

    assert_relative_eq!(a_inv, expected_inverse);
}

#[test]
fn matrix3_try_inverse() {
    let a = Matrix3::new(-3.0,  2.0,  0.0,
                         -6.0,  9.0, -2.0,
                          9.0, -6.0,  4.0);
    let expected_inverse = Matrix3::new(-0.40, 0.4 / 3.0, 0.2 / 3.00,
                                        -0.10,       0.2,       0.10,
                                         0.75,       0.0,       0.25);
    let a_inv = a.try_inverse()
                 .expect("Matrix is invertible");

    assert_relative_eq!(a_inv, expected_inverse);
}

#[test]
fn matrix5_try_inverse() {
    // Dimension 5 is chosen so that the inversion
    // happens by Gaussian elimination
    // (at the time of writing dimensions <= 3 are implemented
    //  as analytic formulas, but we choose 5 in the case that 4
    //  also gets an analytic implementation)
    let a = Matrix5::new(-2.0,   0.0,   2.0,   5.0,  -5.0,
                         -6.0,   4.0,   4.0,  13.0, -15.0,
                          4.0,  16.0, -14.0, -19.0,  12.0,
                         12.0,  12.0, -22.0, -35.0,  34.0,
                         -8.0,   4.0,  12.0,  27.0, -31.0);
    let expected_inverse = Matrix5::new(
        3.9333e+00,  -1.5667e+00,   2.6667e-01,   6.6667e-02,  3.0000e-01,
       -1.2033e+01,   3.9667e+00,  -1.1167e+00,   2.8333e-01, -1.0000e-01,
       -1.8233e+01,   5.7667e+00,  -1.5667e+00,   2.3333e-01, -2.0000e-01,
       -4.3333e+00,   1.6667e+00,  -6.6667e-01,   3.3333e-01, -4.6950e-19,
       -1.3400e+01,   4.6000e+00,  -1.4000e+00,   4.0000e-01, -2.0000e-01);
    let a_inv = a.try_inverse().expect("Matrix is invertible");

    assert_relative_eq!(a_inv, expected_inverse, max_relative=1e-4);
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #114 - achanda:is_nan, r=hauleth<commit_after><|endoftext|>


<commit_before><commit_msg>reorganized control is working with avatar attack<commit_after><|endoftext|>


<commit_before><commit_msg>Add ui test with pinned extern Rust type<commit_after>use std::marker::PhantomPinned;

#[cxx::bridge]
mod ffi {
    extern "Rust" {
        type Pinned;
    }
}

pub struct Pinned {
    _pinned: PhantomPinned,
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add a JSON bench<commit_after>//#![feature(trace_macros)]
#![feature(test)]
extern crate test;

#[macro_use]
extern crate nom;

use nom::{digit, alphanumeric};

use test::Bencher;

use std::str::{self,FromStr};
use std::collections::HashMap;

#[derive(Debug,PartialEq)]
pub enum JsonValue {
  Str(String),
  Num(f32),
  Array(Vec<JsonValue>),
  Object(HashMap<String,JsonValue>)
}

// FIXME: since we already parsed a serie of digits and dots,
// we know it is correct UTF-8. no need to use from_utf8 to
// verify it is correct
// FIXME: use alt_complete (implement ws for alt_complete)
named!(unsigned_float <f32>, map_res!(
  map_res!(
    recognize!(
      alt_complete!(
        delimited!(digit, tag!("."), opt!(complete!(digit))) |
        delimited!(opt!(digit), tag!("."), digit)            |
        digit
      )
    ),
    str::from_utf8
  ),
  FromStr::from_str
));
named!(float<f32>, map!(
  pair!(
    opt!(alt!(tag!("+") | tag!("-"))),
    unsigned_float
  ),
  |(sign, value): (Option<&[u8]>, f32)| {
    sign.and_then(|s| if s[0] == ('-' as u8) { Some(-1f32) } else { None }).unwrap_or(1f32) * value
  }
));

//FIXME: verify how json strings are formatted
named!(string<&str>,
  delimited!(
    tag!("\""),
    map_res!(escaped!(call!(alphanumeric), '\\', is_a!("\"n\\")), str::from_utf8),
    tag!("\"")
  )
);

named!(array < Vec<JsonValue> >,
  ws!(
    delimited!(
      tag!("["),
      separated_list!(tag!(","), value),
      tag!("]")
    )
  )
);

named!(key_value<(&str,JsonValue)>,
  ws!(
    separated_pair!(
      string,
      tag!(":"),
      value
    )
  )
);

named!(hash< HashMap<String,JsonValue> >,
  ws!(
    map!(
      delimited!(
        tag!("{"),
        separated_list!(tag!(","), key_value),
        tag!("}")
        ),
      |tuple_vec| {
        let mut h: HashMap<String, JsonValue> = HashMap::new();
        for (k, v) in tuple_vec {
          h.insert(String::from(k), v);
        }
        h
      }
    )
  )
);

named!(value<JsonValue>,
  ws!(
    alt!(
      hash   => { |h|   JsonValue::Object(h)            } |
      array  => { |v|   JsonValue::Array(v)             } |
      string => { |s|   JsonValue::Str(String::from(s)) } |
      float  => { |num| JsonValue::Num(num)             }
    )
  )
);

#[bench]
fn json_bench(b: &mut Bencher) {
  let data = &b"  { \"a\"\t: 42,
  \"b\": [ \"x\", \"y\", 12 ] ,
  \"c\": { \"hello\" : \"world\"
  }
  }  ";

  //println!("data:\n{:?}", value(&data[..]));
  b.iter(||{
    value(&data[..])
  });
}

<|endoftext|>


<commit_before><commit_msg>removed uncesesary comments of old code, modified the history comments in load_history and save_history, and made the cmd/args line cleaner<commit_after><|endoftext|>


<commit_before>#![crate_type = "bin"]

extern crate metrics;

use metrics::gauge;
use metrics::counter::StdCounter;
use metrics::counter::Counter;

fn main() {
    // Create a metric w val 0
    let mut g1: gauge::Gauge = gauge::Gauge{value: 0};
    println!("{}", g1.value);
    g1.update(100);

    // Get a snapshot of it to g2
    let g2: gauge::Gauge = g1.snapshot();

    // Update g1 to 200
    g1.update(200);

    println!("g1 {} g2 {}", g1.value, g2.value);

    println!("{}", g1.value);

    let mut c1 = StdCounter{value: 0};
    c1.inc(1);
    c1.inc(5);
    println!("{}", c1.value)
}<commit_msg>Fixup according to latest changes<commit_after>#![crate_type = "bin"]

extern crate metrics;

use metrics::gauge;
use metrics::counter::{Counter,StdCounter};

use metrics::meter::{Meter,StdMeter};
use metrics::metric::Metric;

fn main() {
    // Create a metric w val 0
    let mut g1: gauge::Gauge = gauge::Gauge{value: 0};
    println!("{}", g1.value);
    g1.update(100);

    // Get a snapshot of it to g2
    let g2: gauge::Gauge = g1.snapshot();

    // Update g1 to 200
    g1.update(200);

    println!("g1 {} g2 {}", g1.value, g2.value);

    println!("{}", g1.value);

    let mut c1 = StdCounter::new();
    c1.inc(1);
    c1.inc(5);
    println!("{}", c1.value);

    let mut meter = StdMeter::new();
    meter.mark(3i64);
    meter.tick();
    println!("Meter count: {}", meter.count());
    println!("Meter rate: {}", meter.rate(1));
}<|endoftext|>


<commit_before><commit_msg>Correction to mix hop unwrapped meta array ref boundary<commit_after><|endoftext|>