<commit_before>#![crate_type="staticlib"]
#![feature(alloc)]
#![feature(allocator)]
#![feature(arc_counts)]
#![feature(asm)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(core_str_ext)]
#![feature(core_slice_ext)]
#![feature(fnbox)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(no_std)]
#![feature(unboxed_closures)]
#![feature(unsafe_no_drop_flag)]
#![feature(unwind_attributes)]
#![feature(vec_push_all)]
#![no_std]

#[macro_use]
extern crate alloc;

#[macro_use]
extern crate collections;

use alloc::boxed::Box;

use collections::string::{String, ToString};
use collections::vec::Vec;

use core::cell::UnsafeCell;
use core::{mem, usize};
use core::slice::SliceExt;

use common::debug;
use common::event::{self, EVENT_KEY, EventOption};
use common::memory;
use common::paging::Page;
use common::time::Duration;

use drivers::pci::*;
use drivers::pio::*;
use drivers::ps2::*;
use drivers::rtc::*;
use drivers::serial::*;

use env::Environment;

pub use externs::*;

use graphics::display;

use programs::executor::execute;
use programs::scheme::*;

use scheduler::{Context, Regs, TSS};
use scheduler::context::{context_enabled, context_switch, context_i, context_pid};

use schemes::Url;
use schemes::arp::*;
use schemes::context::*;
use schemes::debug::*;
use schemes::ethernet::*;
use schemes::icmp::*;
use schemes::ip::*;
use schemes::memory::*;
// use schemes::display::*;

use syscall::handle::*;

/// Common std-like functionality
#[macro_use]
pub mod common;
/// Allocation
pub mod alloc_system;
/// Audio
pub mod audio;
/// Various drivers
/// TODO: Move out of kernel space (like other microkernels)
pub mod drivers;
/// Environment
pub mod env;
/// Externs
pub mod externs;
/// Various graphical methods
pub mod graphics;
/// Network
pub mod network;
/// Panic
pub mod panic;
/// Programs
pub mod programs;
/// Schemes
pub mod schemes;
/// Scheduling
pub mod scheduler;
/// Sync primatives
pub mod sync;
/// System calls
pub mod syscall;
/// USB input/output
pub mod usb;

pub static mut TSS_PTR: Option<&'static mut TSS> = None;

pub static mut ENV_PTR: Option<&'static mut Environment> = None;

pub fn env() -> &'static Environment {
    unsafe {
        match ENV_PTR {
            Some(&mut ref p) => p,
            None => unreachable!(),
        }
    }
}

/// Pit duration
static PIT_DURATION: Duration = Duration {
    secs: 0,
    nanos: 2250286,
};

/// Idle loop (active while idle)
unsafe fn idle_loop() -> ! {
    loop {
        asm!("cli" : : : : "intel", "volatile");

        let mut halt = true;

        {
            let contexts = ::env().contexts.lock();
            for i in 1..contexts.len() {
                match contexts.get(i) {
                    Some(context) => if context.interrupted {
                        halt = false;
                        break;
                    },
                    None => (),
                }
            }
        }

        if halt {
            asm!("sti" : : : : "intel", "volatile");
            asm!("hlt" : : : : "intel", "volatile");
        } else {
            asm!("sti" : : : : "intel", "volatile");
        }

        context_switch(false);
    }
}

/// Event poll loop
fn poll_loop() -> ! {
    loop {
        env().on_poll();

        unsafe { context_switch(false) };
    }
}

/// Event loop
fn event_loop() -> ! {
    let mut cmd = String::new();
    loop {
        loop {
            let mut console = env().console.lock();
            match env().events.lock().pop_front() {
                Some(event) => {
                    if console.draw {
                        match event.to_option() {
                            EventOption::Key(key_event) => {
                                if key_event.pressed {
                                    match key_event.scancode {
                                        event::K_F2 => {
                                            console.draw = false;
                                        }
                                        event::K_BKSP => if !cmd.is_empty() {
                                            console.write(&[8]);
                                            cmd.pop();
                                        },
                                        _ => match key_event.character {
                                            '\0' => (),
                                            '\n' => {
                                                console.command = Some(cmd.clone());

                                                cmd.clear();
                                                console.write(&[10]);
                                            }
                                            _ => {
                                                cmd.push(key_event.character);
                                                console.write(&[key_event.character as u8]);
                                            }
                                        },
                                    }
                                }
                            }
                            _ => (),
                        }
                    } else {
                        if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 {
                            console.draw = true;
                            console.redraw = true;
                        } else {
                            // TODO: Magical orbital hack
                            unsafe {
                                let reenable = scheduler::start_no_ints();
                                for scheme in env().schemes.iter() {
                                    if (*scheme.get()).scheme() == "orbital" {
                                        (*scheme.get()).event(&event);
                                        break;
                                    }
                                }
                                scheduler::end_no_ints(reenable);
                            }
                        }
                    }
                }
                None => break,
            }
        }

        {
            let mut console = env().console.lock();
            if console.draw {
                if console.redraw {
                    console.redraw = false;
                    console.display.flip();
                }
            }
        }

        unsafe { context_switch(false) };
    }
}

/// Initialize kernel
unsafe fn init(font_data: usize, tss_data: usize) {
    Page::init();
    memory::cluster_init();
    // Unmap first page to catch null pointer errors (after reading memory map)
    Page::new(0).unmap();

    sync::intex::intex_count = 0;

    display::fonts = font_data;
    TSS_PTR = Some(&mut *(tss_data as *mut TSS));

    ENV_PTR = Some(&mut *Box::into_raw(Environment::new()));

    context_pid = 1;
    context_i = 0;
    context_enabled = false;

    match ENV_PTR {
        Some(ref mut env) => {
            env.contexts.lock().push(Context::root());
            env.console.lock().draw = true;

            debug!("Redox ");
            debug::dd(mem::size_of::<usize>() * 8);
            debug!(" bits");
            debug::dl();

            env.clock_realtime = Rtc::new().time();

            env.schemes.push(UnsafeCell::new(Ps2::new()));
            env.schemes.push(UnsafeCell::new(Serial::new(0x3F8, 0x4)));

            pci_init(env);

            env.schemes.push(UnsafeCell::new(DebugScheme::new()));
            env.schemes.push(UnsafeCell::new(box ContextScheme));
            env.schemes.push(UnsafeCell::new(box MemoryScheme));
            // session.items.push(box RandomScheme);
            // session.items.push(box TimeScheme);

            env.schemes.push(UnsafeCell::new(box EthernetScheme));
            env.schemes.push(UnsafeCell::new(box ArpScheme));
            env.schemes.push(UnsafeCell::new(box IcmpScheme));
            env.schemes.push(UnsafeCell::new(box IpScheme { arp: Vec::new() }));
            // session.items.push(box DisplayScheme);

            Context::spawn("kpoll".to_string(),
            box move || {
                poll_loop();
            });

            Context::spawn("kevent".to_string(),
            box move || {
                event_loop();
            });

            Context::spawn("karp".to_string(),
            box move || {
                ArpScheme::reply_loop();
            });

            Context::spawn("kicmp".to_string(),
            box move || {
                IcmpScheme::reply_loop();
            });

            context_enabled = true;

            if let Some(mut resource) = Url::from_str("file:/schemes/").open() {
                let mut vec: Vec<u8> = Vec::new();
                resource.read_to_end(&mut vec);

                for folder in String::from_utf8_unchecked(vec).lines() {
                    if folder.ends_with('/') {
                        let scheme_item = SchemeItem::from_url(&Url::from_string("file:/schemes/"
                                                                                .to_string() +
                                                                                &folder));

                        let reenable = scheduler::start_no_ints();
                        env.schemes.push(UnsafeCell::new(scheme_item));
                        scheduler::end_no_ints(reenable);
                    }
                }
            }

            Context::spawn("kinit".to_string(),
            box move || {
                let wd_c = "file:/\0";
                do_sys_chdir(wd_c.as_ptr());

                let stdio_c = "debug:\0";
                do_sys_open(stdio_c.as_ptr(), 0);
                do_sys_open(stdio_c.as_ptr(), 0);
                do_sys_open(stdio_c.as_ptr(), 0);

                let path_string = "file:/apps/shell/main.bin";
                let path = Url::from_str(path_string);

                debug!("INIT: Executing {}\n", path_string);
                execute(path, Vec::new());
                debug!("INIT: Failed to execute\n");

                loop {
                    context_switch(false);
                }
            });
        },
        None => unreachable!(),
    }
}

#[cold]
#[inline(never)]
#[no_mangle]
/// Take regs for kernel calls and exceptions
pub extern "cdecl" fn kernel(interrupt: usize, mut regs: &mut Regs) {
    macro_rules! exception_inner {
        ($name:expr) => ({
            unsafe {
                if let Some(context) = Context::current() {
                    debugln!("PID {}: {}", context.pid, context.name);
                }
            }

            debugln!("  INT {:X}: {}", interrupt, $name);
            debugln!("    CS:  {:08X}    IP:  {:08X}    FLG: {:08X}", regs.cs, regs.ip, regs.flags);
            debugln!("    SS:  {:08X}    SP:  {:08X}    BP:  {:08X}", regs.ss, regs.sp, regs.bp);
            debugln!("    AX:  {:08X}    BX:  {:08X}    CX:  {:08X}    DX:  {:08X}", regs.ax, regs.bx, regs.cx, regs.dx);
            debugln!("    DI:  {:08X}    SI:  {:08X}", regs.di, regs.di);

            let cr0: usize;
            let cr2: usize;
            let cr3: usize;
            let cr4: usize;
            unsafe {
                asm!("mov $0, cr0" : "=r"(cr0) : : : "intel", "volatile");
                asm!("mov $0, cr2" : "=r"(cr2) : : : "intel", "volatile");
                asm!("mov $0, cr3" : "=r"(cr3) : : : "intel", "volatile");
                asm!("mov $0, cr4" : "=r"(cr4) : : : "intel", "volatile");
            }
            debugln!("    CR0: {:08X}    CR2: {:08X}    CR3: {:08X}    CR4: {:08X}", cr0, cr2, cr3, cr4);
        })
    };

    macro_rules! exception {
        ($name:expr) => ({
            exception_inner!($name);

            loop {
                unsafe { do_sys_exit(usize::MAX) };
            }
        })
    };

    macro_rules! exception_error {
        ($name:expr) => ({
            let error = regs.ip;
            regs.ip = regs.cs;
            regs.cs = regs.flags;
            regs.flags = regs.sp;
            regs.sp = regs.ss;
            regs.ss = 0;
            //regs.ss = regs.error;

            exception_inner!($name);
            debugln!("    ERR: {:08X}", error);

            loop {
                unsafe { do_sys_exit(usize::MAX) };
            }
        })
    };

    if interrupt >= 0x20 && interrupt < 0x30 {
        if interrupt >= 0x28 {
            unsafe { Pio8::new(0xA0).write(0x20) };
        }

        unsafe { Pio8::new(0x20).write(0x20) };
    }

    match interrupt {
        0x20 => {
            unsafe {
                let reenable = scheduler::start_no_ints();

                match ENV_PTR {
                    Some(ref mut env) => {
                        env.clock_realtime = env.clock_realtime + PIT_DURATION;
                        env.clock_monotonic = env.clock_monotonic + PIT_DURATION;

                        scheduler::end_no_ints(reenable);

                        let switch = if let Some(mut context) = Context::current_mut() {
                            context.slices -= 1;
                            context.slice_total += 1;
                            context.slices == 0
                        } else {
                            false
                        };

                        if switch {
                            context_switch(true);
                        }
                    },
                    None => unreachable!(),
                }
            }
        }
        0x21 => env().on_irq(0x1), // keyboard
        0x23 => env().on_irq(0x3), // serial 2 and 4
        0x24 => env().on_irq(0x4), // serial 1 and 3
        0x25 => env().on_irq(0x5), //parallel 2
        0x26 => env().on_irq(0x6), //floppy
        0x27 => env().on_irq(0x7), //parallel 1 or spurious
        0x28 => env().on_irq(0x8), //RTC
        0x29 => env().on_irq(0x9), //pci
        0x2A => env().on_irq(0xA), //pci
        0x2B => env().on_irq(0xB), //pci
        0x2C => env().on_irq(0xC), //mouse
        0x2D => env().on_irq(0xD), //coprocessor
        0x2E => env().on_irq(0xE), //disk
        0x2F => env().on_irq(0xF), //disk
        0x80 => if !unsafe { syscall_handle(regs) } {
            exception!("Unknown Syscall");
        },
        0xFF => {
            unsafe {
                init(regs.ax, regs.bx);
                idle_loop();
            }
        }
        0x0 => exception!("Divide by zero exception"),
        0x1 => exception!("Debug exception"),
        0x2 => exception!("Non-maskable interrupt"),
        0x3 => exception!("Breakpoint exception"),
        0x4 => exception!("Overflow exception"),
        0x5 => exception!("Bound range exceeded exception"),
        0x6 => exception!("Invalid opcode exception"),
        0x7 => exception!("Device not available exception"),
        0x8 => exception_error!("Double fault"),
        0xA => exception_error!("Invalid TSS exception"),
        0xB => exception_error!("Segment not present exception"),
        0xC => exception_error!("Stack-segment fault"),
        0xD => exception_error!("General protection fault"),
        0xE => exception_error!("Page fault"),
        0x10 => exception!("x87 floating-point exception"),
        0x11 => exception_error!("Alignment check exception"),
        0x12 => exception!("Machine check exception"),
        0x13 => exception!("SIMD floating-point exception"),
        0x14 => exception!("Virtualization exception"),
        0x1E => exception_error!("Security exception"),
        _ => exception!("Unknown Interrupt"),
    }
}
<commit_msg>Code cleanup<commit_after>#![crate_type="staticlib"]
#![feature(alloc)]
#![feature(allocator)]
#![feature(arc_counts)]
#![feature(asm)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(core_str_ext)]
#![feature(core_slice_ext)]
#![feature(fnbox)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(no_std)]
#![feature(unboxed_closures)]
#![feature(unsafe_no_drop_flag)]
#![feature(unwind_attributes)]
#![feature(vec_push_all)]
#![no_std]

#[macro_use]
extern crate alloc;

#[macro_use]
extern crate collections;

use alloc::boxed::Box;

use collections::string::{String, ToString};
use collections::vec::Vec;

use core::cell::UnsafeCell;
use core::{mem, usize};
use core::slice::SliceExt;

use common::debug;
use common::event::{self, EVENT_KEY, EventOption};
use common::memory;
use common::paging::Page;
use common::time::Duration;

use drivers::pci::*;
use drivers::pio::*;
use drivers::ps2::*;
use drivers::rtc::*;
use drivers::serial::*;

use env::Environment;

pub use externs::*;

use graphics::display;

use programs::executor::execute;
use programs::scheme::*;

use scheduler::{Context, Regs, TSS};
use scheduler::context::{context_enabled, context_switch, context_i, context_pid};

use schemes::Url;
use schemes::arp::*;
use schemes::context::*;
use schemes::debug::*;
use schemes::ethernet::*;
use schemes::icmp::*;
use schemes::ip::*;
use schemes::memory::*;
// use schemes::display::*;

use syscall::handle::*;

/// Common std-like functionality
#[macro_use]
pub mod common;
/// Allocation
pub mod alloc_system;
/// Audio
pub mod audio;
/// Various drivers
/// TODO: Move out of kernel space (like other microkernels)
pub mod drivers;
/// Environment
pub mod env;
/// Externs
pub mod externs;
/// Various graphical methods
pub mod graphics;
/// Network
pub mod network;
/// Panic
pub mod panic;
/// Programs
pub mod programs;
/// Schemes
pub mod schemes;
/// Scheduling
pub mod scheduler;
/// Sync primatives
pub mod sync;
/// System calls
pub mod syscall;
/// USB input/output
pub mod usb;

pub static mut TSS_PTR: Option<&'static mut TSS> = None;
pub static mut ENV_PTR: Option<&'static mut Environment> = None;

pub fn env() -> &'static Environment {
    unsafe {
        match ENV_PTR {
            Some(&mut ref p) => p,
            None => unreachable!(),
        }
    }
}

/// Pit duration
static PIT_DURATION: Duration = Duration {
    secs: 0,
    nanos: 2250286,
};

/// Idle loop (active while idle)
unsafe fn idle_loop() -> ! {
    loop {
        asm!("cli" : : : : "intel", "volatile");

        let mut halt = true;

        {
            let contexts = ::env().contexts.lock();
            for i in 1..contexts.len() {
                if let Some(context) = contexts.get(i) {
                    if context.interrupted {
                        halt = false;
                        break;
                    }
                }
            }
        }

        if halt {
            asm!("sti" : : : : "intel", "volatile");
            asm!("hlt" : : : : "intel", "volatile");
        } else {
            asm!("sti" : : : : "intel", "volatile");
        }

        context_switch(false);
    }
}

/// Event poll loop
fn poll_loop() -> ! {
    loop {
        env().on_poll();

        unsafe { context_switch(false) };
    }
}

/// Event loop
fn event_loop() -> ! {
    let mut cmd = String::new();
    loop {
        loop {
            let mut console = env().console.lock();
            match env().events.lock().pop_front() {
                Some(event) => {
                    if console.draw {
                        match event.to_option() {
                            EventOption::Key(key_event) => {
                                if key_event.pressed {
                                    match key_event.scancode {
                                        event::K_F2 => {
                                            console.draw = false;
                                        }
                                        event::K_BKSP => if !cmd.is_empty() {
                                            console.write(&[8]);
                                            cmd.pop();
                                        },
                                        _ => match key_event.character {
                                            '\0' => (),
                                            '\n' => {
                                                console.command = Some(cmd.clone());

                                                cmd.clear();
                                                console.write(&[10]);
                                            }
                                            _ => {
                                                cmd.push(key_event.character);
                                                console.write(&[key_event.character as u8]);
                                            }
                                        },
                                    }
                                }
                            }
                            _ => (),
                        }
                    } else {
                        if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 {
                            console.draw = true;
                            console.redraw = true;
                        } else {
                            // TODO: Magical orbital hack
                            unsafe {
                                let reenable = scheduler::start_no_ints();
                                for scheme in env().schemes.iter() {
                                    if (*scheme.get()).scheme() == "orbital" {
                                        (*scheme.get()).event(&event);
                                        break;
                                    }
                                }
                                scheduler::end_no_ints(reenable);
                            }
                        }
                    }
                }
                None => break,
            }
        }

        {
            let mut console = env().console.lock();
            if console.draw && console.redraw {
                console.redraw = false;
                console.display.flip();
            }
        }

        unsafe { context_switch(false) };
    }
}

/// Initialize kernel
unsafe fn init(font_data: usize, tss_data: usize) {
    Page::init();
    memory::cluster_init();
    // Unmap first page to catch null pointer errors (after reading memory map)
    Page::new(0).unmap();

    sync::intex::intex_count = 0;

    display::fonts = font_data;
    TSS_PTR = Some(&mut *(tss_data as *mut TSS));
    ENV_PTR = Some(&mut *Box::into_raw(Environment::new()));

    context_pid = 1;
    context_i = 0;
    context_enabled = false;

    match ENV_PTR {
        Some(ref mut env) => {
            env.contexts.lock().push(Context::root());
            env.console.lock().draw = true;

            debug!("Redox ");
            debug::dd(mem::size_of::<usize>() * 8);
            debug!(" bits");
            debug::dl();

            env.clock_realtime = Rtc::new().time();

            env.schemes.push(UnsafeCell::new(Ps2::new()));
            env.schemes.push(UnsafeCell::new(Serial::new(0x3F8, 0x4)));

            pci_init(env);

            env.schemes.push(UnsafeCell::new(DebugScheme::new()));
            env.schemes.push(UnsafeCell::new(box ContextScheme));
            env.schemes.push(UnsafeCell::new(box MemoryScheme));
            // session.items.push(box RandomScheme);
            // session.items.push(box TimeScheme);

            env.schemes.push(UnsafeCell::new(box EthernetScheme));
            env.schemes.push(UnsafeCell::new(box ArpScheme));
            env.schemes.push(UnsafeCell::new(box IcmpScheme));
            env.schemes.push(UnsafeCell::new(box IpScheme { arp: Vec::new() }));
            // session.items.push(box DisplayScheme);

            Context::spawn("kpoll".to_string(),
            box move || {
                poll_loop();
            });

            Context::spawn("kevent".to_string(),
            box move || {
                event_loop();
            });

            Context::spawn("karp".to_string(),
            box move || {
                ArpScheme::reply_loop();
            });

            Context::spawn("kicmp".to_string(),
            box move || {
                IcmpScheme::reply_loop();
            });

            context_enabled = true;

            if let Some(mut resource) = Url::from_str("file:/schemes/").open() {
                let mut vec: Vec<u8> = Vec::new();
                resource.read_to_end(&mut vec);

                for folder in String::from_utf8_unchecked(vec).lines() {
                    if folder.ends_with('/') {
                        let scheme_item = SchemeItem::from_url(&Url::from_string("file:/schemes/"
                                                                                .to_string() +
                                                                                &folder));

                        let reenable = scheduler::start_no_ints();
                        env.schemes.push(UnsafeCell::new(scheme_item));
                        scheduler::end_no_ints(reenable);
                    }
                }
            }

            Context::spawn("kinit".to_string(),
            box move || {
                let wd_c = "file:/\0";
                do_sys_chdir(wd_c.as_ptr());

                let stdio_c = "debug:\0";
                do_sys_open(stdio_c.as_ptr(), 0);
                do_sys_open(stdio_c.as_ptr(), 0);
                do_sys_open(stdio_c.as_ptr(), 0);

                let path_string = "file:/apps/shell/main.bin";
                let path = Url::from_str(path_string);

                debug!("INIT: Executing {}\n", path_string);
                execute(path, Vec::new());
                debug!("INIT: Failed to execute\n");

                loop {
                    context_switch(false);
                }
            });
        },
        None => unreachable!(),
    }
}

#[cold]
#[inline(never)]
#[no_mangle]
/// Take regs for kernel calls and exceptions
pub extern "cdecl" fn kernel(interrupt: usize, mut regs: &mut Regs) {
    macro_rules! exception_inner {
        ($name:expr) => ({
            unsafe {
                if let Some(context) = Context::current() {
                    debugln!("PID {}: {}", context.pid, context.name);
                }
            }

            debugln!("  INT {:X}: {}", interrupt, $name);
            debugln!("    CS:  {:08X}    IP:  {:08X}    FLG: {:08X}", regs.cs, regs.ip, regs.flags);
            debugln!("    SS:  {:08X}    SP:  {:08X}    BP:  {:08X}", regs.ss, regs.sp, regs.bp);
            debugln!("    AX:  {:08X}    BX:  {:08X}    CX:  {:08X}    DX:  {:08X}", regs.ax, regs.bx, regs.cx, regs.dx);
            debugln!("    DI:  {:08X}    SI:  {:08X}", regs.di, regs.di);

            let cr0: usize;
            let cr2: usize;
            let cr3: usize;
            let cr4: usize;
            unsafe {
                asm!("mov $0, cr0" : "=r"(cr0) : : : "intel", "volatile");
                asm!("mov $0, cr2" : "=r"(cr2) : : : "intel", "volatile");
                asm!("mov $0, cr3" : "=r"(cr3) : : : "intel", "volatile");
                asm!("mov $0, cr4" : "=r"(cr4) : : : "intel", "volatile");
            }
            debugln!("    CR0: {:08X}    CR2: {:08X}    CR3: {:08X}    CR4: {:08X}", cr0, cr2, cr3, cr4);
        })
    };

    macro_rules! exception {
        ($name:expr) => ({
            exception_inner!($name);

            loop {
                unsafe { do_sys_exit(usize::MAX) };
            }
        })
    };

    macro_rules! exception_error {
        ($name:expr) => ({
            let error = regs.ip;
            regs.ip = regs.cs;
            regs.cs = regs.flags;
            regs.flags = regs.sp;
            regs.sp = regs.ss;
            regs.ss = 0;
            //regs.ss = regs.error;

            exception_inner!($name);
            debugln!("    ERR: {:08X}", error);

            loop {
                unsafe { do_sys_exit(usize::MAX) };
            }
        })
    };

    if interrupt >= 0x20 && interrupt < 0x30 {
        if interrupt >= 0x28 {
            unsafe { Pio8::new(0xA0).write(0x20) };
        }

        unsafe { Pio8::new(0x20).write(0x20) };
    }

    match interrupt {
        0x20 => {
            unsafe {
                let reenable = scheduler::start_no_ints();

                match ENV_PTR {
                    Some(ref mut env) => {
                        env.clock_realtime = env.clock_realtime + PIT_DURATION;
                        env.clock_monotonic = env.clock_monotonic + PIT_DURATION;

                        scheduler::end_no_ints(reenable);

                        let switch = if let Some(mut context) = Context::current_mut() {
                            context.slices -= 1;
                            context.slice_total += 1;
                            context.slices == 0
                        } else {
                            false
                        };

                        if switch {
                            context_switch(true);
                        }
                    },
                    None => unreachable!(),
                }
            }
        }
        0x21 => env().on_irq(0x1), // keyboard
        0x23 => env().on_irq(0x3), // serial 2 and 4
        0x24 => env().on_irq(0x4), // serial 1 and 3
        0x25 => env().on_irq(0x5), //parallel 2
        0x26 => env().on_irq(0x6), //floppy
        0x27 => env().on_irq(0x7), //parallel 1 or spurious
        0x28 => env().on_irq(0x8), //RTC
        0x29 => env().on_irq(0x9), //pci
        0x2A => env().on_irq(0xA), //pci
        0x2B => env().on_irq(0xB), //pci
        0x2C => env().on_irq(0xC), //mouse
        0x2D => env().on_irq(0xD), //coprocessor
        0x2E => env().on_irq(0xE), //disk
        0x2F => env().on_irq(0xF), //disk
        0x80 => if !unsafe { syscall_handle(regs) } {
            exception!("Unknown Syscall");
        },
        0xFF => {
            unsafe {
                init(regs.ax, regs.bx);
                idle_loop();
            }
        },
        0x0 => exception!("Divide by zero exception"),
        0x1 => exception!("Debug exception"),
        0x2 => exception!("Non-maskable interrupt"),
        0x3 => exception!("Breakpoint exception"),
        0x4 => exception!("Overflow exception"),
        0x5 => exception!("Bound range exceeded exception"),
        0x6 => exception!("Invalid opcode exception"),
        0x7 => exception!("Device not available exception"),
        0x8 => exception_error!("Double fault"),
        0xA => exception_error!("Invalid TSS exception"),
        0xB => exception_error!("Segment not present exception"),
        0xC => exception_error!("Stack-segment fault"),
        0xD => exception_error!("General protection fault"),
        0xE => exception_error!("Page fault"),
        0x10 => exception!("x87 floating-point exception"),
        0x11 => exception_error!("Alignment check exception"),
        0x12 => exception!("Machine check exception"),
        0x13 => exception!("SIMD floating-point exception"),
        0x14 => exception!("Virtualization exception"),
        0x1E => exception_error!("Security exception"),
        _ => exception!("Unknown Interrupt"),
    }
}
<|endoftext|>


<commit_before><commit_msg>leader-election: rewrite socket code to handle its own socket buffers<commit_after><|endoftext|>


<commit_before><commit_msg>automate benchmark label escaping<commit_after><|endoftext|>


<commit_before><commit_msg>Remove range support, moving to rust-http anyway.<commit_after><|endoftext|>


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

mod foo {
    const b: u8 = 2; //~ NOTE constant defined here
    const d: u8 = 2; //~ NOTE constant defined here
}

use foo::b as c; //~ NOTE constant imported here
use foo::d; //~ NOTE constant imported here

const a: u8 = 2; //~ NOTE constant defined here

fn main() {
    let a = 4; //~ ERROR only irrefutable
               //~^ NOTE there already is a constant in scope
    let c = 4; //~ ERROR only irrefutable
               //~^ NOTE there already is a constant in scope
    let d = 4; //~ ERROR only irrefutable
               //~^ NOTE there already is a constant in scope
}
<|endoftext|>


<commit_before><commit_msg>Use std .to_digit(), refactor a little<commit_after><|endoftext|>


<commit_before><commit_msg>values are dropped in the opposite order they are declared<commit_after><|endoftext|>


<commit_before><commit_msg>Solves the Entropy challenge<commit_after>use std::num::Real;
use std::hashmap::HashMap;
use std::str::StrSlice;

fn shannon_entropy(s: &str) -> f32 {
    let mut map = HashMap::<char, uint>::new();

    for c in s.chars() {
        map.insert_or_update_with(c, 1, |_,v| *v += 1);
    }

    map.iter().fold(0f32, |mut acc, (_, nb)| {
        let p = (*nb as f32)/(s.len() as f32);
        acc -= p * p.log2();
        acc
    })
}

fn main() {
    println!("{:f}", shannon_entropy("1223334444"));
}<|endoftext|>


<commit_before><commit_msg>waypoints<commit_after><|endoftext|>


<commit_before><commit_msg>add missing source file..<commit_after>#![allow(unused)]

use interpreter::ast::*;
use interpreter::tokenizer::*;

use std::collections::HashMap;

impl Expr {
    fn run(&mut self, memory: &mut HashMap<Ident, Expr>) -> Result<Expr, String> {
        match self.node {
            Node::Ident(ref id) => {
                memory
                    .get(id)
                    .ok_or_else(|| {
                        self.debug.to_string() + ", but " + &id.0 + " has not been defined yet."
                    })
                    .map(|val| val.clone())
            }
            Node::Op(ref mut operator) => operator.run(memory),
            Node::Function(ref mut function) => function.run(memory, Vec::new()),
            _ => Ok(self.clone()),
        }
    }
}

impl Operator {
    fn run(&mut self, memory: &mut HashMap<Ident, Expr>) -> Result<Expr, String> {
        match *self {
            Operator::Assign(ref id, ref mut expr) => {
                let val = expr.run(memory)?;
                memory.insert(id.clone(), val);
                Ok(Expr::new(Node::Noop, expr.debug.clone()))
            },
            Operator::Add(ref mut left, ref mut right) => {
                let left_res = left.run(memory)?;
                let right_res = right.run(memory)?;
                match (left_res.node, right_res.node) {
                    (Node::Int(val1), Node::Int(val2)) => {
                        Ok(Expr::new(Node::Int(val1 + val2), DebugInfo::none()))
                    }
                    _ => unimplemented!()
                }
            }
            _ => unimplemented!(),
        }
    }
}

impl Function {
    fn run(&mut self, memory: &mut HashMap<Ident, Expr>, args: Vec<Expr>) -> Result<Expr, String> {
        if self.args.len() != args.len() {
            return Err(format!("Function {} called with an incorrect number of arguments. Expected {} but found {}.", self.name, self.args.len(), args.len()))?
        }
        for (id, val) in self.args.iter().zip(args) {
            memory.insert(id.clone(), val);
        }
        for mut expr in &mut self.body {
            match expr.node {
                Node::Return(_) => return expr.run(memory),
                _ => expr.run(memory)?,
            };
        }

        Ok(Expr::new(Node::Noop, DebugInfo::none()))
    }
}

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

    #[test]
    fn walk_assign() {
        let mut expr = Expr::parse("$someInt = 35").unwrap();
        let mut memory = HashMap::new();
        let result = expr.run(&mut memory);
        println!("{:#?} -> {:#?}\n memory: {:#?}", expr, result, memory);
    }

    #[test]
    fn walk_assign2() {
        let mut expr = Expr::parse("$someInt = 35; $otherInt = $someInt + 4;").unwrap();
        let mut memory = HashMap::new();
        let result = expr.run(&mut memory);
        println!("{:#?}\n memory: {:#?}", result, memory);
    }
}
<|endoftext|>


<commit_before><commit_msg>Support multi-line text<commit_after><|endoftext|>


<commit_before><commit_msg>newton + euler = physics<commit_after>use engine::math::Vector2;

pub struct Motion {
	m: f32,
	s: Vector2,
	v: Vector2,
	a: Vector2,
}

impl Motion {
	pub fn new(m: f32, s: Vector2, v: Vector2, a: Vector2) -> Motion{
		Motion {m:m, s:s, v:v, a:a}
	}

	pub fn update(&mut self, dt: f32) {
		//Euler. should switch to RK
		self.v = self.v + self.a * dt;
		self.s = self.s + self.v * dt + self.a * dt * dt * 0.5;
	}

	pub fn get_s(&self) -> Vector2 {
		self.s
	}

	pub fn set_a(&mut self, a: Vector2) {
		self.a = a;
	}
}<|endoftext|>


<commit_before><commit_msg>Auto merge of #2148 - RalfJung:compare-exchange-weak-failure-rate-test, r=RalfJung<commit_after>// compile-flags: -Zmiri-compare-exchange-weak-failure-rate=0.0
use std::sync::atomic::{AtomicBool, Ordering::*};

// Ensure that compare_exchange_weak never fails.
fn main() {
    let atomic = AtomicBool::new(false);
    let tries = 100;
    for _ in 0..tries {
        let cur = atomic.load(Relaxed);
        // Try (weakly) to flip the flag.
        if atomic.compare_exchange_weak(cur, !cur, Relaxed, Relaxed).is_err() {
            // We failed. Avoid panic machinery as that uses atomics/locks.
            eprintln!("compare_exchange_weak failed");
            std::process::abort();
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>add escape char<commit_after><|endoftext|>


<commit_before><commit_msg>update<commit_after><|endoftext|>


<commit_before><commit_msg>format fixes<commit_after><|endoftext|>


<commit_before><commit_msg>Fix ELF parser<commit_after>// Represents useful attributes from 64-bit elf file

const KERNEL_ELF_IMAGE_POSITION: usize = 0xA000; // must match with plan.md
const MAX_PH_ENTRY_COUNT: usize = 20;
// const MAX_SH_ENTRY_COUNT: usize = 50;

const ELF_MAGIC: u32 = 0x464c457F;
const ELF_BITNESS_64: u8 = 2;
const ELF_LITTLE_ENDIAN: u8 = 1;
const CURRENT_ELF_VERSION: u8 = 1;
const ELF_ARCH_X86_64: u16 = 0x3E;
const ELF_PH_TABLE_ENTRY_SIZE: u16 = 56;

pub struct ELFData {
    pub header: ELFHeader,
    pub ph_table: [Option<ELFProgramHeader>; MAX_PH_ENTRY_COUNT],
    // pub sh_table: [Option<ELFSectionHeader>; MAX_SH_ENTRY_COUNT]
}

bitflags! {
    pub flags ELFPermissionFlags: u32 {
        const EXECUTABLE    = 1 << 0,
        const WRITABLE      = 1 << 1,
        const READABLE      = 1 << 2,
    }
}

#[derive(Clone,Copy)]
#[repr(C,packed)]
pub struct ELFHeader {
    magic: u32,
    bitness: u8,
    endianness: u8,
    elf_version: u8,
    abi_version: u8,
    _undef: u64,
    elf_type: u16,
    instrucion_set: u16,
    elf_version_2: u32,
    program_entry_pos: u64,
    ph_table_position: u64,
    sh_table_position: u64,
    flags: u32,
    header_size: u16,
    ph_table_entry_size: u16,
    ph_table_entry_count: u16,
    sh_table_entry_size: u16,
    sh_table_entry_count: u16,
    sh_table_names: u16
}

#[derive(Clone,Copy)]
#[repr(C,packed)]
pub struct ELFProgramHeader {
    pub header_type: u32,
    pub flags: ELFPermissionFlags,
    pub offset: u64,
    pub virtual_address: u64,
    pub _undef: u64,            // physical address, unused
    pub size_in_file: u64,
    pub size_in_memory: u64,
    pub alignment: u64
}
impl ELFProgramHeader {
    pub fn loadable(&self) -> bool {
        self.header_type == 1
    }
}

// #[derive(Clone,Copy)]
// #[repr(C,packed)]
// pub struct ELFSectionHeader {
//     pub name_index: u32,
//     pub section_type: u32,
//     pub flags: u64,
//     pub address: u64,
//     pub offset: u64,
//     pub size: u64,
//     pub link: u32,
//     pub info: u32,
//     pub align: u64,
//     pub entry_size: u64
// }

#[derive(Debug)]
#[allow(dead_code)]
pub enum ELFParsingError {
    NotElf,
    Not64Bit,
    WrongEndianness,
    WrongVersion,
    WrongAbi,
    WrongInstrcutionSet,
    WrongElfVersion,
    InvalidELF,
    FeatureSupportMissing,
    EmptyHeader,
}

pub unsafe fn parse_elf(ptr: usize) -> Result<ELFData, ELFParsingError> {
    let elf_header: ELFHeader = *(ptr as *const _);

    if elf_header.magic != ELF_MAGIC {
        Err(ELFParsingError::NotElf)
    }
    else if elf_header.bitness != ELF_BITNESS_64 {
        Err(ELFParsingError::Not64Bit)
    }
    else if elf_header.ph_table_entry_size != ELF_PH_TABLE_ENTRY_SIZE {
        Err(ELFParsingError::InvalidELF)
    }
    else if elf_header.endianness != ELF_LITTLE_ENDIAN {
        Err(ELFParsingError::WrongEndianness)
    }
    else if elf_header.elf_version != CURRENT_ELF_VERSION {
        Err(ELFParsingError::WrongVersion)
    }
    else if elf_header.elf_version_2 != CURRENT_ELF_VERSION as u32 {
        Err(ELFParsingError::WrongVersion)
    }

    else if elf_header.instrucion_set != ELF_ARCH_X86_64 {
        Err(ELFParsingError::WrongInstrcutionSet)
    }
    else {
        let mut elf_data = ELFData {
            header: elf_header,
            ph_table: [None; MAX_PH_ENTRY_COUNT],
            // sh_table: [None; MAX_SH_ENTRY_COUNT]
        };

        // get program headers
        let mut ph_table = 0;
        for index in 0..elf_data.header.ph_table_entry_count {
            let ph_ptr = ptr + (elf_data.header.ph_table_position as usize) + (elf_data.header.ph_table_entry_size as usize) * (index as usize);
            let ph: ELFProgramHeader = *(ph_ptr as *const _);

            // rprintln!("> {:x}", ph_ptr-ptr);
            // rprintln!("< {:x}", ph.header_type);

            match ph.header_type as usize {
                0 => {},    // null, ignore
                1 => {      // load, supported
                    elf_data.ph_table[ph_table] = Some(ph);
                    ph_table += 1;
                },
                2 => {      // dynamic, not supported
                    return Err(ELFParsingError::FeatureSupportMissing);
                },
                3 => {      // interp, not supported
                    return Err(ELFParsingError::FeatureSupportMissing);
                },
                4 => {},    // notes
                0x6474e551 => { // PT_GNU_STACK (not sure why, but it appears there so I will just let it be)

                }
                _ => {      // unknown, not supported
                    return Err(ELFParsingError::FeatureSupportMissing);
                }
            }
        }
        // // get section headers
        // // no checking is done here, this is just for future use
        // let mut sh_table = 0;
        // for index in 0..elf_data.header.sh_table_entry_count {
        //     let sh_ptr = ptr + (elf_data.header.sh_table_position as usize) + (elf_data.header.sh_table_entry_size as usize) * (index as usize);
        //     let sh: ELFSectionHeader = *(sh_ptr as *const _);
        //
        //     match sh.section_type as usize {
        //         0 => {},    // null, ignore
        //         1 => {      // PROGBITS
        //             elf_data.sh_table[sh_table] = Some(sh);
        //             sh_table += 1;
        //         },
        //         8 => {      // NOBITS (.bss)
        //             elf_data.sh_table[sh_table] = Some(sh);
        //             sh_table += 1;
        //         }
        //         _ => {}     // unknown
        //     }
        // }

        Ok(elf_data)
    }
}

pub unsafe fn parse_kernel_elf() -> ELFData {
    match parse_elf(KERNEL_ELF_IMAGE_POSITION) {
        Ok(header) => header,
        Err(error) => panic!("Could not receive kernel image data: {:?}", error)
    }
}
<|endoftext|>


<commit_before><commit_msg>utils: Add tests for the `align_blocks` helper in utils.<commit_after>extern crate clippy_lints;

use clippy_lints::utils::align_snippets;

#[test]
fn test_align_snippets_single_line() {
    assert_eq!("", align_snippets(&[""]));
    assert_eq!("...", align_snippets(&["..."]));
}

#[test]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn test_align_snippets_multiline() {
    let expected = "\
if condition() {
    do_something();
    do_another_thing();
    yet_another_thing();
    {
        and_then_an_indented_block();
    }
        and_then_something_the_user_indented();"; // expected

    let input = &[
"\
if condition() {
    do_something();",
"       do_another_thing();",
"            yet_another_thing();
            {
                and_then_an_indented_block();
            }
                and_then_something_the_user_indented();",
    ]; // input

    let got = align_snippets(input);
    assert_eq!(expected, got);

}

#[test]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn test_align_snippets_multiline_with_empty_lines() {
    let expected = "\
if condition() {
    do_something();
    do_another_thing();
    yet_another_thing();
    {

        and_then_an_indented_block();
    }

        and_then_something_the_user_indented();"; // expected

    let input = &[
"\
if condition() {
    do_something();",
"       do_another_thing();",
"            yet_another_thing();
            {

                and_then_an_indented_block();
            }

                and_then_something_the_user_indented();",
    ]; // input

    let got = align_snippets(input);
    println!("Input: {}\nExpected: {}\nGot: {}", input.join("\n"), &expected, &got);
    assert_eq!(expected, got);
}

<|endoftext|>


<commit_before><commit_msg>TCP reactor benchmarks<commit_after>#![feature(test)]

extern crate futures;
extern crate tokio_core;

#[macro_use]
extern crate tokio_io;

pub extern crate test;

mod prelude {
    pub use futures::*;
    pub use tokio_core::reactor::Core;
    pub use tokio_core::net::{TcpListener, TcpStream};
    pub use tokio_io::io::read_to_end;

    pub use test::{self, Bencher};
    pub use std::thread;
    pub use std::time::Duration;
    pub use std::io::{self, Read, Write};
}

mod connect_churn {
    use ::prelude::*;

    const NUM: usize = 300;
    const CONCURRENT: usize = 8;

    #[bench]
    fn one_thread(b: &mut Bencher) {
        let addr = "127.0.0.1:0".parse().unwrap();
        let mut core = Core::new().unwrap();
        let handle = core.handle();
        let listener = TcpListener::bind(&addr, &handle).unwrap();
        let addr = listener.local_addr().unwrap();

        // Spawn a single task that accepts & drops connections
        handle.spawn(
            listener.incoming()
                .map_err(|e| panic!("server err: {:?}", e))
                .for_each(|_| Ok(())));

        b.iter(move || {
            let connects = stream::iter((0..NUM).map(|_| {
                Ok(TcpStream::connect(&addr, &handle)
                    .and_then(|sock| {
                        sock.set_linger(Some(Duration::from_secs(0))).unwrap();
                        read_to_end(sock, vec![])
                    }))
            }));

            core.run(
                connects.buffer_unordered(CONCURRENT)
                    .map_err(|e| panic!("client err: {:?}", e))
                    .for_each(|_| Ok(()))).unwrap();
        });
    }

    fn n_workers(n: usize, b: &mut Bencher) {
        let (shutdown_tx, shutdown_rx) = sync::oneshot::channel();
        let (remote_tx, remote_rx) = ::std::sync::mpsc::channel();

        // Spawn reactor thread
        thread::spawn(move || {
            // Create the core
            let mut core = Core::new().unwrap();

            // Reactor handles
            let handle = core.handle();
            let remote = handle.remote().clone();

            // Bind the TCP listener
            let listener = TcpListener::bind(
                &"127.0.0.1:0".parse().unwrap(), &handle).unwrap();

            // Get the address being listened on.
            let addr = listener.local_addr().unwrap();

            // Send the remote & address back to the main thread
            remote_tx.send((remote, addr)).unwrap();

            // Spawn a single task that accepts & drops connections
            handle.spawn(
                listener.incoming()
                    .map_err(|e| panic!("server err: {:?}", e))
                    .for_each(|_| Ok(())));

            // Run the reactor
            core.run(shutdown_rx).unwrap();
        });

        // Get the remote info
        let (remote, addr) = remote_rx.recv().unwrap();

        b.iter(move || {
            use std::sync::{Barrier, Arc};

            // Create a barrier to coordinate threads
            let barrier = Arc::new(Barrier::new(n + 1));

            // Spawn worker threads
            let threads: Vec<_> = (0..n).map(|_| {
                let barrier = barrier.clone();
                let remote = remote.clone();
                let addr = addr.clone();

                thread::spawn(move || {
                    let connects = stream::iter((0..(NUM / n)).map(|_| {
                        // TODO: Once `Handle` is `Send / Sync`, update this

                        let (socket_tx, socket_rx) = sync::oneshot::channel();

                        remote.spawn(move |handle| {
                            TcpStream::connect(&addr, &handle)
                                .map_err(|e| panic!("connect err: {:?}", e))
                                .then(|res| socket_tx.send(res))
                                .map_err(|_| ())
                        });

                        Ok(socket_rx
                            .then(|res| res.unwrap())
                            .and_then(|sock| {
                                sock.set_linger(Some(Duration::from_secs(0))).unwrap();
                                read_to_end(sock, vec![])
                            }))
                    }));

                    barrier.wait();

                    connects.buffer_unordered(CONCURRENT)
                        .map_err(|e| panic!("client err: {:?}", e))
                        .for_each(|_| Ok(())).wait().unwrap();
                })
            }).collect();

            barrier.wait();

            for th in threads {
                th.join().unwrap();
            }
        });

        // Shutdown the reactor
        shutdown_tx.send(()).unwrap();
    }

    #[bench]
    fn two_threads(b: &mut Bencher) {
        n_workers(1, b);
    }

    #[bench]
    fn multi_threads(b: &mut Bencher) {
        n_workers(4, b);
    }
}

mod transfer {
    use ::prelude::*;
    use std::{cmp, mem};

    const MB: usize = 3 * 1024 * 1024;

    struct Drain {
        sock: TcpStream,
        chunk: usize,
    }

    impl Future for Drain {
        type Item = ();
        type Error = io::Error;

        fn poll(&mut self) -> Poll<(), io::Error> {
            let mut buf: [u8; 1024] = unsafe { mem::uninitialized() };

            loop {
                match try_nb!(self.sock.read(&mut buf[..self.chunk])) {
                    0 => return Ok(Async::Ready(())),
                    _ => {}
                }
            }
        }
    }

    struct Transfer {
        sock: TcpStream,
        rem: usize,
        chunk: usize,
    }

    impl Future for Transfer {
        type Item = ();
        type Error = io::Error;

        fn poll(&mut self) -> Poll<(), io::Error> {
            while self.rem > 0 {
                let len = cmp::min(self.rem, self.chunk);
                let buf = &DATA[..len];

                let n = try_nb!(self.sock.write(&buf));
                self.rem -= n;
            }

            Ok(Async::Ready(()))
        }
    }

    static DATA: [u8; 1024] = [0; 1024];

    fn one_thread(b: &mut Bencher, read_size: usize, write_size: usize) {
        let addr = "127.0.0.1:0".parse().unwrap();
        let mut core = Core::new().unwrap();
        let handle = core.handle();
        let listener = TcpListener::bind(&addr, &handle).unwrap();
        let addr = listener.local_addr().unwrap();

        let h2 = handle.clone();

        // Spawn a single task that accepts & drops connections
        handle.spawn(
            listener.incoming()
                .map_err(|e| panic!("server err: {:?}", e))
                .for_each(move |(sock, _)| {
                    sock.set_linger(Some(Duration::from_secs(0))).unwrap();
                    let drain = Drain {
                        sock: sock,
                        chunk: read_size,
                    };

                    h2.spawn(drain.map_err(|e| panic!("server error: {:?}", e)));

                    Ok(())
                }));

        b.iter(move || {
            let client = TcpStream::connect(&addr, &handle)
                .and_then(|sock| {
                    Transfer {
                        sock: sock,
                        rem: MB,
                        chunk: write_size,
                    }
                });

            core.run(
                client.map_err(|e| panic!("client err: {:?}", e))
                ).unwrap();
        });
    }

    fn cross_thread(b: &mut Bencher, read_size: usize, write_size: usize) {
        let (shutdown_tx, shutdown_rx) = sync::oneshot::channel();
        let (remote_tx, remote_rx) = ::std::sync::mpsc::channel();

        // Spawn reactor thread
        thread::spawn(move || {
            // Create the core
            let mut core = Core::new().unwrap();

            // Reactor handles
            let handle = core.handle();
            let remote = handle.remote().clone();

            remote_tx.send(remote).unwrap();
            core.run(shutdown_rx).unwrap();
        });

        let remote = remote_rx.recv().unwrap();

        b.iter(move || {
            let (server_tx, server_rx) = sync::oneshot::channel();
            let (client_tx, client_rx) = sync::oneshot::channel();

            remote.spawn(|handle| {
                let sock = TcpListener::bind(&"127.0.0.1:0".parse().unwrap(), &handle).unwrap();
                server_tx.send(sock).unwrap();
                Ok(())
            });

            let remote2 = remote.clone();

            server_rx.and_then(move |server| {
                let addr = server.local_addr().unwrap();

                remote2.spawn(move |handle| {
                    let fut = TcpStream::connect(&addr, &handle);
                    client_tx.send(fut).ok().unwrap();
                    Ok(())
                });

                let client = client_rx
                    .then(|res| res.unwrap())
                    .and_then(move |sock| {
                        Transfer {
                            sock: sock,
                            rem: MB,
                            chunk: write_size,
                        }
                    });

                let server = server.incoming().into_future()
                    .map_err(|(e, _)| e)
                    .and_then(move |(sock, _)| {
                        let sock = sock.unwrap().0;
                        sock.set_linger(Some(Duration::from_secs(0))).unwrap();

                        Drain {
                            sock: sock,
                            chunk: read_size,
                        }
                    });

                client
                    .join(server)
                    .then(|res| {
                        let _ = res.unwrap();
                        Ok(())
                    })
            }).wait().unwrap();
        });

        // Shutdown the reactor
        shutdown_tx.send(()).unwrap();
    }

    mod small_chunks {
        use ::prelude::*;

        #[bench]
        fn one_thread(b: &mut Bencher) {
            super::one_thread(b, 32, 32);
        }

        #[bench]
        fn cross_thread(b: &mut Bencher) {
            super::cross_thread(b, 32, 32);
        }
    }

    mod big_chunks {
        use ::prelude::*;

        #[bench]
        fn one_thread(b: &mut Bencher) {
            super::one_thread(b, 1_024, 1_024);
        }

        #[bench]
        fn cross_thread(b: &mut Bencher) {
            super::cross_thread(b, 1_024, 1_024);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Print Runtime errors to stderr<commit_after><|endoftext|>


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

// compile-flags: --test
extern crate test;

#[bench]
fn bench_explicit_return_type(_: &mut ::test::Bencher) -> () {}

#[test]
fn test_explicit_return_type() -> () {}

<|endoftext|>


<commit_before><commit_msg>Create 2_more_vec_functions.rs<commit_after>enum Number{
    Nothing,
    Number(i32)
}

/* Capable of handling empty vectors as well */
fn vec_min(vec: Vec<i32>) -> Number{

    let mut min = Number::Nothing;

    for i in vec{
        match min{
            Number::Nothing => min = Number::Number(i),
            Number::Number(num) => if i < num{
                                        min = Number::Number(i)
                                    }
        }
    }
    min
}

fn vec_sum(vec: Vec<i32>) -> Number{

    let mut sum = Number::Nothing;

    for i in vec{
        match sum{
            Number::Nothing => sum = Number::Number(i),
            Number::Number(num) => sum = Number::Number(num + i)
        }
    }
    sum
}

impl Number{
    fn print(self){
        match self{
            Number::Nothing => println!("Nothing to print"),
            Number::Number(num) => println!("Number = {}", num)
        }
    }
}

fn vec_print(vec: Vec<i32>) -> (){
    for i in vec{
        println!("Num = {}", i);
    }
}

fn main() {
    println!("Hello, world!");

    let vec = vec![1,4,6,3,6,2,-1,0];
    //let vec = vec![];
    let min = vec_min(vec);

    min.print();

/*  Leads to an error. 'vec' is already moved into vec_min(). Now vec_min() will
    own it. 'vec' will be destroyed at the end of vec_min()

    let sum = vec_sum(vec);
*/

    let vec2 = vec![1,4,6,3,6,2,-1,0];
    let sum = vec_sum(vec2);
    sum.print();

    let vec3 = vec![1,4,6,3,6,2,-1,0];
    vec_print(vec3);
}
<|endoftext|>


<commit_before>use std::convert::Into;
use std::str::FromStr;

use chrono::naive::datetime::NaiveDateTime;
use chrono::naive::time::NaiveTime;
use chrono::naive::date::NaiveDate;
use chrono::Datelike;
use chrono::Timelike;
use regex::Regex;

use libimagstore::storeid::StoreId;
use libimagstore::storeid::IntoStoreId;

use module_path::ModuleEntryPath;

#[derive(Debug, Clone)]
pub struct DiaryId {
    name: String,
    year: i32,
    month: u32,
    day: u32,
    hour: u32,
    minute: u32,
}

impl DiaryId {

    pub fn new(name: String, y: i32, m: u32, d: u32, h: u32, min: u32) -> DiaryId {
        DiaryId {
            name: name,
            year: y,
            month: m,
            day: d,
            hour: h,
            minute: min,
        }
    }

    pub fn from_datetime<DT: Datelike + Timelike>(diary_name: String, dt: DT) -> DiaryId {
        DiaryId::new(diary_name, dt.year(), dt.month(), dt.day(), dt.hour(), dt.minute())
    }

    pub fn diary_name(&self) -> &String {
        &self.name
    }

    pub fn year(&self) -> i32 {
        self.year
    }

    pub fn month(&self) -> u32 {
        self.month
    }

    pub fn day(&self) -> u32 {
        self.day
    }

    pub fn hour(&self) -> u32 {
        self.hour
    }

    pub fn minute(&self) -> u32 {
        self.minute
    }

}

impl IntoStoreId for DiaryId {

    fn into_storeid(self) -> StoreId {
        let s : String = self.into();
        ModuleEntryPath::new(s).into_storeid()
    }

}

impl Into<String> for DiaryId {

    fn into(self) -> String {
        format!("{}/{}/{}-{}-{}:{}",
                self.name, self.year, self.month, self.day, self.hour, self.minute)
    }

}

impl Into<NaiveDateTime> for DiaryId {

    fn into(self) -> NaiveDateTime {
        let d = NaiveDate::from_ymd(self.year, self.month, self.day);
        let t = NaiveTime::from_hms(self.hour, self.minute, 0);
        NaiveDateTime::new(d, t)
    }

}

pub trait FromStoreId : Sized {

    fn from_storeid(&StoreId) -> Option<Self>;

}

impl FromStoreId for DiaryId {

    fn from_storeid(s: &StoreId) -> Option<DiaryId> {
        lazy_static! {
            static ref RE: Regex = Regex::new(r"(?x)
            (.*)
            /(?P<name>(.*))
            /(?P<year>\d{4})
            /(?P<month>\d{2})
            -(?P<day>\d{2})
            -(?P<hour>\d{2})
            :(?P<minute>\d{2})
            "
            ).unwrap();
        }

        s.to_str()
            .map(|s| { debug!("StoreId = {:?}", s); s })
            .and_then(|s| RE.captures(s))
            .and_then(|caps| {
                let name   = caps.at(0);
                let year   = caps.at(1);
                let month  = caps.at(2);
                let day    = caps.at(3);
                let hour   = caps.at(4);
                let minute = caps.at(5);

                debug!("some? name   = {:?}", name.is_some());
                debug!("some? year   = {:?}", year.is_some());
                debug!("some? month  = {:?}", month.is_some());
                debug!("some? day    = {:?}", day.is_some());
                debug!("some? hour   = {:?}", hour.is_some());
                debug!("some? minute = {:?}", minute.is_some());

                if [name, year, month, day, hour, minute].iter().all(|x| x.is_some()) {
                    let year = {
                        match i32::from_str(year.unwrap()) {
                            Ok(x) => x,
                            Err(_) => return None,
                        }
                    };

                    let month = {
                        match u32::from_str(month.unwrap()) {
                            Ok(x) => x,
                            Err(_) => return None,
                        }
                    };

                    let day = {
                        match u32::from_str(day.unwrap()) {
                            Ok(x) => x,
                            Err(_) => return None,
                        }
                    };

                    let hour = {
                        match u32::from_str(hour.unwrap()) {
                            Ok(x) => x,
                            Err(_) => return None,
                        }
                    };

                    let minute = {
                        match u32::from_str(minute.unwrap()) {
                            Ok(x) => x,
                            Err(_) => return None,
                        }
                    };

                    Some(DiaryId {
                        name   : String::from(name.unwrap()),
                        year   : year,
                        month  : month,
                        day    : day,
                        hour   : hour,
                        minute : minute,
                    })
                } else {
                    None
                }
            })
    }

}

<commit_msg>Reimplement FromStoreId::from_storeid() for DiaryId<commit_after>use std::convert::Into;

use chrono::naive::datetime::NaiveDateTime;
use chrono::naive::time::NaiveTime;
use chrono::naive::date::NaiveDate;
use chrono::Datelike;
use chrono::Timelike;

use libimagstore::storeid::StoreId;
use libimagstore::storeid::IntoStoreId;

use module_path::ModuleEntryPath;

#[derive(Debug, Clone)]
pub struct DiaryId {
    name: String,
    year: i32,
    month: u32,
    day: u32,
    hour: u32,
    minute: u32,
}

impl DiaryId {

    pub fn new(name: String, y: i32, m: u32, d: u32, h: u32, min: u32) -> DiaryId {
        DiaryId {
            name: name,
            year: y,
            month: m,
            day: d,
            hour: h,
            minute: min,
        }
    }

    pub fn from_datetime<DT: Datelike + Timelike>(diary_name: String, dt: DT) -> DiaryId {
        DiaryId::new(diary_name, dt.year(), dt.month(), dt.day(), dt.hour(), dt.minute())
    }

    pub fn diary_name(&self) -> &String {
        &self.name
    }

    pub fn year(&self) -> i32 {
        self.year
    }

    pub fn month(&self) -> u32 {
        self.month
    }

    pub fn day(&self) -> u32 {
        self.day
    }

    pub fn hour(&self) -> u32 {
        self.hour
    }

    pub fn minute(&self) -> u32 {
        self.minute
    }

}

impl IntoStoreId for DiaryId {

    fn into_storeid(self) -> StoreId {
        let s : String = self.into();
        ModuleEntryPath::new(s).into_storeid()
    }

}

impl Into<String> for DiaryId {

    fn into(self) -> String {
        format!("{}/{}/{}/{}/{}:{}",
                self.name, self.year, self.month, self.day, self.hour, self.minute)
    }

}

impl Into<NaiveDateTime> for DiaryId {

    fn into(self) -> NaiveDateTime {
        let d = NaiveDate::from_ymd(self.year, self.month, self.day);
        let t = NaiveTime::from_hms(self.hour, self.minute, 0);
        NaiveDateTime::new(d, t)
    }

}

pub trait FromStoreId : Sized {

    fn from_storeid(&StoreId) -> Option<Self>;

}

use std::path::Component;

fn component_to_str<'a>(com: Component<'a>) -> Option<&'a str> {
    match com {
        Component::Normal(s) => Some(s),
        _ => None
    }.and_then(|s| s.to_str())
}

impl FromStoreId for DiaryId {

    fn from_storeid(s: &StoreId) -> Option<DiaryId> {
        use std::str::FromStr;

        let mut cmps   = s.components().rev();
        let (hour, minute) = match cmps.next().and_then(component_to_str)
            .and_then(|time| {
                let mut time = time.split(":");
                let hour     = time.next().and_then(|s| FromStr::from_str(s).ok());
                let minute   = time.next()
                    .and_then(|s| s.split("~").next())
                    .and_then(|s| FromStr::from_str(s).ok());

                debug!("Hour   = {:?}", hour);
                debug!("Minute = {:?}", minute);

                match (hour, minute) {
                    (Some(h), Some(m)) => Some((h, m)),
                    _ => None,
                }
            })
        {
            Some(s) => s,
            None => return None,
        };

        let day   :Option<u32> = cmps.next().and_then(component_to_str).and_then(|s| FromStr::from_str(s).ok());
        let month :Option<u32> = cmps.next().and_then(component_to_str).and_then(|s| FromStr::from_str(s).ok());
        let year  :Option<i32> = cmps.next().and_then(component_to_str).and_then(|s| FromStr::from_str(s).ok());
        let name       = cmps.next().and_then(component_to_str).map(String::from);

        debug!("Day   = {:?}", day);
        debug!("Month = {:?}", month);
        debug!("Year  = {:?}", year);
        debug!("Name  = {:?}", name);

        let day    = if day.is_none()    { return None; } else { day.unwrap() };
        let month  = if month.is_none()  { return None; } else { month.unwrap() };
        let year   = if year.is_none()   { return None; } else { year.unwrap() };
        let name   = if name.is_none()   { return None; } else { name.unwrap() };

        Some(DiaryId::new(name, year, month, day, hour, minute))
    }

}

<|endoftext|>


<commit_before>use std::path::PathBuf;
use std::path::Path;
use std::borrow::Borrow;
use std::ops::Deref;

use semver::Version;
use std::fmt::{Display, Debug, Formatter};
use std::fmt::Error as FmtError;
use std::result::Result as RResult;

use error::StoreErrorKind as SEK;
use store::Result;
use store::Store;

/// The Index into the Store
#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
pub struct StoreId {
    store_location: PathBuf,
    id: PathBuf,
}

impl StoreId {

    pub fn storified(self, store: &Store) -> StoreId {
        if self.starts_with(store.path()) {
            debug!("Not storifying {:?}, because it is already.", self);
            self
        } else {
            debug!("Create new store id out of: {:?} and {:?}", store.path(), self.id);

            let new_id = StoreId { store_location: store.path().clone(), self.id };

            debug!("Created: '{:?}'", new_id);
            new_id
        }
    }

    pub fn exists(&self) -> bool {
        let pb : PathBuf = self.clone().into();
        pb.exists()
    }

    pub fn is_file(&self) -> bool {
        true
    }

    pub fn is_dir(&self) -> bool {
        false
    }

}

impl Into<PathBuf> for StoreId {

    fn into(self) -> PathBuf {
        let mut base = self.store_location;
        base.push(self.id);
        base
    }

}

impl Display for StoreId {

    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> {
        match self.id.to_str() {
            Some(s) => write!(fmt, "{}", s),
            None    => write!(fmt, "{}", self.id.to_string_lossy()),
        }
    }

}

impl From<PathBuf> for StoreId {

    fn from(pb: PathBuf) -> StoreId {
        StoreId(pb)
    }

}

impl From<String> for StoreId {

    fn from(string: String) -> StoreId {
        StoreId(string.into())
    }

}

impl AsRef<Path> for StoreId {

    fn as_ref(&self) -> &Path {
        self.id.as_ref()
    }

}

impl Borrow<Path> for StoreId {

    fn borrow(&self) -> &Path {
        self.0.borrow()
    }

}

/// This Trait allows you to convert various representations to a single one
/// suitable for usage in the Store
pub trait IntoStoreId {
    fn into_storeid(self) -> StoreId;
}

impl IntoStoreId for PathBuf {
    fn into_storeid(self) -> StoreId {
        StoreId(self)
    }
}

impl IntoStoreId for StoreId {
    fn into_storeid(self) -> StoreId {
        self
    }
}

pub fn build_entry_path(store: &Store, path_elem: &str) -> Result<PathBuf> {
    debug!("Checking path element for version");
    if path_elem.split('~').last().map_or(false, |v| Version::parse(v).is_err()) {
        debug!("Version cannot be parsed from {:?}", path_elem);
        debug!("Path does not contain version!");
        return Err(SEK::StorePathLacksVersion.into());
    }
    debug!("Version checking succeeded");

    debug!("Building path from {:?}", path_elem);
    let mut path = store.path().clone();

    if path_elem.starts_with('/') {
        path.push(&path_elem[1..]);
    } else {
        path.push(path_elem);
    }

    Ok(path)
}

#[macro_export]
macro_rules! module_entry_path_mod {
    ($name:expr, $version:expr) => (
        #[deny(missing_docs,
                missing_copy_implementations,
                trivial_casts, trivial_numeric_casts,
                unsafe_code,
                unstable_features,
                unused_import_braces, unused_qualifications,
                unused_imports)]
        /// A helper module to create valid module entry paths
        pub mod module_path {
            use semver::Version;
            use std::convert::AsRef;
            use std::path::Path;
            use std::path::PathBuf;

            use $crate::storeid::StoreId;

            /// A Struct giving you the ability to choose store entries assigned
            /// to it.
            ///
            /// It is created through a call to `new`.
            pub struct ModuleEntryPath(PathBuf);

            impl ModuleEntryPath {
                /// Path has to be a valid UTF-8 string or this will panic!
                pub fn new<P: AsRef<Path>>(pa: P) -> ModuleEntryPath {
                    let mut path = PathBuf::new();
                    path.push(format!("{}", $name));
                    path.push(pa.as_ref().clone());
                    let version = Version::parse($version).unwrap();
                    let name = pa.as_ref().file_name().unwrap()
                        .to_str().unwrap();
                    path.set_file_name(format!("{}~{}",
                                               name,
                                               version));
                    ModuleEntryPath(path)
                }
            }

            impl $crate::storeid::IntoStoreId for ModuleEntryPath {
                fn into_storeid(self) -> $crate::storeid::StoreId {
                    StoreId::from(self.0)
                }
            }
        }
    )
}

pub struct StoreIdIterator {
    iter: Box<Iterator<Item = StoreId>>,
}

impl Debug for StoreIdIterator {

    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> {
        write!(fmt, "StoreIdIterator")
    }

}

impl StoreIdIterator {

    pub fn new(iter: Box<Iterator<Item = StoreId>>) -> StoreIdIterator {
        StoreIdIterator {
            iter: iter,
        }
    }

}

impl Iterator for StoreIdIterator {
    type Item = StoreId;

    fn next(&mut self) -> Option<StoreId> {
        self.iter.next()
    }

}

#[cfg(test)]
mod test {

    use storeid::IntoStoreId;

    module_entry_path_mod!("test", "0.2.0-alpha+leet1337");

    #[test]
    fn correct_path() {
        let p = module_path::ModuleEntryPath::new("test");

        assert_eq!(p.into_storeid().to_str().unwrap(), "test/test~0.2.0-alpha+leet1337");
    }

}
<commit_msg>Rewrite Borrow<Path> for StoreId<commit_after>use std::path::PathBuf;
use std::path::Path;
use std::borrow::Borrow;
use std::ops::Deref;

use semver::Version;
use std::fmt::{Display, Debug, Formatter};
use std::fmt::Error as FmtError;
use std::result::Result as RResult;

use error::StoreErrorKind as SEK;
use store::Result;
use store::Store;

/// The Index into the Store
#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
pub struct StoreId {
    store_location: PathBuf,
    id: PathBuf,
}

impl StoreId {

    pub fn storified(self, store: &Store) -> StoreId {
        if self.starts_with(store.path()) {
            debug!("Not storifying {:?}, because it is already.", self);
            self
        } else {
            debug!("Create new store id out of: {:?} and {:?}", store.path(), self.id);

            let new_id = StoreId { store_location: store.path().clone(), self.id };

            debug!("Created: '{:?}'", new_id);
            new_id
        }
    }

    pub fn exists(&self) -> bool {
        let pb : PathBuf = self.clone().into();
        pb.exists()
    }

    pub fn is_file(&self) -> bool {
        true
    }

    pub fn is_dir(&self) -> bool {
        false
    }

}

impl Into<PathBuf> for StoreId {

    fn into(self) -> PathBuf {
        let mut base = self.store_location;
        base.push(self.id);
        base
    }

}

impl Display for StoreId {

    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> {
        match self.id.to_str() {
            Some(s) => write!(fmt, "{}", s),
            None    => write!(fmt, "{}", self.id.to_string_lossy()),
        }
    }

}

impl From<PathBuf> for StoreId {

    fn from(pb: PathBuf) -> StoreId {
        StoreId(pb)
    }

}

impl From<String> for StoreId {

    fn from(string: String) -> StoreId {
        StoreId(string.into())
    }

}

impl AsRef<Path> for StoreId {

    fn as_ref(&self) -> &Path {
        self.id.as_ref()
    }

}

impl Borrow<Path> for StoreId {

    fn borrow(&self) -> &Path {
        self.id.borrow()
    }

}

/// This Trait allows you to convert various representations to a single one
/// suitable for usage in the Store
pub trait IntoStoreId {
    fn into_storeid(self) -> StoreId;
}

impl IntoStoreId for PathBuf {
    fn into_storeid(self) -> StoreId {
        StoreId(self)
    }
}

impl IntoStoreId for StoreId {
    fn into_storeid(self) -> StoreId {
        self
    }
}

pub fn build_entry_path(store: &Store, path_elem: &str) -> Result<PathBuf> {
    debug!("Checking path element for version");
    if path_elem.split('~').last().map_or(false, |v| Version::parse(v).is_err()) {
        debug!("Version cannot be parsed from {:?}", path_elem);
        debug!("Path does not contain version!");
        return Err(SEK::StorePathLacksVersion.into());
    }
    debug!("Version checking succeeded");

    debug!("Building path from {:?}", path_elem);
    let mut path = store.path().clone();

    if path_elem.starts_with('/') {
        path.push(&path_elem[1..]);
    } else {
        path.push(path_elem);
    }

    Ok(path)
}

#[macro_export]
macro_rules! module_entry_path_mod {
    ($name:expr, $version:expr) => (
        #[deny(missing_docs,
                missing_copy_implementations,
                trivial_casts, trivial_numeric_casts,
                unsafe_code,
                unstable_features,
                unused_import_braces, unused_qualifications,
                unused_imports)]
        /// A helper module to create valid module entry paths
        pub mod module_path {
            use semver::Version;
            use std::convert::AsRef;
            use std::path::Path;
            use std::path::PathBuf;

            use $crate::storeid::StoreId;

            /// A Struct giving you the ability to choose store entries assigned
            /// to it.
            ///
            /// It is created through a call to `new`.
            pub struct ModuleEntryPath(PathBuf);

            impl ModuleEntryPath {
                /// Path has to be a valid UTF-8 string or this will panic!
                pub fn new<P: AsRef<Path>>(pa: P) -> ModuleEntryPath {
                    let mut path = PathBuf::new();
                    path.push(format!("{}", $name));
                    path.push(pa.as_ref().clone());
                    let version = Version::parse($version).unwrap();
                    let name = pa.as_ref().file_name().unwrap()
                        .to_str().unwrap();
                    path.set_file_name(format!("{}~{}",
                                               name,
                                               version));
                    ModuleEntryPath(path)
                }
            }

            impl $crate::storeid::IntoStoreId for ModuleEntryPath {
                fn into_storeid(self) -> $crate::storeid::StoreId {
                    StoreId::from(self.0)
                }
            }
        }
    )
}

pub struct StoreIdIterator {
    iter: Box<Iterator<Item = StoreId>>,
}

impl Debug for StoreIdIterator {

    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> {
        write!(fmt, "StoreIdIterator")
    }

}

impl StoreIdIterator {

    pub fn new(iter: Box<Iterator<Item = StoreId>>) -> StoreIdIterator {
        StoreIdIterator {
            iter: iter,
        }
    }

}

impl Iterator for StoreIdIterator {
    type Item = StoreId;

    fn next(&mut self) -> Option<StoreId> {
        self.iter.next()
    }

}

#[cfg(test)]
mod test {

    use storeid::IntoStoreId;

    module_entry_path_mod!("test", "0.2.0-alpha+leet1337");

    #[test]
    fn correct_path() {
        let p = module_path::ModuleEntryPath::new("test");

        assert_eq!(p.into_storeid().to_str().unwrap(), "test/test~0.2.0-alpha+leet1337");
    }

}
<|endoftext|>


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

//! A typed high-level graphics pipeline interface.
//!
//! # Overview
//! A `PipelineState` holds all information needed to manage a graphics pipeline. It contain
//! information about the shaders used, and on how to bind variables to these shaders. A
//! `PipelineState` manifests itself in the form of a Pipeline State Object, or PSO in short.
//!
//! A Pipeline State Object exists out of different components. Every component represents
//! a resource handle: a shader input or output/target. The types of these components can be found
//! in this module's submodules, grouped by category.
//!
//! Before all, a Pipeline State Object must be defined. This is done using the `gfx_pipeline`
//! macro. This macro creates three different structures:
//!
//! - The `Init` structure contains the location of every PSO component. During shader linking,
//!   this is used to construct the `Meta` structure.
//! - The `Meta` structure contains the layout of every PSO. Using the `Meta` structure, the right
//!   data is mapped to the right components.
//! - The `Data` structure contains the data of all components, to be sent to the GPU.
//!
//! # Construction and Handling
//! A Pipeline State Object is constructed by a factory, from its `Init` structure, a `Rasterizer`,
//! a primitive type and a shader program.
//!
//! After construction an `Encoder` can use the PSO along with a `Data` structure matching that
//! PSO to process the shader pipeline, for instance, using the `draw` method.

pub mod buffer;
pub mod resource;
pub mod target;
pub mod bundle;

use std::default::Default;
use gfx_core as d;
pub use gfx_core::pso::{Descriptor};

/// A complete set of raw data that needs to be specified at run-time
/// whenever we draw something with a PSO. This is what "data" struct
/// gets transformed into when we call `encoder.draw(...)` with it.
/// It doesn't have any typing information, since PSO knows what
/// format and layout to expect from each resource.
#[allow(missing_docs)]
#[derive(Debug)]
pub struct RawDataSet<R: d::Resources>{
    pub vertex_buffers: d::pso::VertexBufferSet<R>,
    pub constant_buffers: Vec<d::pso::ConstantBufferParam<R>>,
    pub global_constants: Vec<(d::shade::Location, d::shade::UniformValue)>,
    pub resource_views: Vec<d::pso::ResourceViewParam<R>>,
    pub unordered_views: Vec<d::pso::UnorderedViewParam<R>>,
    pub samplers: Vec<d::pso::SamplerParam<R>>,
    pub pixel_targets: d::pso::PixelTargetSet<R>,
    pub ref_values: d::state::RefValues,
    pub scissor: d::target::Rect,
}

impl<R: d::Resources> RawDataSet<R> {
    /// Create an empty data set.
    pub fn new() -> RawDataSet<R> {
        RawDataSet {
            vertex_buffers: d::pso::VertexBufferSet::new(),
            constant_buffers: Vec::new(),
            global_constants: Vec::new(),
            resource_views: Vec::new(),
            unordered_views: Vec::new(),
            samplers: Vec::new(),
            pixel_targets: d::pso::PixelTargetSet::new(),
            ref_values: Default::default(),
            scissor: d::target::Rect{x:0, y:0, w:1, h:1},
        }
    }
    /// Clear all contained data.
    pub fn clear(&mut self) {
        self.vertex_buffers = d::pso::VertexBufferSet::new();
        self.constant_buffers.clear();
        self.global_constants.clear();
        self.resource_views.clear();
        self.unordered_views.clear();
        self.samplers.clear();
        self.pixel_targets = d::pso::PixelTargetSet::new();
        self.ref_values = Default::default();
        self.scissor = d::target::Rect{x:0, y:0, w:1, h:1};
    }
}

/// Failure to initilize the link between the shader and the data.
#[derive(Clone, PartialEq, Debug)]
pub enum InitError {
    /// Vertex attribute mismatch.
    VertexImport(d::AttributeSlot, Option<d::format::Format>),
    /// Constant buffer mismatch.
    ConstantBuffer(d::ConstantBufferSlot, Option<()>),
    /// Global constant mismatch.
    GlobalConstant(d::shade::Location, Option<()>),
    /// Shader resource view mismatch.
    ResourceView(d::ResourceViewSlot, Option<()>),
    /// Unordered access view mismatch.
    UnorderedView(d::UnorderedViewSlot, Option<()>),
    /// Sampler mismatch.
    Sampler(d::SamplerSlot, Option<()>),
    /// Pixel target mismatch.
    PixelExport(d::ColorSlot, Option<d::format::Format>),
}

/// A service trait implemented by the "init" structure of PSO.
pub trait PipelineInit {
    /// The associated "meta" struct.
    type Meta;
    /// Attempt to map a PSO descriptor to a give shader program,
    /// represented by `ProgramInfo`. Returns an instance of the
    /// "meta" struct upon successful mapping.
    fn link_to(&self, &mut Descriptor, &d::shade::ProgramInfo)
               -> Result<Self::Meta, InitError>;
}

/// a service trait implemented the "data" structure of PSO.
pub trait PipelineData<R: d::Resources> {
    /// The associated "meta" struct.
    type Meta;
    /// Dump all the contained data into the raw data set,
    /// given the mapping ("meta"), and a handle manager.
    fn bake_to(&self, &mut RawDataSet<R>, meta: &Self::Meta, &mut d::handle::Manager<R>);
}

/// A strongly typed Pipleline State Object. See the module documentation for more information.
pub struct PipelineState<R: d::Resources, M>(
    d::handle::RawPipelineState<R>, d::Primitive, M);

impl<R: d::Resources, M> PipelineState<R, M> {
    /// Create a new PSO from a raw handle and the "meta" instance.
    pub fn new(raw: d::handle::RawPipelineState<R>, prim: d::Primitive, meta: M)
               -> PipelineState<R, M> {
        PipelineState(raw, prim, meta)
    }
    /// Get a raw handle reference.
    pub fn get_handle(&self) -> &d::handle::RawPipelineState<R> {
        &self.0
    }
    /// Get a "meta" struct reference. Can be used by the user to check
    /// what resources are actually used and what not.
    pub fn get_meta(&self) -> &M {
        &self.2
    }
}

/// The "link" logic portion of a PSO component.
/// Defines the input data for the component.
pub trait DataLink<'a>: Sized {
    /// The assotiated "init" type - a member of the PSO "init" struct.
    type Init: 'a;
    /// Create a new empty data link.
    fn new() -> Self;
    /// Check if this link is actually used by the shader.
    fn is_active(&self) -> bool;
    /// Attempt to link with a vertex attribute.
    fn link_input(&mut self, _: &d::shade::AttributeVar, _: &Self::Init) ->
                  Option<Result<d::pso::AttributeDesc, d::format::Format>> { None }
    /// Attempt to link with a constant buffer.
    fn link_constant_buffer(&mut self, _: &d::shade::ConstantBufferVar, _: &Self::Init) ->
                            Option<Result<(), d::shade::ConstFormat>> { None }
    /// Attempt to link with a global constant.
    fn link_global_constant(&mut self, _: &d::shade::ConstVar, _: &Self::Init) ->
                            Option<Result<(), d::shade::UniformValue>> { None }
    /// Attempt to link with an output render target (RTV).
    fn link_output(&mut self, _: &d::shade::OutputVar, _: &Self::Init) ->
                   Option<Result<d::pso::ColorTargetDesc, d::format::Format>> { None }
    /// Attempt to link with a depth-stencil target (DSV).
    fn link_depth_stencil(&mut self, _: &Self::Init) ->
                          Option<d::pso::DepthStencilDesc> { None }
    /// Attempt to link with a shader resource (SRV).
    fn link_resource_view(&mut self, _: &d::shade::TextureVar, _: &Self::Init) ->
                          Option<Result<(), d::format::Format>> { None }
    /// Attempt to link with an unordered access (UAV).
    fn link_unordered_view(&mut self, _: &d::shade::UnorderedVar, _: &Self::Init) ->
                           Option<Result<(), d::format::Format>> { None }
    /// Attempt to link with a sampler.
    fn link_sampler(&mut self, _: &d::shade::SamplerVar, _: &Self::Init) -> Option<()> { None }
    /// Attempt to enable scissor test.
    fn link_scissor(&mut self) -> bool { false }
}

/// The "bind" logic portion of the PSO component.
/// Defines how the user data translates into the raw data set.
pub trait DataBind<R: d::Resources> {
    /// The associated "data" type - a member of the PSO "data" struct.
    type Data;
    /// Dump the given data into the raw data set.
    fn bind_to(&self, &mut RawDataSet<R>, &Self::Data, &mut d::handle::Manager<R>);
}
<commit_msg>Fix type in pso documentation.<commit_after>// Copyright 2015 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.

//! A typed high-level graphics pipeline interface.
//!
//! # Overview
//! A `PipelineState` holds all information needed to manage a graphics pipeline. It contains
//! information about the shaders used, and on how to bind variables to these shaders. A
//! `PipelineState` manifests itself in the form of a Pipeline State Object, or PSO in short.
//!
//! A Pipeline State Object exists out of different components. Every component represents
//! a resource handle: a shader input or output/target. The types of these components can be found
//! in this module's submodules, grouped by category.
//!
//! Before all, a Pipeline State Object must be defined. This is done using the `gfx_pipeline`
//! macro. This macro creates three different structures:
//!
//! - The `Init` structure contains the location of every PSO component. During shader linking,
//!   this is used to construct the `Meta` structure.
//! - The `Meta` structure contains the layout of every PSO. Using the `Meta` structure, the right
//!   data is mapped to the right components.
//! - The `Data` structure contains the data of all components, to be sent to the GPU.
//!
//! # Construction and Handling
//! A Pipeline State Object is constructed by a factory, from its `Init` structure, a `Rasterizer`,
//! a primitive type and a shader program.
//!
//! After construction an `Encoder` can use the PSO along with a `Data` structure matching that
//! PSO to process the shader pipeline, for instance, using the `draw` method.

pub mod buffer;
pub mod resource;
pub mod target;
pub mod bundle;

use std::default::Default;
use gfx_core as d;
pub use gfx_core::pso::{Descriptor};

/// A complete set of raw data that needs to be specified at run-time
/// whenever we draw something with a PSO. This is what "data" struct
/// gets transformed into when we call `encoder.draw(...)` with it.
/// It doesn't have any typing information, since PSO knows what
/// format and layout to expect from each resource.
#[allow(missing_docs)]
#[derive(Debug)]
pub struct RawDataSet<R: d::Resources>{
    pub vertex_buffers: d::pso::VertexBufferSet<R>,
    pub constant_buffers: Vec<d::pso::ConstantBufferParam<R>>,
    pub global_constants: Vec<(d::shade::Location, d::shade::UniformValue)>,
    pub resource_views: Vec<d::pso::ResourceViewParam<R>>,
    pub unordered_views: Vec<d::pso::UnorderedViewParam<R>>,
    pub samplers: Vec<d::pso::SamplerParam<R>>,
    pub pixel_targets: d::pso::PixelTargetSet<R>,
    pub ref_values: d::state::RefValues,
    pub scissor: d::target::Rect,
}

impl<R: d::Resources> RawDataSet<R> {
    /// Create an empty data set.
    pub fn new() -> RawDataSet<R> {
        RawDataSet {
            vertex_buffers: d::pso::VertexBufferSet::new(),
            constant_buffers: Vec::new(),
            global_constants: Vec::new(),
            resource_views: Vec::new(),
            unordered_views: Vec::new(),
            samplers: Vec::new(),
            pixel_targets: d::pso::PixelTargetSet::new(),
            ref_values: Default::default(),
            scissor: d::target::Rect{x:0, y:0, w:1, h:1},
        }
    }
    /// Clear all contained data.
    pub fn clear(&mut self) {
        self.vertex_buffers = d::pso::VertexBufferSet::new();
        self.constant_buffers.clear();
        self.global_constants.clear();
        self.resource_views.clear();
        self.unordered_views.clear();
        self.samplers.clear();
        self.pixel_targets = d::pso::PixelTargetSet::new();
        self.ref_values = Default::default();
        self.scissor = d::target::Rect{x:0, y:0, w:1, h:1};
    }
}

/// Failure to initilize the link between the shader and the data.
#[derive(Clone, PartialEq, Debug)]
pub enum InitError {
    /// Vertex attribute mismatch.
    VertexImport(d::AttributeSlot, Option<d::format::Format>),
    /// Constant buffer mismatch.
    ConstantBuffer(d::ConstantBufferSlot, Option<()>),
    /// Global constant mismatch.
    GlobalConstant(d::shade::Location, Option<()>),
    /// Shader resource view mismatch.
    ResourceView(d::ResourceViewSlot, Option<()>),
    /// Unordered access view mismatch.
    UnorderedView(d::UnorderedViewSlot, Option<()>),
    /// Sampler mismatch.
    Sampler(d::SamplerSlot, Option<()>),
    /// Pixel target mismatch.
    PixelExport(d::ColorSlot, Option<d::format::Format>),
}

/// A service trait implemented by the "init" structure of PSO.
pub trait PipelineInit {
    /// The associated "meta" struct.
    type Meta;
    /// Attempt to map a PSO descriptor to a give shader program,
    /// represented by `ProgramInfo`. Returns an instance of the
    /// "meta" struct upon successful mapping.
    fn link_to(&self, &mut Descriptor, &d::shade::ProgramInfo)
               -> Result<Self::Meta, InitError>;
}

/// a service trait implemented the "data" structure of PSO.
pub trait PipelineData<R: d::Resources> {
    /// The associated "meta" struct.
    type Meta;
    /// Dump all the contained data into the raw data set,
    /// given the mapping ("meta"), and a handle manager.
    fn bake_to(&self, &mut RawDataSet<R>, meta: &Self::Meta, &mut d::handle::Manager<R>);
}

/// A strongly typed Pipleline State Object. See the module documentation for more information.
pub struct PipelineState<R: d::Resources, M>(
    d::handle::RawPipelineState<R>, d::Primitive, M);

impl<R: d::Resources, M> PipelineState<R, M> {
    /// Create a new PSO from a raw handle and the "meta" instance.
    pub fn new(raw: d::handle::RawPipelineState<R>, prim: d::Primitive, meta: M)
               -> PipelineState<R, M> {
        PipelineState(raw, prim, meta)
    }
    /// Get a raw handle reference.
    pub fn get_handle(&self) -> &d::handle::RawPipelineState<R> {
        &self.0
    }
    /// Get a "meta" struct reference. Can be used by the user to check
    /// what resources are actually used and what not.
    pub fn get_meta(&self) -> &M {
        &self.2
    }
}

/// The "link" logic portion of a PSO component.
/// Defines the input data for the component.
pub trait DataLink<'a>: Sized {
    /// The assotiated "init" type - a member of the PSO "init" struct.
    type Init: 'a;
    /// Create a new empty data link.
    fn new() -> Self;
    /// Check if this link is actually used by the shader.
    fn is_active(&self) -> bool;
    /// Attempt to link with a vertex attribute.
    fn link_input(&mut self, _: &d::shade::AttributeVar, _: &Self::Init) ->
                  Option<Result<d::pso::AttributeDesc, d::format::Format>> { None }
    /// Attempt to link with a constant buffer.
    fn link_constant_buffer(&mut self, _: &d::shade::ConstantBufferVar, _: &Self::Init) ->
                            Option<Result<(), d::shade::ConstFormat>> { None }
    /// Attempt to link with a global constant.
    fn link_global_constant(&mut self, _: &d::shade::ConstVar, _: &Self::Init) ->
                            Option<Result<(), d::shade::UniformValue>> { None }
    /// Attempt to link with an output render target (RTV).
    fn link_output(&mut self, _: &d::shade::OutputVar, _: &Self::Init) ->
                   Option<Result<d::pso::ColorTargetDesc, d::format::Format>> { None }
    /// Attempt to link with a depth-stencil target (DSV).
    fn link_depth_stencil(&mut self, _: &Self::Init) ->
                          Option<d::pso::DepthStencilDesc> { None }
    /// Attempt to link with a shader resource (SRV).
    fn link_resource_view(&mut self, _: &d::shade::TextureVar, _: &Self::Init) ->
                          Option<Result<(), d::format::Format>> { None }
    /// Attempt to link with an unordered access (UAV).
    fn link_unordered_view(&mut self, _: &d::shade::UnorderedVar, _: &Self::Init) ->
                           Option<Result<(), d::format::Format>> { None }
    /// Attempt to link with a sampler.
    fn link_sampler(&mut self, _: &d::shade::SamplerVar, _: &Self::Init) -> Option<()> { None }
    /// Attempt to enable scissor test.
    fn link_scissor(&mut self) -> bool { false }
}

/// The "bind" logic portion of the PSO component.
/// Defines how the user data translates into the raw data set.
pub trait DataBind<R: d::Resources> {
    /// The associated "data" type - a member of the PSO "data" struct.
    type Data;
    /// Dump the given data into the raw data set.
    fn bind_to(&self, &mut RawDataSet<R>, &Self::Data, &mut d::handle::Manager<R>);
}
<|endoftext|>


<commit_before><commit_msg>Moar rainbows \o/<commit_after>extern mod png;

use std::iter::count;

struct Pixel(u8, u8, u8);

fn to_vec(pixels: ~[Pixel]) -> ~[u8] {
  pixels.flat_map(|&Pixel(r, g, b)| { ~[r, g, b] })
}

fn main() {
  let mut line = ~[Pixel(0, 0, 0), ..100];

  for x in range(0u, 100) {
    line[x] = match x {
      x if x < 25 => { Pixel(255, count(0u8, 255 / 25).nth(x % 25).unwrap(), 0) }
      x if x < 50 => { Pixel(255 - count(1u8, 255 / 25).nth(x % 25).unwrap(), 255, 0) }
      x if x < 75 => { Pixel(0, 255 - count(1u8, 255 / 25).nth(x % 25).unwrap(), count(0u8, 255 / 25).nth(x % 25).unwrap()) }
      _ => { Pixel(0, count(0u8, 192 / 25).nth(x % 25).unwrap(), 255) }
    }
  }

  let pixels = std::vec::from_fn(100 * 100, |i| { line[i % 100] });

  let img = png::Image {
    width: 100,
    height: 100,
    color_type: png::RGB8,
    pixels: to_vec(pixels)
  };

  png::store_png(&img, &Path::new("rainbow.png"));
}
<|endoftext|>


<commit_before><commit_msg>reexport json value from execute request module<commit_after><|endoftext|>


<commit_before><commit_msg>Add documentation to easy-plugin-plugins crate<commit_after><|endoftext|>


<commit_before><commit_msg>And mem_map.rs :)<commit_after>pub const PIF_ROM_START: u32 = 0x1fc0_0000;
pub const PIF_ROM_LENGTH: u32 = 2048;
pub const PIF_ROM_END: u32 = PIF_ROM_START + PIF_ROM_LENGTH;

pub const SP_BASE_REG: u32 = 0x0404_0000;
pub const SP_STATUS_REG: u32 = 0x0404_0010;
<|endoftext|>