<commit_before><commit_msg>Add a basic base64 module<commit_after>import io::{reader, reader_util};

iface to_base64 {
    fn to_base64() -> str;
}

impl of to_base64 for ~[u8] {
    fn to_base64() -> str {
        let chars = str::chars(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
        );

        let len = self.len();
        let mut s = "";
        str::reserve(s, ((len + 3u) / 4u) * 3u);

        let mut i = 0u;

        while i < len - (len % 3u) {
            let n = (self[i] as uint) << 16u |
                    (self[i + 1u] as uint) << 8u |
                    (self[i + 2u] as uint);

            // This 24-bit number gets separated into four 6-bit numbers.
            str::push_char(s, chars[(n >> 18u) & 63u]);
            str::push_char(s, chars[(n >> 12u) & 63u]);
            str::push_char(s, chars[(n >> 6u) & 63u]);
            str::push_char(s, chars[n & 63u]);

            i += 3u;
        }

        alt check len % 3u {
          0u { }
          1u {
            let n = (self[i] as uint) << 16u;
            str::push_char(s, chars[(n >> 18u) & 63u]);
            str::push_char(s, chars[(n >> 12u) & 63u]);
            str::push_char(s, '=');
            str::push_char(s, '=');
          }
          2u {
            let n = (self[i] as uint) << 16u | (self[i + 1u] as uint) << 8u;
            str::push_char(s, chars[(n >> 18u) & 63u]);
            str::push_char(s, chars[(n >> 12u) & 63u]);
            str::push_char(s, chars[(n >> 6u) & 63u]);
            str::push_char(s, '=');
          }
        }

        s
    }
}

impl of to_base64 for str {
    fn to_base64() -> str {
        str::bytes(self).to_base64()
    }
}

iface from_base64 {
    fn from_base64() -> ~[u8];
}

impl of from_base64 for ~[u8] {
    fn from_base64() -> ~[u8] {
        if self.len() % 4u != 0u { fail "invalid base64 length"; }

        let len = self.len();
        let mut padding = 0u;

        if len != 0u {
            if self[len - 1u] == '=' as u8 { padding += 1u; }
            if self[len - 2u] == '=' as u8 { padding += 1u; }
        }

        let mut r = ~[];
        vec::reserve(r, (len / 4u) * 3u - padding);

        let mut i = 0u;
        while i < len {
            let mut n = 0u;

            for iter::repeat(4u) {
                let ch = self[i] as char;
                n <<= 6u;

                if ch >= 'A' && ch <= 'Z' {
                    n |= (ch as uint) - 0x41u;
                } else if ch >= 'a' && ch <= 'z' {
                    n |= (ch as uint) - 0x47u;
                } else if ch >= '0' && ch <= '9' {
                    n |= (ch as uint) + 0x04u;
                } else if ch == '+' {
                    n |= 0x3Eu;
                } else if ch == '/' {
                    n |= 0x3Fu;
                } else if ch == '=' {
                    alt len - i {
                      1u {
                        vec::push(r, ((n >> 16u) & 0xFFu) as u8);
                        vec::push(r, ((n >> 8u ) & 0xFFu) as u8);
                        ret copy r;
                      }
                      2u {
                        vec::push(r, ((n >> 10u) & 0xFFu) as u8);
                        ret copy r;
                      }
                      _ {
                        fail "invalid base64 padding";
                      }
                    }
                } else {
                    fail "invalid base64 character";
                }

                i += 1u;
            };

            vec::push(r, ((n >> 16u) & 0xFFu) as u8);
            vec::push(r, ((n >> 8u ) & 0xFFu) as u8);
            vec::push(r, ((n       ) & 0xFFu) as u8);
        }

        r
    }
}

impl of from_base64 for str {
    fn from_base64() -> ~[u8] {
        str::bytes(self).from_base64()
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_to_base64() {
        assert "".to_base64()       == "";
        assert "f".to_base64()      == "Zg==";
        assert "fo".to_base64()     == "Zm8=";
        assert "foo".to_base64()    == "Zm9v";
        assert "foob".to_base64()   == "Zm9vYg==";
        assert "fooba".to_base64()  == "Zm9vYmE=";
        assert "foobar".to_base64() == "Zm9vYmFy";
    }

    #[test]
    fn test_from_base64() {
        assert "".from_base64() == str::bytes("");
        assert "Zg==".from_base64() == str::bytes("f");
        assert "Zm8=".from_base64() == str::bytes("fo");
        assert "Zm9v".from_base64() == str::bytes("foo");
        assert "Zm9vYg==".from_base64() == str::bytes("foob");
        assert "Zm9vYmE=".from_base64() == str::bytes("fooba");
        assert "Zm9vYmFy".from_base64() == str::bytes("foobar");
    }
}
<|endoftext|>


<commit_before><commit_msg>Advent<commit_after><|endoftext|>


<commit_before><commit_msg>Do not delete empty strings<commit_after><|endoftext|>


<commit_before><commit_msg>Example example :)<commit_after>extern crate rosc;

fn main() {
    println!("hello");
}
<|endoftext|>


<commit_before><commit_msg>chore: shortcut for propagating errors: ?<commit_after><|endoftext|>


<commit_before><commit_msg>Rollup merge of #76977 - tmiasko:issue-76740, r=wesleywiser<commit_after>// Regression test for issue #76740.
// run-fail FIXME: change to run-pass once #76899 lands
// compile-flags: -Zmir-opt-level=3

#[derive(Copy, Clone)]
pub struct V([usize; 4]);

impl V {
    fn new() -> Self {
        V([0; 4])
    }

    #[inline(never)]
    fn check(mut self) {
        assert_eq!(self.0[0], 0);
        self.0[0] = 1;
    }
}

fn main() {
    let v = V::new();
    let mut i = 0;
    while i != 10 {
        // Copy propagation incorrectly assumed that Operand::Move does not
        // mutate the local, and used the same v for each V::check call,
        // rather than a copy.
        v.check();
        i += 1;
    }
}
<|endoftext|>


<commit_before>use collections::string::ToString;

use common::event::MouseEvent;
use common::memory;
use common::time::{self, Duration};

use core::{cmp, mem, ptr, slice, str};

use graphics::display::VBEMODEINFO;

use scheduler::Context;

use super::{Packet, Pipe, Setup};
use super::desc::*;

pub trait Hci {
    fn msg(&mut self, address: u8, endpoint: u8, pipe: Pipe, msgs: &[Packet]) -> usize;

    fn descriptor(&mut self,
                         address: u8,
                         descriptor_type: u8,
                         descriptor_index: u8,
                         descriptor_ptr: usize,
                         descriptor_len: usize) {
        self.msg(address, 0, Pipe::Control, &[
            Packet::Setup(&Setup::get_descriptor(descriptor_type, descriptor_index, 0, descriptor_len as u16)),
            Packet::In(&mut unsafe { slice::from_raw_parts_mut(descriptor_ptr as *mut u8, descriptor_len as usize) }),
            Packet::Out(&[])
        ]);
    }

    unsafe fn device(&mut self, address: u8) where Self: Sized + 'static {
        self.msg(0, 0, Pipe::Control, &[
            Packet::Setup(&Setup::set_address(address)),
            Packet::In(&mut [])
        ]);

        let mut desc_dev = box DeviceDescriptor::default();
        self.descriptor(address,
                        DESC_DEV,
                        0,
                        (&mut *desc_dev as *mut DeviceDescriptor) as usize,
                        mem::size_of_val(&*desc_dev));
        debugln!("{:#?}", *desc_dev);

        {
            let mut desc_str = box StringDescriptor::default();
            self.descriptor(address,
                            DESC_STR,
                            desc_dev.manufacturer_string,
                            (&mut *desc_str as *mut StringDescriptor) as usize,
                            mem::size_of_val(&*desc_str));
            debugln!("Manufacturer: {}", desc_str.str());
        }

        {
            let mut desc_str = box StringDescriptor::default();
            self.descriptor(address,
                            DESC_STR,
                            desc_dev.product_string,
                            (&mut *desc_str as *mut StringDescriptor) as usize,
                            mem::size_of_val(&*desc_str));
            debugln!("Product: {}", desc_str.str());
        }

        {
            let mut desc_str = box StringDescriptor::default();
            self.descriptor(address,
                            DESC_STR,
                            desc_dev.serial_string,
                            (&mut *desc_str as *mut StringDescriptor) as usize,
                            mem::size_of_val(&*desc_str));
            debugln!("Serial: {}", desc_str.str());
        }

        for configuration in 0..(*desc_dev).configurations {
            let desc_cfg_len = 1023;
            let desc_cfg_buf = memory::alloc(desc_cfg_len) as *mut u8;
            for i in 0..desc_cfg_len as isize {
                ptr::write(desc_cfg_buf.offset(i), 0);
            }
            self.descriptor(address,
                            DESC_CFG,
                            configuration,
                            desc_cfg_buf as usize,
                            desc_cfg_len);

            let desc_cfg = ptr::read(desc_cfg_buf as *const ConfigDescriptor);
            debugln!("{:#?}", desc_cfg);

            let mut hid = false;

            let mut i = desc_cfg.length as isize;
            while i < desc_cfg.total_length as isize {
                let length = ptr::read(desc_cfg_buf.offset(i));
                let descriptor_type = ptr::read(desc_cfg_buf.offset(i + 1));
                match descriptor_type {
                    DESC_INT => {
                        let desc_int = ptr::read(desc_cfg_buf.offset(i) as *const InterfaceDescriptor);
                        debugln!("{:#?}", desc_int);
                    }
                    DESC_END => {
                        let desc_end = ptr::read(desc_cfg_buf.offset(i) as *const EndpointDescriptor);
                        debugln!("{:#?}", desc_end);

                        let endpoint = desc_end.address & 0xF;
                        let in_len = desc_end.max_packet_size as usize;

                        if hid {
                            let this = self as *mut Hci;
                            Context::spawn("kuhci_hid".to_string(), box move || {
                                debugln!("Starting HID driver");

                                let in_ptr = memory::alloc(in_len) as *mut u8;

                                loop {
                                    for i in 0..in_len as isize {
                                        ptr::write(in_ptr.offset(i), 0);
                                    }

                                    if (*this).msg(address, endpoint, Pipe::Isochronous, &[
                                        Packet::In(&mut slice::from_raw_parts_mut(in_ptr, in_len))
                                    ]) > 0 {
                                        let buttons = ptr::read(in_ptr.offset(0) as *const u8) as usize;
                                        let x = ptr::read(in_ptr.offset(1) as *const u16) as usize;
                                        let y = ptr::read(in_ptr.offset(3) as *const u16) as usize;

                                        let mode_info = &*VBEMODEINFO;
                                        let mouse_x = (x * mode_info.xresolution as usize) / 32768;
                                        let mouse_y = (y * mode_info.yresolution as usize) / 32768;

                                        let mouse_event = MouseEvent {
                                            x: cmp::max(0, cmp::min(mode_info.xresolution as i32 - 1, mouse_x as i32)),
                                            y: cmp::max(0, cmp::min(mode_info.yresolution as i32 - 1, mouse_y as i32)),
                                            left_button: buttons & 1 == 1,
                                            middle_button: buttons & 4 == 4,
                                            right_button: buttons & 2 == 2,
                                        };
                                        ::env().events.lock().push_back(mouse_event.to_event());
                                    }

                                    Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep();
                                }
                            });
                        }
                    }
                    DESC_HID => {
                        let desc_hid = &*(desc_cfg_buf.offset(i) as *const HIDDescriptor);
                        debugln!("{:#?}", desc_hid);
                        hid = true;
                    }
                    _ => {
                        debugln!("Unknown Descriptor Length {} Type {:X}", length as usize, descriptor_type);
                    }
                }
                i += length as isize;
            }

            memory::unalloc(desc_cfg_buf as usize);
        }
    }
}
<commit_msg>Make sure string descriptors are not null<commit_after>use collections::string::ToString;

use common::event::MouseEvent;
use common::memory;
use common::time::{self, Duration};

use core::{cmp, mem, ptr, slice, str};

use graphics::display::VBEMODEINFO;

use scheduler::Context;

use super::{Packet, Pipe, Setup};
use super::desc::*;

pub trait Hci {
    fn msg(&mut self, address: u8, endpoint: u8, pipe: Pipe, msgs: &[Packet]) -> usize;

    fn descriptor(&mut self,
                         address: u8,
                         descriptor_type: u8,
                         descriptor_index: u8,
                         descriptor_ptr: usize,
                         descriptor_len: usize) {
        self.msg(address, 0, Pipe::Control, &[
            Packet::Setup(&Setup::get_descriptor(descriptor_type, descriptor_index, 0, descriptor_len as u16)),
            Packet::In(&mut unsafe { slice::from_raw_parts_mut(descriptor_ptr as *mut u8, descriptor_len as usize) }),
            Packet::Out(&[])
        ]);
    }

    unsafe fn device(&mut self, address: u8) where Self: Sized + 'static {
        self.msg(0, 0, Pipe::Control, &[
            Packet::Setup(&Setup::set_address(address)),
            Packet::In(&mut [])
        ]);

        let mut desc_dev = box DeviceDescriptor::default();
        self.descriptor(address,
                        DESC_DEV,
                        0,
                        (&mut *desc_dev as *mut DeviceDescriptor) as usize,
                        mem::size_of_val(&*desc_dev));
        debugln!("{:#?}", *desc_dev);

        if desc_dev.manufacturer_string > 0 {
            let mut desc_str = box StringDescriptor::default();
            self.descriptor(address,
                            DESC_STR,
                            desc_dev.manufacturer_string,
                            (&mut *desc_str as *mut StringDescriptor) as usize,
                            mem::size_of_val(&*desc_str));
            debugln!("Manufacturer: {}", desc_str.str());
        }

        if desc_dev.product_string > 0 {
            let mut desc_str = box StringDescriptor::default();
            self.descriptor(address,
                            DESC_STR,
                            desc_dev.product_string,
                            (&mut *desc_str as *mut StringDescriptor) as usize,
                            mem::size_of_val(&*desc_str));
            debugln!("Product: {}", desc_str.str());
        }

        if desc_dev.serial_string > 0 {
            let mut desc_str = box StringDescriptor::default();
            self.descriptor(address,
                            DESC_STR,
                            desc_dev.serial_string,
                            (&mut *desc_str as *mut StringDescriptor) as usize,
                            mem::size_of_val(&*desc_str));
            debugln!("Serial: {}", desc_str.str());
        }

        for configuration in 0..(*desc_dev).configurations {
            let desc_cfg_len = 1023;
            let desc_cfg_buf = memory::alloc(desc_cfg_len) as *mut u8;
            for i in 0..desc_cfg_len as isize {
                ptr::write(desc_cfg_buf.offset(i), 0);
            }
            self.descriptor(address,
                            DESC_CFG,
                            configuration,
                            desc_cfg_buf as usize,
                            desc_cfg_len);

            let desc_cfg = ptr::read(desc_cfg_buf as *const ConfigDescriptor);
            debugln!("{:#?}", desc_cfg);

            if desc_cfg.string > 0 {
                let mut desc_str = box StringDescriptor::default();
                self.descriptor(address,
                                DESC_STR,
                                desc_cfg.string,
                                (&mut *desc_str as *mut StringDescriptor) as usize,
                                mem::size_of_val(&*desc_str));
                debugln!("Configuration: {}", desc_str.str());
            }

            let mut hid = false;

            let mut i = desc_cfg.length as isize;
            while i < desc_cfg.total_length as isize {
                let length = ptr::read(desc_cfg_buf.offset(i));
                let descriptor_type = ptr::read(desc_cfg_buf.offset(i + 1));
                match descriptor_type {
                    DESC_INT => {
                        let desc_int = ptr::read(desc_cfg_buf.offset(i) as *const InterfaceDescriptor);
                        debugln!("{:#?}", desc_int);

                        if desc_int.string > 0 {
                            let mut desc_str = box StringDescriptor::default();
                            self.descriptor(address,
                                            DESC_STR,
                                            desc_int.string,
                                            (&mut *desc_str as *mut StringDescriptor) as usize,
                                            mem::size_of_val(&*desc_str));
                            debugln!("Interface: {}", desc_str.str());
                        }
                    }
                    DESC_END => {
                        let desc_end = ptr::read(desc_cfg_buf.offset(i) as *const EndpointDescriptor);
                        debugln!("{:#?}", desc_end);

                        let endpoint = desc_end.address & 0xF;
                        let in_len = desc_end.max_packet_size as usize;

                        if hid {
                            let this = self as *mut Hci;
                            Context::spawn("kuhci_hid".to_string(), box move || {
                                debugln!("Starting HID driver");

                                let in_ptr = memory::alloc(in_len) as *mut u8;

                                loop {
                                    for i in 0..in_len as isize {
                                        ptr::write(in_ptr.offset(i), 0);
                                    }

                                    if (*this).msg(address, endpoint, Pipe::Isochronous, &[
                                        Packet::In(&mut slice::from_raw_parts_mut(in_ptr, in_len))
                                    ]) > 0 {
                                        let buttons = ptr::read(in_ptr.offset(0) as *const u8) as usize;
                                        let x = ptr::read(in_ptr.offset(1) as *const u16) as usize;
                                        let y = ptr::read(in_ptr.offset(3) as *const u16) as usize;

                                        let mode_info = &*VBEMODEINFO;
                                        let mouse_x = (x * mode_info.xresolution as usize) / 32768;
                                        let mouse_y = (y * mode_info.yresolution as usize) / 32768;

                                        let mouse_event = MouseEvent {
                                            x: cmp::max(0, cmp::min(mode_info.xresolution as i32 - 1, mouse_x as i32)),
                                            y: cmp::max(0, cmp::min(mode_info.yresolution as i32 - 1, mouse_y as i32)),
                                            left_button: buttons & 1 == 1,
                                            middle_button: buttons & 4 == 4,
                                            right_button: buttons & 2 == 2,
                                        };
                                        ::env().events.lock().push_back(mouse_event.to_event());
                                    }

                                    Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep();
                                }
                            });
                        }
                    }
                    DESC_HID => {
                        let desc_hid = &*(desc_cfg_buf.offset(i) as *const HIDDescriptor);
                        debugln!("{:#?}", desc_hid);
                        hid = true;
                    }
                    _ => {
                        debugln!("Unknown Descriptor Length {} Type {:X}", length as usize, descriptor_type);
                    }
                }
                i += length as isize;
            }

            memory::unalloc(desc_cfg_buf as usize);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add native_closures.rs example with GMainLoop and g_idle_add()<commit_after>#![feature(libc)]
extern crate libc;

#[repr(C)]
struct GMainLoop;

#[link(name = "glib-2.0")]
extern {
    fn g_main_loop_new(ctx: *const libc::c_void, is_running: libc::c_int) -> *mut GMainLoop;
    fn g_main_loop_run(l: *mut GMainLoop);
    fn g_main_loop_quit(l: *mut GMainLoop);
    fn g_main_loop_ref(l: *mut GMainLoop) -> *mut GMainLoop;
    fn g_main_loop_unref(l: *mut GMainLoop);

    fn g_idle_add_full(prio: libc::c_int, f: extern fn (*mut libc::c_void) -> libc::c_int, user_data: *mut libc::c_void, destroy: extern fn (*mut libc::c_void));
}

struct MainLoop {
    raw: *mut GMainLoop
}

impl MainLoop {
    fn new() -> MainLoop {
        unsafe {
            let raw = g_main_loop_new(std::ptr::null(), 0);
            return MainLoop {raw: raw};
        };
    }

    fn run(&self) {
        unsafe {
            g_main_loop_run(self.raw);
        }
    }

    fn quit(&self) {
        unsafe {
            g_main_loop_quit(self.raw);
        }
    }
}

impl Drop for MainLoop {
    fn drop(&mut self) {
        unsafe {
            g_main_loop_unref(self.raw);
        }
    }
}

impl Clone for MainLoop {
    fn clone(&self) -> Self {
        unsafe {
            return MainLoop{raw: g_main_loop_ref(self.raw)};
        }
    }
}

enum SourceReturn {
    SourceContinue,
    SourceRemove
}

fn idle_add<F>(f: F)
  where F: FnMut() -> SourceReturn + 'static {
    let closure = Box::new(f);

    unsafe {
        g_idle_add_full(200, dispatch::<F>, std::mem::transmute(closure), destroy::<F>);
    }

    extern fn dispatch<F>(user_data: *mut libc::c_void) -> libc::c_int
      where F: FnMut() -> SourceReturn + 'static {
        unsafe {
            let mut closure: Box<F> = std::mem::transmute(user_data);

            let res = match (*closure)() {
                SourceReturn::SourceRemove => 0,
                _                          => 1
            };

            std::mem::forget(closure);
            return res;
        }
    }

    extern fn destroy<F>(user_data: *mut libc::c_void)
      where F: FnMut() -> SourceReturn + 'static{
        unsafe {
            let _: Box<F> = std::mem::transmute(user_data);
        }
    }
}

struct Foo {
    b : u32
}

impl Drop for Foo {
    fn drop(&mut self) {
        print!("drop!\n");
    }
}

fn foo(l: &mut MainLoop) {
    let l = l.clone();
    let mut x = 0;
    let y = Foo{b: 1};

    idle_add(move || {
        x += 1;
        print!("bar {} {}\n", x, y.b);

        if x >= 100 {
            l.quit();
            return SourceReturn::SourceRemove;
        }

        return SourceReturn::SourceContinue;
    });
}

fn main() {
    let mut l = MainLoop::new();

    foo(&mut l);

    l.run();

    print!("done\n");
}
<|endoftext|>


<commit_before><commit_msg>(feat) Added Hello World example.<commit_after><|endoftext|>


<commit_before>//! Enviroment data

use alloc::boxed::Box;

use core_collections::borrow::ToOwned;

use ffi::{OsString, OsStr};
use fs::{self, File};
use path::{Path, PathBuf};
use string::{String, ToString};
use sys_common::AsInner;
use vec::Vec;

use system::error::ENOENT;
use system::syscall::sys_chdir;

use io::{Error, Result, Read, Write};

static mut _args: *mut Vec<&'static str> = 0 as *mut Vec<&'static str>;

pub struct Args {
    i: usize
}

impl Iterator for Args {
    //Yes, this is supposed to be String, do not change it!
    //Only change it if https://doc.rust-lang.org/std/env/struct.Args.html changes from String
    type Item = String;
    fn next(&mut self) -> Option<String> {
        if let Some(arg) = unsafe { (*_args).get(self.i) } {
            self.i += 1;
            Some(arg.to_string())
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = if self.i <= unsafe { (*_args).len() } {
            unsafe { (*_args).len() - self.i }
        } else {
            0
        };
        (len, Some(len))
    }
}

impl ExactSizeIterator for Args {}

/// Arguments
pub fn args() -> Args {
    Args {
        i: 0
    }
}

/// Initialize arguments
pub unsafe fn args_init(args: Vec<&'static str>) {
    _args = Box::into_raw(box args);
}

/// Destroy arguments
pub unsafe fn args_destroy() {
    if _args as usize > 0 {
        drop(Box::from_raw(_args));
    }
}

/// Private function to get the path from a custom location
/// If the custom directory cannot be found, None will be returned
fn get_path_from(location : &str) -> Result<PathBuf> {
    match File::open(location) {
        Ok(file) => {
            match file.path() {
                Ok(path) => Ok(path),
                Err(err) => Err(err),
            }
        }
        Err(err) => Err(err),
    }
}

/// Method to return the current directory
pub fn current_dir() -> Result<PathBuf> {
    // Return the current path
    get_path_from("./")
}

/// Method to return the home directory
pub fn home_dir() -> Option<PathBuf> {
    get_path_from("/home/").ok()
}

pub fn temp_dir() -> Option<PathBuf> {
    get_path_from("/tmp/").ok()
}

/// Set the current directory
pub fn set_current_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let file_result = if path_str.is_empty() || path_str.ends_with('/') {
        File::open(path_str)
    } else {
        let mut path_string = path_str.to_owned();
        path_string.push_str("/");
        File::open(path_string)
    };

    match file_result {
        Ok(file) => {
            match file.path() {
                Ok(path) => {
                    if let Some(path_str) = path.to_str() {
                        let mut path_c = path_str.to_owned();
                        path_c.push_str("\0");
                        unsafe {
                            sys_chdir(path_c.as_ptr()).and(Ok(()))
                        }.map_err(|x| Error::from_sys(x))
                    } else {
                        Err(Error::new_sys(ENOENT))
                    }
                }
                Err(err) => Err(err),
            }
        }
        Err(err) => Err(err),
    }
}

pub enum VarError {
    NotPresent,
    NotUnicode(OsString),
}

/// Returns the environment variable `key` from the current process. If `key` is not valid Unicode
/// or if the variable is not present then `Err` is returned
pub fn var<K: AsRef<OsStr>>(key: K) -> ::core::result::Result<String, VarError> {
    if let Some(key_str) = key.as_ref().to_str() {
        let mut file = try!(File::open(&("env:".to_owned() + key_str)).or(Err(VarError::NotPresent)));
        let mut string = String::new();
        try!(file.read_to_string(&mut string).or(Err(VarError::NotPresent)));
        Ok(string)
    } else {
        Err(VarError::NotUnicode(key.as_ref().to_owned()))
    }
}

pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
    if let Ok(value) = var(key) {
        Some((value.as_ref() as &OsStr).to_owned())
    } else {
        None
    }
}

/// Sets the environment variable `key` to the value `value` for the current process
pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) {
    if let (Some(key_str), Some(value_str)) = (key.as_ref().to_str(), value.as_ref().to_str()) {
        if let Ok(mut file) = File::open(&("env:".to_owned() + key_str)) {
            let _ = file.write_all(value_str.as_bytes());
        }
    }
}

/// Removes an environment variable from the environment of the current process
pub fn remove_var<K: AsRef<OsStr>>(key: K) {
    if let Some(key_str) = key.as_ref().to_str() {
        let _ = fs::remove_file(&("env:".to_owned() + key_str));
    }
}

pub struct Vars {
    vars: Vec<(String, String)>,
    pos: usize
}

impl Iterator for Vars {
    type Item = (String, String);

    fn next(&mut self) -> Option<Self::Item> {
        let variable = self.vars.get(self.pos);
        self.pos += 1;
        variable.cloned()
    }
}

/// Returns an iterator over the environment variables of the current process
pub fn vars() -> Vars {
    let mut variables: Vec<(String, String)> = Vec::new();
    if let Ok(mut file) = File::open("env:") {
        let mut string = String::new();
        if file.read_to_string(&mut string).is_ok() {
            for line in string.lines() {
                if let Some(equal_sign) = line.chars().position(|c| c == '=') {
                    let name = line.chars().take(equal_sign).collect::<String>();
                    let value = line.chars().skip(equal_sign+1).collect::<String>();
                    variables.push((name, value));
                }
            }
            return Vars { vars: variables, pos: 0 };
        }
    }
    Vars { vars: Vec::new(), pos: 0 }
}
<commit_msg>Add some documentation to std::env<commit_after>//! Enviroment data

use alloc::boxed::Box;

use core_collections::borrow::ToOwned;

use ffi::{OsString, OsStr};
use fs::{self, File};
use path::{Path, PathBuf};
use string::{String, ToString};
use sys_common::AsInner;
use vec::Vec;
use error;
use fmt;

use system::error::ENOENT;
use system::syscall::sys_chdir;

use io::{Error, Result, Read, Write};

static mut _args: *mut Vec<&'static str> = 0 as *mut Vec<&'static str>;

/// An iterator over the arguments of a process, yielding a `String` value for each argument.
pub struct Args {
    i: usize
}

impl Iterator for Args {
    //Yes, this is supposed to be String, do not change it!
    //Only change it if https://doc.rust-lang.org/std/env/struct.Args.html changes from String
    type Item = String;
    fn next(&mut self) -> Option<String> {
        if let Some(arg) = unsafe { (*_args).get(self.i) } {
            self.i += 1;
            Some(arg.to_string())
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = if self.i <= unsafe { (*_args).len() } {
            unsafe { (*_args).len() - self.i }
        } else {
            0
        };
        (len, Some(len))
    }
}

impl ExactSizeIterator for Args {}

/// Arguments
pub fn args() -> Args {
    Args {
        i: 0
    }
}

/// Initialize arguments
pub unsafe fn args_init(args: Vec<&'static str>) {
    _args = Box::into_raw(box args);
}

/// Destroy arguments
pub unsafe fn args_destroy() {
    if _args as usize > 0 {
        drop(Box::from_raw(_args));
    }
}

/// Private function to get the path from a custom location
/// If the custom directory cannot be found, None will be returned
fn get_path_from(location : &str) -> Result<PathBuf> {
    match File::open(location) {
        Ok(file) => {
            match file.path() {
                Ok(path) => Ok(path),
                Err(err) => Err(err),
            }
        }
        Err(err) => Err(err),
    }
}

/// Method to return the current directory
pub fn current_dir() -> Result<PathBuf> {
    // Return the current path
    get_path_from("./")
}

/// Method to return the home directory
pub fn home_dir() -> Option<PathBuf> {
    get_path_from("/home/").ok()
}

pub fn temp_dir() -> Option<PathBuf> {
    get_path_from("/tmp/").ok()
}

/// Set the current directory
pub fn set_current_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let file_result = if path_str.is_empty() || path_str.ends_with('/') {
        File::open(path_str)
    } else {
        let mut path_string = path_str.to_owned();
        path_string.push_str("/");
        File::open(path_string)
    };

    match file_result {
        Ok(file) => {
            match file.path() {
                Ok(path) => {
                    if let Some(path_str) = path.to_str() {
                        let mut path_c = path_str.to_owned();
                        path_c.push_str("\0");
                        unsafe {
                            sys_chdir(path_c.as_ptr()).and(Ok(()))
                        }.map_err(|x| Error::from_sys(x))
                    } else {
                        Err(Error::new_sys(ENOENT))
                    }
                }
                Err(err) => Err(err),
            }
        }
        Err(err) => Err(err),
    }
}

/// Possible errors from the `env::var` method.
#[derive(Debug)]
pub enum VarError {
    /// The specified environment variable was not set.
    NotPresent,
    /// The key or the value of the specified environment variable did not contain valid Unicode
    /// data.
    NotUnicode(OsString),
}

impl fmt::Display for VarError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            VarError::NotPresent => write!(f, "environment variable not found"),
            VarError::NotUnicode(ref s) => write!(f, "environment variable was not valid unicode: {:?}", s)
        }
    }
}

impl error::Error for VarError {
    fn description(&self) -> &str {
        match *self {
            VarError::NotPresent => "environment variable not found",
            VarError::NotUnicode(_) => "environment variable was not valid unicode"
        }
    }
}

/// Returns the environment variable `key` from the current process. If `key` is not valid Unicode
/// or if the variable is not present then `Err` is returned
pub fn var<K: AsRef<OsStr>>(key: K) -> ::core::result::Result<String, VarError> {
    if let Some(key_str) = key.as_ref().to_str() {
        let mut file = try!(File::open(&("env:".to_owned() + key_str)).or(Err(VarError::NotPresent)));
        let mut string = String::new();
        try!(file.read_to_string(&mut string).or(Err(VarError::NotPresent)));
        Ok(string)
    } else {
        Err(VarError::NotUnicode(key.as_ref().to_owned()))
    }
}

/// Fetches the environment variable `key` from the current process, returning `None` if the
/// variable isn't set.
pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
    if let Ok(value) = var(key) {
        Some((value.as_ref() as &OsStr).to_owned())
    } else {
        None
    }
}

/// Sets the environment variable `key` to the value `value` for the current process
pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) {
    if let (Some(key_str), Some(value_str)) = (key.as_ref().to_str(), value.as_ref().to_str()) {
        if let Ok(mut file) = File::open(&("env:".to_owned() + key_str)) {
            let _ = file.write_all(value_str.as_bytes());
        }
    }
}

/// Removes an environment variable from the environment of the current process
pub fn remove_var<K: AsRef<OsStr>>(key: K) {
    if let Some(key_str) = key.as_ref().to_str() {
        let _ = fs::remove_file(&("env:".to_owned() + key_str));
    }
}

/// An iterator over the snapshot of the environment variables of this process.
/// This iterator is created through `std::env::vars() and yields (String, String) pairs.`
pub struct Vars {
    vars: Vec<(String, String)>,
    pos: usize
}

impl Iterator for Vars {
    type Item = (String, String);

    fn next(&mut self) -> Option<Self::Item> {
        let variable = self.vars.get(self.pos);
        self.pos += 1;
        variable.cloned()
    }
}

/// Returns an iterator over the environment variables of the current process
pub fn vars() -> Vars {
    let mut variables: Vec<(String, String)> = Vec::new();
    if let Ok(mut file) = File::open("env:") {
        let mut string = String::new();
        if file.read_to_string(&mut string).is_ok() {
            for line in string.lines() {
                if let Some(equal_sign) = line.chars().position(|c| c == '=') {
                    let name = line.chars().take(equal_sign).collect::<String>();
                    let value = line.chars().skip(equal_sign+1).collect::<String>();
                    variables.push((name, value));
                }
            }
            return Vars { vars: variables, pos: 0 };
        }
    }
    Vars { vars: Vec::new(), pos: 0 }
}
<|endoftext|>


<commit_before><commit_msg>Add line feed character<commit_after><|endoftext|>


<commit_before>// TODO: Refactor using a matrix for performance

use redox::*;

mod cmd;

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
        if self.offset > 0 {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset - 1].to_string() +
                &self.string[self.offset .. self.string.len()];
            self.offset -= 1;
        }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset].to_string() +
                &self.string[self.offset + 1 .. self.string.len()];
        }
    }

    // TODO: Add methods for multiple movements
    fn up(&mut self) {
        if self.cur() == '\n' || self.cur() == '\0' {
            self.left();
            while self.cur() != '\n' &&
                  self.cur() != '\0' &&
                  self.offset >= 1 {
                self.left();
            }
        } else {
            let x = self.get_x(); //- if self.cur() == '\n' { 1 } else { 0 };

            while self.cur() != '\n' {
                self.left();
            }
            self.right();
            let mut new_offset = 0;

            for i in 2..self.offset {
                match self.string.as_bytes()[self.offset - i] {
                    0 => break,
                    10 => {
                        new_offset = self.offset - i + 1;
                        break;
                    }
                    _ => (),
                }
            }
            self.offset = new_offset;
            for _ in 1..x {
                if self.cur() != '\n' {
                    self.right();
                } else {
                    break;
                }
            }
        }
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let x = self.get_x(); //- if self.cur() == '\n' { 1 } else { 0 };
        let original_c = self.cur();

        while self.offset >= self.string.len() &&
              self.cur() != '\n' &&
              self.cur() != '\0' {
            self.right();
        }
        self.right();

        if original_c == '\n' {
            while self.cur() != '\n' &&
                  self.cur() != '\0' &&
                  self.offset < self.string.len() {
                self.right();
            }
        } else {
            for _ in 1..x {
                if self.cur() != '\n' {
                    self.right();
                } else {
                    break;
                }
            }
        }
    }

    fn cur(&self) -> char {
        self.string.chars().nth(self.offset).unwrap_or('\0')
    }

    fn insert(&mut self, c: char, window: &mut Window) {
        window.set_title(&format!("{}{}{}","self (", &self.url, ") Changed"));
        self.string = self.string[0 .. self.offset].to_string() +
            &c.to_string() +
            &self.string[self.offset .. self.string.len()];
        self.offset += 1;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn get_x(&self) -> usize {
        let mut x = 0;
        for (n, c) in self.string.chars().enumerate() {
            if c == '\n' {
                x = 0;
            } else {
                x += 1;
            }
            if n >= self.offset {
                break;
            }
        }
        x
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
        (rand() % 300 + 50) as isize,
        576,
        400,
        &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;
        let mut swap = 0;
        let mut period = String::new();
        let mut is_recording = false;

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        cmd::exec(self, &mut mode, &mut multiplier, &mut last_change, key_event, &mut window, &mut swap, &mut period, &mut is_recording);

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<commit_msg>Fix bugs after refactoring<commit_after>// TODO: Refactor using a matrix for performance

use redox::*;

mod cmd;

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
        if self.offset > 0 {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset - 1].to_string() +
                &self.string[self.offset .. self.string.len()];
            self.offset -= 1;
        }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset].to_string() +
                &self.string[self.offset + 1 .. self.string.len()];
        }
    }

    // TODO: Add methods for multiple movements
    fn up(&mut self) {
        if self.cur() == '\n' || self.cur() == '\0' {
            self.left();
            while self.cur() != '\n' &&
                  self.cur() != '\0' &&
                  self.offset >= 1 {
                self.left();
            }
        } else {
            let x = self.get_x(); //- if self.cur() == '\n' { 1 } else { 0 };

            while self.cur() != '\n' &&
                  self.offset >= 1 {
                self.left();
            }
            self.right();
            let mut new_offset = 0;

            for i in 2..self.offset {
                match self.string.as_bytes()[self.offset - i] {
                    0 => break,
                    10 => {
                        new_offset = self.offset - i + 1;
                        break;
                    }
                    _ => (),
                }
            }
            self.offset = new_offset;
            for _ in 1..x {
                if self.cur() != '\n' {
                    self.right();
                } else {
                    break;
                }
            }
        }
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let x = self.get_x(); //- if self.cur() == '\n' { 1 } else { 0 };
        let original_c = self.cur();

        while self.offset < self.string.len() &&
              self.cur() != '\n' &&
              self.cur() != '\0' {
            self.right();
        }
        self.right();

        if original_c == '\n' {
            while self.cur() != '\n' &&
                  self.cur() != '\0' &&
                  self.offset < self.string.len() {
                self.right();
            }
        } else {
            for _ in 1..x {
                if self.cur() != '\n' {
                    self.right();
                } else {
                    break;
                }
            }
        }
    }

    fn cur(&self) -> char {
        self.string.chars().nth(self.offset).unwrap_or('\0')
    }

    fn insert(&mut self, c: char, window: &mut Window) {
        window.set_title(&format!("{}{}{}","self (", &self.url, ") Changed"));
        self.string = self.string[0 .. self.offset].to_string() +
            &c.to_string() +
            &self.string[self.offset .. self.string.len()];
        self.offset += 1;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn get_x(&self) -> usize {
        let mut x = 0;
        for (n, c) in self.string.chars().enumerate() {
            if c == '\n' {
                x = 0;
            } else {
                x += 1;
            }
            if n >= self.offset {
                break;
            }
        }
        x
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
        (rand() % 300 + 50) as isize,
        576,
        400,
        &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;
        let mut swap = 0;
        let mut period = String::new();
        let mut is_recording = false;

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        cmd::exec(self, &mut mode, &mut multiplier, &mut last_change, key_event, &mut window, &mut swap, &mut period, &mut is_recording);

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<|endoftext|>


<commit_before><commit_msg>Set user agent...<commit_after><|endoftext|>


<commit_before><commit_msg>Create hello-world-cl.rs<commit_after>fn main() {
    // Print text to the console
    println!("Hello World!");
    println!("Hola mundo!");
    println!("Bonjour le monde!");
    println!("Hallo verden!");
}
<|endoftext|>


<commit_before>// based on:
// http://shootout.alioth.debian.org/u32/benchmark.php?test=nbody&lang=java

#[abi = "cdecl"]
#[nolink]
native mod llvm {
    fn sqrt(n: float) -> float;
}

fn main() {
    //
    // Leave these commented out to
    // finish in a reasonable time
    // during 'make check' under valgrind
    // 5000000
    // 50000000
    let inputs: [int] = [50000, 500000];

    let bodies: [Body::props] = NBodySystem::MakeNBodySystem();

    for n: int in inputs {
        log(debug, NBodySystem::energy(bodies));

        let i: int = 0;
        while i < n { NBodySystem::advance(bodies, 0.01); i += 1; }
        log(debug, NBodySystem::energy(bodies));
    }
}

// Body::props is a record of floats, so
// vec<Body::props> is a vector of records of floats

mod NBodySystem {

    fn MakeNBodySystem() -> [Body::props] {
        // these each return a Body::props
        let bodies: [Body::props] =
            [Body::sun(), Body::jupiter(), Body::saturn(), Body::uranus(),
             Body::neptune()];

        let px: float = 0.0;
        let py: float = 0.0;
        let pz: float = 0.0;

        let i: int = 0;
        while i < 5 {
            px += bodies[i].vx * bodies[i].mass;
            py += bodies[i].vy * bodies[i].mass;
            pz += bodies[i].vz * bodies[i].mass;

            i += 1;
        }

        // side-effecting
        Body::offsetMomentum(bodies[0], px, py, pz);

        ret bodies;
    }

    fn advance(bodies: [Body::props], dt: float) {

        let i: int = 0;
        while i < 5 {
            let j: int = i + 1;
            while j < 5 { advance_one(bodies[i], bodies[j], dt); j += 1; }

            i += 1;
        }

        i = 0;
        while i < 5 { move(bodies[i], dt); i += 1; }
    }

    fn advance_one(bi: Body::props, bj: Body::props, dt: float) unsafe {
        let dx: float = bi.x - bj.x;
        let dy: float = bi.y - bj.y;
        let dz: float = bi.z - bj.z;

        let dSquared: float = dx * dx + dy * dy + dz * dz;

        let distance: float = llvm::sqrt(dSquared);
        let mag: float = dt / (dSquared * distance);

        bi.vx -= dx * bj.mass * mag;
        bi.vy -= dy * bj.mass * mag;
        bi.vz -= dz * bj.mass * mag;

        bj.vx += dx * bi.mass * mag;
        bj.vy += dy * bi.mass * mag;
        bj.vz += dz * bi.mass * mag;
    }

    fn move(b: Body::props, dt: float) {
        b.x += dt * b.vx;
        b.y += dt * b.vy;
        b.z += dt * b.vz;
    }

    fn energy(bodies: [Body::props]) -> float unsafe {
        let dx: float;
        let dy: float;
        let dz: float;
        let distance: float;
        let e: float = 0.0;

        let i: int = 0;
        while i < 5 {
            e +=
                0.5 * bodies[i].mass *
                    (bodies[i].vx * bodies[i].vx + bodies[i].vy * bodies[i].vy
                         + bodies[i].vz * bodies[i].vz);

            let j: int = i + 1;
            while j < 5 {
                dx = bodies[i].x - bodies[j].x;
                dy = bodies[i].y - bodies[j].y;
                dz = bodies[i].z - bodies[j].z;

                distance = llvm::sqrt(dx * dx + dy * dy + dz * dz);
                e -= bodies[i].mass * bodies[j].mass / distance;

                j += 1;
            }

            i += 1;
        }
        ret e;

    }
}

mod Body {

    const PI: float = 3.141592653589793;
    const SOLAR_MASS: float = 39.478417604357432;
    // was 4 * PI * PI originally
    const DAYS_PER_YEAR: float = 365.24;

    type props =
        {mutable x: float,
         mutable y: float,
         mutable z: float,
         mutable vx: float,
         mutable vy: float,
         mutable vz: float,
         mass: float};

    fn jupiter() -> Body::props {
        ret {mutable x: 4.84143144246472090e+00,
             mutable y: -1.16032004402742839e+00,
             mutable z: -1.03622044471123109e-01,
             mutable vx: 1.66007664274403694e-03 * DAYS_PER_YEAR,
             mutable vy: 7.69901118419740425e-03 * DAYS_PER_YEAR,
             mutable vz: -6.90460016972063023e-05 * DAYS_PER_YEAR,
             mass: 9.54791938424326609e-04 * SOLAR_MASS};
    }

    fn saturn() -> Body::props {
        ret {mutable x: 8.34336671824457987e+00,
             mutable y: 4.12479856412430479e+00,
             mutable z: -4.03523417114321381e-01,
             mutable vx: -2.76742510726862411e-03 * DAYS_PER_YEAR,
             mutable vy: 4.99852801234917238e-03 * DAYS_PER_YEAR,
             mutable vz: 2.30417297573763929e-05 * DAYS_PER_YEAR,
             mass: 2.85885980666130812e-04 * SOLAR_MASS};
    }

    fn uranus() -> Body::props {
        ret {mutable x: 1.28943695621391310e+01,
             mutable y: -1.51111514016986312e+01,
             mutable z: -2.23307578892655734e-01,
             mutable vx: 2.96460137564761618e-03 * DAYS_PER_YEAR,
             mutable vy: 2.37847173959480950e-03 * DAYS_PER_YEAR,
             mutable vz: -2.96589568540237556e-05 * DAYS_PER_YEAR,
             mass: 4.36624404335156298e-05 * SOLAR_MASS};
    }

    fn neptune() -> Body::props {
        ret {mutable x: 1.53796971148509165e+01,
             mutable y: -2.59193146099879641e+01,
             mutable z: 1.79258772950371181e-01,
             mutable vx: 2.68067772490389322e-03 * DAYS_PER_YEAR,
             mutable vy: 1.62824170038242295e-03 * DAYS_PER_YEAR,
             mutable vz: -9.51592254519715870e-05 * DAYS_PER_YEAR,
             mass: 5.15138902046611451e-05 * SOLAR_MASS};
    }

    fn sun() -> Body::props {
        ret {mutable x: 0.0,
             mutable y: 0.0,
             mutable z: 0.0,
             mutable vx: 0.0,
             mutable vy: 0.0,
             mutable vz: 0.0,
             mass: SOLAR_MASS};
    }

    fn offsetMomentum(props: Body::props, px: float, py: float, pz: float) {
        props.vx = -px / SOLAR_MASS;
        props.vy = -py / SOLAR_MASS;
        props.vz = -pz / SOLAR_MASS;
    }

}
<commit_msg>bench: Update shootout-nbody for style<commit_after>// based on:
// http://shootout.alioth.debian.org/u32/benchmark.php?test=nbody&lang=java

use std;

// Using sqrt from the standard library is way slower than using libc
// directly even though std just calls libc, I guess it must be
// because the the indirection through another dynamic linker
// stub. Kind of shocking. Might be able to make it faster still with
// an llvm intrinsic.
#[nolink]
native mod libc {
    fn sqrt(n: float) -> float;
}

fn main(args: [str]) {
    let n = if vec::len(args) == 2u {
        int::from_str(args[1])
    } else {
        1000000
    };
    let bodies: [Body::props] = NBodySystem::MakeNBodySystem();
    std::io::println(#fmt("%f", NBodySystem::energy(bodies)));
    let i: int = 0;
    while i < n { NBodySystem::advance(bodies, 0.01); i += 1; }
    std::io::println(#fmt("%f", NBodySystem::energy(bodies)));
}

// Body::props is a record of floats, so
// vec<Body::props> is a vector of records of floats

mod NBodySystem {

    fn MakeNBodySystem() -> [Body::props] {
        // these each return a Body::props
        let bodies: [Body::props] =
            [Body::sun(), Body::jupiter(), Body::saturn(), Body::uranus(),
             Body::neptune()];

        let px: float = 0.0;
        let py: float = 0.0;
        let pz: float = 0.0;

        let i: int = 0;
        while i < 5 {
            px += bodies[i].vx * bodies[i].mass;
            py += bodies[i].vy * bodies[i].mass;
            pz += bodies[i].vz * bodies[i].mass;

            i += 1;
        }

        // side-effecting
        Body::offsetMomentum(bodies[0], px, py, pz);

        ret bodies;
    }

    fn advance(bodies: [Body::props], dt: float) {

        let i: int = 0;
        while i < 5 {
            let j: int = i + 1;
            while j < 5 { advance_one(bodies[i], bodies[j], dt); j += 1; }

            i += 1;
        }

        i = 0;
        while i < 5 { move(bodies[i], dt); i += 1; }
    }

    fn advance_one(bi: Body::props, bj: Body::props, dt: float) unsafe {
        let dx: float = bi.x - bj.x;
        let dy: float = bi.y - bj.y;
        let dz: float = bi.z - bj.z;

        let dSquared: float = dx * dx + dy * dy + dz * dz;

        let distance: float = libc::sqrt(dSquared);
        let mag: float = dt / (dSquared * distance);

        bi.vx -= dx * bj.mass * mag;
        bi.vy -= dy * bj.mass * mag;
        bi.vz -= dz * bj.mass * mag;

        bj.vx += dx * bi.mass * mag;
        bj.vy += dy * bi.mass * mag;
        bj.vz += dz * bi.mass * mag;
    }

    fn move(b: Body::props, dt: float) {
        b.x += dt * b.vx;
        b.y += dt * b.vy;
        b.z += dt * b.vz;
    }

    fn energy(bodies: [Body::props]) -> float unsafe {
        let dx: float;
        let dy: float;
        let dz: float;
        let distance: float;
        let e: float = 0.0;

        let i: int = 0;
        while i < 5 {
            e +=
                0.5 * bodies[i].mass *
                    (bodies[i].vx * bodies[i].vx + bodies[i].vy * bodies[i].vy
                         + bodies[i].vz * bodies[i].vz);

            let j: int = i + 1;
            while j < 5 {
                dx = bodies[i].x - bodies[j].x;
                dy = bodies[i].y - bodies[j].y;
                dz = bodies[i].z - bodies[j].z;

                distance = libc::sqrt(dx * dx + dy * dy + dz * dz);
                e -= bodies[i].mass * bodies[j].mass / distance;

                j += 1;
            }

            i += 1;
        }
        ret e;

    }
}

mod Body {

    const PI: float = 3.141592653589793;
    const SOLAR_MASS: float = 39.478417604357432;
    // was 4 * PI * PI originally
    const DAYS_PER_YEAR: float = 365.24;

    type props =
        {mutable x: float,
         mutable y: float,
         mutable z: float,
         mutable vx: float,
         mutable vy: float,
         mutable vz: float,
         mass: float};

    fn jupiter() -> Body::props {
        ret {mutable x: 4.84143144246472090e+00,
             mutable y: -1.16032004402742839e+00,
             mutable z: -1.03622044471123109e-01,
             mutable vx: 1.66007664274403694e-03 * DAYS_PER_YEAR,
             mutable vy: 7.69901118419740425e-03 * DAYS_PER_YEAR,
             mutable vz: -6.90460016972063023e-05 * DAYS_PER_YEAR,
             mass: 9.54791938424326609e-04 * SOLAR_MASS};
    }

    fn saturn() -> Body::props {
        ret {mutable x: 8.34336671824457987e+00,
             mutable y: 4.12479856412430479e+00,
             mutable z: -4.03523417114321381e-01,
             mutable vx: -2.76742510726862411e-03 * DAYS_PER_YEAR,
             mutable vy: 4.99852801234917238e-03 * DAYS_PER_YEAR,
             mutable vz: 2.30417297573763929e-05 * DAYS_PER_YEAR,
             mass: 2.85885980666130812e-04 * SOLAR_MASS};
    }

    fn uranus() -> Body::props {
        ret {mutable x: 1.28943695621391310e+01,
             mutable y: -1.51111514016986312e+01,
             mutable z: -2.23307578892655734e-01,
             mutable vx: 2.96460137564761618e-03 * DAYS_PER_YEAR,
             mutable vy: 2.37847173959480950e-03 * DAYS_PER_YEAR,
             mutable vz: -2.96589568540237556e-05 * DAYS_PER_YEAR,
             mass: 4.36624404335156298e-05 * SOLAR_MASS};
    }

    fn neptune() -> Body::props {
        ret {mutable x: 1.53796971148509165e+01,
             mutable y: -2.59193146099879641e+01,
             mutable z: 1.79258772950371181e-01,
             mutable vx: 2.68067772490389322e-03 * DAYS_PER_YEAR,
             mutable vy: 1.62824170038242295e-03 * DAYS_PER_YEAR,
             mutable vz: -9.51592254519715870e-05 * DAYS_PER_YEAR,
             mass: 5.15138902046611451e-05 * SOLAR_MASS};
    }

    fn sun() -> Body::props {
        ret {mutable x: 0.0,
             mutable y: 0.0,
             mutable z: 0.0,
             mutable vx: 0.0,
             mutable vy: 0.0,
             mutable vz: 0.0,
             mass: SOLAR_MASS};
    }

    fn offsetMomentum(props: Body::props, px: float, py: float, pz: float) {
        props.vx = -px / SOLAR_MASS;
        props.vy = -py / SOLAR_MASS;
        props.vz = -pz / SOLAR_MASS;
    }

}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #18652<commit_after>// Copyright 2014 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.

// Tests multiple free variables being passed by value into an unboxed
// once closure as an optimization by trans.  This used to hit an
// incorrect assert.

#![feature(unboxed_closures, overloaded_calls)]

fn main() {
    let x = 2u8;
    let y = 3u8;
    assert_eq!((move |:| x + y)(), 5);
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #37851 - jneem:master, r=sanxiyn<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

fn gimme_a_raw_pointer<T>(_: *const T) { }

fn test<T>(t: T) { }

fn main() {
    // Clearly `pointer` must be of type `*const ()`.
    let pointer = &() as *const _;
    gimme_a_raw_pointer(pointer);

    let t = test as fn (i32);
    t(0i32);
}

<|endoftext|>


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

// compile-flags:--test
// rustc-env:RUSTC_BOOTSTRAP_KEY=
// ignore-pretty : (#23623) problems when  ending with // comments

#![cfg(any())] // This test should be configured away
#![feature(rustc_attrs)] // Test that this is allowed on stable/beta
#![feature(iter_arith_traits)] // Test that this is not unused
#![deny(unused_features)]

#[test]
fn dummy() {
    let () = "this should not reach type-checking";
}
<|endoftext|>


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

/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is public
///
/// As mentioned in a huge comment block in `super::super`, backtrace
/// doesn't play well with green threads, so while it is extremely nice and
/// simple to use it should be used only on iOS devices as the only viable
/// option.

use io;
use libc;
use mem;
use sys::backtrace::BacktraceContext;
use sys_common::backtrace::Frame;

#[inline(never)] // if we know this is a function call, we can skip it when
                 // tracing
pub fn unwind_backtrace(frames: &mut [Frame])
    -> io::Result<(usize, BacktraceContext)>
{
    const FRAME_LEN: usize = 100;
    assert!(FRAME_LEN >= frames.len());
    let mut raw_frames = [::ptr::null_mut(); FRAME_LEN];
    let nb_frames = unsafe {
        backtrace(raw_frames.as_mut_ptr(), raw_frames.len() as libc::c_int)
    } as usize;
    for (from, to) in raw_frames.iter().zip(frames.iter_mut()).take(nb_frames) {
        *to = Frame {
            exact_position: *from,
            symbol_addr: *from,
        };
    }
    Ok((nb_frames as usize, BacktraceContext))
}

extern {
    fn backtrace(buf: *mut *mut libc::c_void, sz: libc::c_int) -> libc::c_int;
}
<commit_msg>Remove unused<commit_after>// Copyright 2014-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.

/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is public
///
/// As mentioned in a huge comment block in `super::super`, backtrace
/// doesn't play well with green threads, so while it is extremely nice and
/// simple to use it should be used only on iOS devices as the only viable
/// option.

use io;
use libc;
use sys::backtrace::BacktraceContext;
use sys_common::backtrace::Frame;

#[inline(never)] // if we know this is a function call, we can skip it when
                 // tracing
pub fn unwind_backtrace(frames: &mut [Frame])
    -> io::Result<(usize, BacktraceContext)>
{
    const FRAME_LEN: usize = 100;
    assert!(FRAME_LEN >= frames.len());
    let mut raw_frames = [::ptr::null_mut(); FRAME_LEN];
    let nb_frames = unsafe {
        backtrace(raw_frames.as_mut_ptr(), raw_frames.len() as libc::c_int)
    } as usize;
    for (from, to) in raw_frames.iter().zip(frames.iter_mut()).take(nb_frames) {
        *to = Frame {
            exact_position: *from,
            symbol_addr: *from,
        };
    }
    Ok((nb_frames as usize, BacktraceContext))
}

extern {
    fn backtrace(buf: *mut *mut libc::c_void, sz: libc::c_int) -> libc::c_int;
}
<|endoftext|>


<commit_before>#![feature(slice_concat_ext, const_fn)]

extern crate compiletest_rs as compiletest;

use std::slice::SliceConcatExt;
use std::path::{PathBuf, Path};
use std::io::Write;

macro_rules! eprintln {
    ($($arg:tt)*) => {
        let stderr = std::io::stderr();
        writeln!(stderr.lock(), $($arg)*).unwrap();
    }
}

const fn miri_path() -> &'static str {
    concat!("target/", env!("PROFILE"), "/miri")
}

fn compile_fail(sysroot: &Path, path: &str, target: &str, host: &str, fullmir: bool) {
    eprintln!("## Running compile-fail tests in {} against miri for target {}", path, target);
    let mut config = compiletest::default_config();
    config.mode = "compile-fail".parse().expect("Invalid mode");
    config.rustc_path = miri_path().into();
    if fullmir {
        if host != target {
            // skip fullmir on nonhost
            return;
        }
        let sysroot = Path::new(&std::env::var("HOME").unwrap()).join(".xargo").join("HOST");
        config.target_rustcflags = Some(format!("--sysroot {}", sysroot.to_str().unwrap()));
        config.src_base = PathBuf::from(path.to_string());
    } else {
        config.target_rustcflags = Some(format!("--sysroot {}", sysroot.to_str().unwrap()));
        config.src_base = PathBuf::from(path.to_string());
    }
    config.target = target.to_owned();
    compiletest::run_tests(&config);
}

fn run_pass(path: &str) {
    eprintln!("## Running run-pass tests in {} against rustc", path);
    let mut config = compiletest::default_config();
    config.mode = "run-pass".parse().expect("Invalid mode");
    config.src_base = PathBuf::from(path);
    config.target_rustcflags = Some("-Dwarnings".to_string());
    config.host_rustcflags = Some("-Dwarnings".to_string());
    compiletest::run_tests(&config);
}

fn miri_pass(path: &str, target: &str, host: &str, fullmir: bool, opt: bool) {
    let opt_str = if opt {
        " with optimizations"
    } else {
        ""
    };
    eprintln!("## Running run-pass tests in {} against miri for target {}{}", path, target, opt_str);
    let mut config = compiletest::default_config();
    config.mode = "mir-opt".parse().expect("Invalid mode");
    config.src_base = PathBuf::from(path);
    config.target = target.to_owned();
    config.host = host.to_owned();
    config.rustc_path = miri_path().into();
    let mut flags = Vec::new();
    if fullmir {
        if host != target {
            // skip fullmir on nonhost
            return;
        }
        let sysroot = Path::new(&std::env::var("HOME").unwrap()).join(".xargo").join("HOST");
        flags.push(format!("--sysroot {}", sysroot.to_str().unwrap()));
    }
    if opt {
        flags.push("-Zmir-opt-level=3".to_owned());
    } else {
        flags.push("-Zmir-opt-level=0".to_owned());
    }
    config.target_rustcflags = Some(flags.join(" "));
    // don't actually execute the final binary, it might be for other targets and we only care
    // about running miri, not the binary.
    config.runtool = Some("echo \"\" || ".to_owned());
    if target == host {
        std::env::set_var("MIRI_HOST_TARGET", "yes");
    }
    compiletest::run_tests(&config);
    std::env::set_var("MIRI_HOST_TARGET", "");
}

fn is_target_dir<P: Into<PathBuf>>(path: P) -> bool {
    let mut path = path.into();
    path.push("lib");
    path.metadata().map(|m| m.is_dir()).unwrap_or(false)
}

fn for_all_targets<F: FnMut(String)>(sysroot: &Path, mut f: F) {
    let target_dir = sysroot.join("lib").join("rustlib");
    for entry in std::fs::read_dir(target_dir).expect("invalid sysroot") {
        let entry = entry.unwrap();
        if !is_target_dir(entry.path()) { continue; }
        let target = entry.file_name().into_string().unwrap();
        f(target);
    }
}

fn get_sysroot() -> PathBuf {
    let sysroot = std::env::var("MIRI_SYSROOT").unwrap_or_else(|_| {
        let sysroot = std::process::Command::new("rustc")
            .arg("--print")
            .arg("sysroot")
            .output()
            .expect("rustc not found")
            .stdout;
        String::from_utf8(sysroot).expect("sysroot is not utf8")
    });
    PathBuf::from(sysroot.trim())
}

fn get_host() -> String {
    let host = std::process::Command::new("rustc")
        .arg("-vV")
        .output()
        .expect("rustc not found for -vV")
        .stdout;
    let host = std::str::from_utf8(&host).expect("sysroot is not utf8");
    let host = host.split("\nhost: ").nth(1).expect("no host: part in rustc -vV");
    let host = host.split('\n').next().expect("no \n after host");
    String::from(host)
}

#[test]
fn run_pass_miri() {
    let sysroot = get_sysroot();
    let host = get_host();

    for &opt in [false, true].iter() {
        for_all_targets(&sysroot, |target| {
            miri_pass("tests/run-pass", &target, &host, false, opt);
        });
        miri_pass("tests/run-pass-fullmir", &host, &host, true, opt);
    }
}

#[test]
fn run_pass_rustc() {
    run_pass("tests/run-pass");
    run_pass("tests/run-pass-fullmir");
}

#[test]
fn compile_fail_miri() {
    let sysroot = get_sysroot();
    let host = get_host();

    for_all_targets(&sysroot, |target| {
        compile_fail(&sysroot, "tests/compile-fail", &target, &host, false);
    });
    compile_fail(&sysroot, "tests/compile-fail-fullmir", &host, &host, true);
}
<commit_msg>actually, we can use a plain constant<commit_after>#![feature(slice_concat_ext)]

extern crate compiletest_rs as compiletest;

use std::slice::SliceConcatExt;
use std::path::{PathBuf, Path};
use std::io::Write;

macro_rules! eprintln {
    ($($arg:tt)*) => {
        let stderr = std::io::stderr();
        writeln!(stderr.lock(), $($arg)*).unwrap();
    }
}

const MIRI_PATH: &'static str = concat!("target/", env!("PROFILE"), "/miri");

fn compile_fail(sysroot: &Path, path: &str, target: &str, host: &str, fullmir: bool) {
    eprintln!("## Running compile-fail tests in {} against miri for target {}", path, target);
    let mut config = compiletest::default_config();
    config.mode = "compile-fail".parse().expect("Invalid mode");
    config.rustc_path = MIRI_PATH.into();
    if fullmir {
        if host != target {
            // skip fullmir on nonhost
            return;
        }
        let sysroot = Path::new(&std::env::var("HOME").unwrap()).join(".xargo").join("HOST");
        config.target_rustcflags = Some(format!("--sysroot {}", sysroot.to_str().unwrap()));
        config.src_base = PathBuf::from(path.to_string());
    } else {
        config.target_rustcflags = Some(format!("--sysroot {}", sysroot.to_str().unwrap()));
        config.src_base = PathBuf::from(path.to_string());
    }
    config.target = target.to_owned();
    compiletest::run_tests(&config);
}

fn run_pass(path: &str) {
    eprintln!("## Running run-pass tests in {} against rustc", path);
    let mut config = compiletest::default_config();
    config.mode = "run-pass".parse().expect("Invalid mode");
    config.src_base = PathBuf::from(path);
    config.target_rustcflags = Some("-Dwarnings".to_string());
    config.host_rustcflags = Some("-Dwarnings".to_string());
    compiletest::run_tests(&config);
}

fn miri_pass(path: &str, target: &str, host: &str, fullmir: bool, opt: bool) {
    let opt_str = if opt {
        " with optimizations"
    } else {
        ""
    };
    eprintln!("## Running run-pass tests in {} against miri for target {}{}", path, target, opt_str);
    let mut config = compiletest::default_config();
    config.mode = "mir-opt".parse().expect("Invalid mode");
    config.src_base = PathBuf::from(path);
    config.target = target.to_owned();
    config.host = host.to_owned();
    config.rustc_path = MIRI_PATH.into();
    let mut flags = Vec::new();
    if fullmir {
        if host != target {
            // skip fullmir on nonhost
            return;
        }
        let sysroot = Path::new(&std::env::var("HOME").unwrap()).join(".xargo").join("HOST");
        flags.push(format!("--sysroot {}", sysroot.to_str().unwrap()));
    }
    if opt {
        flags.push("-Zmir-opt-level=3".to_owned());
    } else {
        flags.push("-Zmir-opt-level=0".to_owned());
    }
    config.target_rustcflags = Some(flags.join(" "));
    // don't actually execute the final binary, it might be for other targets and we only care
    // about running miri, not the binary.
    config.runtool = Some("echo \"\" || ".to_owned());
    if target == host {
        std::env::set_var("MIRI_HOST_TARGET", "yes");
    }
    compiletest::run_tests(&config);
    std::env::set_var("MIRI_HOST_TARGET", "");
}

fn is_target_dir<P: Into<PathBuf>>(path: P) -> bool {
    let mut path = path.into();
    path.push("lib");
    path.metadata().map(|m| m.is_dir()).unwrap_or(false)
}

fn for_all_targets<F: FnMut(String)>(sysroot: &Path, mut f: F) {
    let target_dir = sysroot.join("lib").join("rustlib");
    for entry in std::fs::read_dir(target_dir).expect("invalid sysroot") {
        let entry = entry.unwrap();
        if !is_target_dir(entry.path()) { continue; }
        let target = entry.file_name().into_string().unwrap();
        f(target);
    }
}

fn get_sysroot() -> PathBuf {
    let sysroot = std::env::var("MIRI_SYSROOT").unwrap_or_else(|_| {
        let sysroot = std::process::Command::new("rustc")
            .arg("--print")
            .arg("sysroot")
            .output()
            .expect("rustc not found")
            .stdout;
        String::from_utf8(sysroot).expect("sysroot is not utf8")
    });
    PathBuf::from(sysroot.trim())
}

fn get_host() -> String {
    let host = std::process::Command::new("rustc")
        .arg("-vV")
        .output()
        .expect("rustc not found for -vV")
        .stdout;
    let host = std::str::from_utf8(&host).expect("sysroot is not utf8");
    let host = host.split("\nhost: ").nth(1).expect("no host: part in rustc -vV");
    let host = host.split('\n').next().expect("no \n after host");
    String::from(host)
}

#[test]
fn run_pass_miri() {
    let sysroot = get_sysroot();
    let host = get_host();

    for &opt in [false, true].iter() {
        for_all_targets(&sysroot, |target| {
            miri_pass("tests/run-pass", &target, &host, false, opt);
        });
        miri_pass("tests/run-pass-fullmir", &host, &host, true, opt);
    }
}

#[test]
fn run_pass_rustc() {
    run_pass("tests/run-pass");
    run_pass("tests/run-pass-fullmir");
}

#[test]
fn compile_fail_miri() {
    let sysroot = get_sysroot();
    let host = get_host();

    for_all_targets(&sysroot, |target| {
        compile_fail(&sysroot, "tests/compile-fail", &target, &host, false);
    });
    compile_fail(&sysroot, "tests/compile-fail-fullmir", &host, &host, true);
}
<|endoftext|>


<commit_before><commit_msg>add tests<commit_after>// run-pass

// Test copy

#![feature(bindings_after_at)]

struct A { a: i32, b: i32 }
struct B { a: i32, b: C }
struct D { a: i32, d: C }
#[derive(Copy,Clone)]
struct C { c: i32 }

pub fn main() {
    match (A {a: 10, b: 20}) {
        x@A {a, b: 20} => { assert!(x.a == 10); assert!(a == 10); }
        A {b: _b, ..} => { panic!(); }
    }

    let mut x@B {b, ..} = B {a: 10, b: C {c: 20}};
    assert_eq!(x.a, 10);
    x.b.c = 30;
    assert_eq!(b.c, 20);
    let mut y@D {d, ..} = D {a: 10, d: C {c: 20}};
    assert_eq!(y.a, 10);
    y.d.c = 30;
    assert_eq!(d.c, 20);

    let some_b = Some(B { a: 10, b: C { c: 20 } });

    // in irrefutable pattern
    if let Some(x @ B { b, .. }) = some_b {
        assert_eq!(x.b.c, 20);
        assert_eq!(b.c, 20);
    } else {
        unreachable!();
    }

    let some_b = Some(B { a: 10, b: C { c: 20 } });

    if let Some(x @ B { b: mut b @ C { c }, .. }) = some_b {
        assert_eq!(x.b.c, 20);
        assert_eq!(b.c, 20);
        b.c = 30;
        assert_eq!(b.c, 30);
        assert_eq!(c, 20);
    } else {
        unreachable!();
    }
}
<|endoftext|>


<commit_before>fn main() {
    fn baz(_x: fn() -> int) {}
    for baz |_e| { } //~ ERROR should return `bool`
}
<commit_msg>Fix busted test case<commit_after>fn main() {
    fn baz(_x: fn(y: int) -> int) {}
    for baz |_e| { } //~ ERROR should return `bool`
}
<|endoftext|>


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

#![feature(rustc_attrs)]

macro_rules! mac {
    {} => {
        #[cfg(attr)]
        mod m {
            #[lang_item]
            fn f() {}
        }
    }
}

mac! {}

#[rustc_error]
fn main() {} //~ ERROR compilation successful
<|endoftext|>


<commit_before><commit_msg>Implements operations suitable on primitive integer types.<commit_after>// Copyright 2015 Pierre Talbot (IRCAM)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use ncollections::ops::*;
use num::One;

macro_rules! integer_basic_ops_impl
{
  ( $( $source:ty, $size:ty ),* ) =>
  {$(
    impl Cardinality for $source
    {
      type Size = $size;
      fn size(&self) -> $size {
        <$size as One>::one()
      }
    }

    impl Singleton<$source> for $source {
      fn singleton(value: $source) -> $source {
        value
      }
    }

    impl Bounded for $source {
      type Bound = $source;
      fn lower(&self) -> $source {
        *self
      }
      fn upper(&self) -> $source {
        *self
      }
    }

    impl Contains<$source> for $source
    {
      fn contains(&self, value: &$source) -> bool {
        self == value
      }
    }

    impl Disjoint for $source
    {
      fn is_disjoint(&self, value: &$source) -> bool {
        self != value
      }
    }

    impl Subset for $source
    {
      fn is_subset(&self, value: &$source) -> bool {
        self == value
      }
    }

    impl ProperSubset for $source
    {
      fn is_proper_subset(&self, _value: &$source) -> bool {
        false
      }
    }

    impl Overlap for $source
    {
      fn overlap(&self, value: &$source) -> bool {
        self == value
      }
    }
  )*}
}

integer_basic_ops_impl!(i8,u8,u8,u8,i16,u16,u16,u16,i32,u32,u32,u32,i64,u64,u64,u64,isize,usize,usize,usize);

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

  #[test]
  fn simple_tests() {
    for ref i in -2i32..10 {
      assert_eq!(i.size(), 1u32);
      assert_eq!(i.is_singleton(), true);
      assert_eq!(i.is_empty(), false);
      let res: i32 = Singleton::singleton(*i);
      assert_eq!(res, *i);
      assert_eq!(i.lower(), *i);
      assert_eq!(i.upper(), *i);
      for ref j in -10..10 {
        assert_eq!(i.contains(j), j.contains(i));
        assert_eq!(i.contains(j), i == j);
        assert_eq!(i.is_subset(j), i.contains(j));
        assert_eq!(i.overlap(j), i.contains(j));
        assert_eq!(i.is_subset(j), j.is_subset(i));

        assert_eq!(i.is_disjoint(j), j.is_disjoint(i));
        assert_eq!(i.is_disjoint(j), i != j);
        assert_eq!(i.is_proper_subset(j), false);
        assert_eq!(j.is_proper_subset(i), false);
      }
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>set output to mpg<commit_after><|endoftext|>


<commit_before><commit_msg>updated to check dirty file<commit_after><|endoftext|>


<commit_before><commit_msg>rust: initial implementation of Matrix and MatrixStack<commit_after>// Copyright (C) 2019 Inderjit Gill

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

struct Matrix {
    m: [f32; 16],
}

struct MatrixStack {
    stack: Vec<Matrix>,
}

impl Matrix {
    pub fn identity() -> Self {
        Matrix {
            m: [
                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
            ],
        }
    }

    pub fn copy_matrix(a: &Matrix) -> Self {
        Matrix { m: a.m }
    }

    pub fn copy_from(&mut self, a: &Matrix) {
        self.m = a.m;
    }

    // self = self * b
    pub fn multiply(&mut self, b: &Matrix) {
        let a00 = self.m[0];
        let a01 = self.m[1];
        let a02 = self.m[2];
        let a03 = self.m[3];
        let a10 = self.m[4];
        let a11 = self.m[5];
        let a12 = self.m[6];
        let a13 = self.m[7];
        let a20 = self.m[8];
        let a21 = self.m[9];
        let a22 = self.m[10];
        let a23 = self.m[11];
        let a30 = self.m[12];
        let a31 = self.m[13];
        let a32 = self.m[14];
        let a33 = self.m[15];

        {
            let b0 = b.m[0];
            let b1 = b.m[1];
            let b2 = b.m[2];
            let b3 = b.m[3];

            self.m[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
            self.m[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
            self.m[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
            self.m[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
        }

        {
            let b0 = b.m[4];
            let b1 = b.m[5];
            let b2 = b.m[6];
            let b3 = b.m[7];
            self.m[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
            self.m[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
            self.m[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
            self.m[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
        }
        {
            let b0 = b.m[8];
            let b1 = b.m[9];
            let b2 = b.m[10];
            let b3 = b.m[11];
            self.m[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
            self.m[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
            self.m[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
            self.m[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
        }
        {
            let b0 = b.m[12];
            let b1 = b.m[13];
            let b2 = b.m[14];
            let b3 = b.m[15];
            self.m[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
            self.m[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
            self.m[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
            self.m[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
        }
    }

    pub fn scale(&mut self, x: f32, y: f32, z: f32) {
        self.m[0] *= x;
        self.m[1] *= x;
        self.m[2] *= x;
        self.m[3] *= x;

        self.m[4] *= y;
        self.m[5] *= y;
        self.m[6] *= y;
        self.m[7] *= y;

        self.m[8] *= z;
        self.m[9] *= z;
        self.m[10] *= z;
        self.m[11] *= z;
    }

    pub fn translate(&mut self, x: f32, y: f32, z: f32) {
        self.m[12] = self.m[0] * x + self.m[4] * y + self.m[8] * z + self.m[12];
        self.m[13] = self.m[1] * x + self.m[5] * y + self.m[9] * z + self.m[13];
        self.m[14] = self.m[2] * x + self.m[6] * y + self.m[10] * z + self.m[14];
        self.m[15] = self.m[3] * x + self.m[7] * y + self.m[11] * z + self.m[15];
    }

    pub fn rotate_z(&mut self, rad: f32) {
        let s = rad.sin();
        let c = rad.cos();
        let a00 = self.m[0];
        let a01 = self.m[1];
        let a02 = self.m[2];
        let a03 = self.m[3];
        let a10 = self.m[4];
        let a11 = self.m[5];
        let a12 = self.m[6];
        let a13 = self.m[7];

        // Perform axis-specific matrix multiplication
        self.m[0] = a00 * c + a10 * s;
        self.m[1] = a01 * c + a11 * s;
        self.m[2] = a02 * c + a12 * s;
        self.m[3] = a03 * c + a13 * s;
        self.m[4] = a10 * c - a00 * s;
        self.m[5] = a11 * c - a01 * s;
        self.m[6] = a12 * c - a02 * s;
        self.m[7] = a13 * c - a03 * s;
    }

    pub fn transform_vec2(&self, x: f32, y: f32) -> (f32, f32) {
        let outx = self.m[0] * x + self.m[4] * y + self.m[12];
        let outy = self.m[1] * x + self.m[5] * y + self.m[13];
        (outx, outy)
    }

    pub fn transform_vec3(&self, x: f32, y: f32, z: f32) -> (f32, f32, f32) {
        let w1 = self.m[3] * x + self.m[7] * y + self.m[11] * z + self.m[15];
        let w = if w1 == 0.0 { 1.0 } else { w1 };

        let outx = (self.m[0] * x + self.m[4] * y + self.m[8] * z + self.m[12]) / w;
        let outy = (self.m[1] * x + self.m[5] * y + self.m[9] * z + self.m[13]) / w;
        let outz = (self.m[2] * x + self.m[6] * y + self.m[10] * z + self.m[14]) / w;

        (outx, outy, outz)
    }
}

impl MatrixStack {
    pub fn new() -> Self {
        let mut ms = MatrixStack {
            stack: Vec::with_capacity(16),
        };
        ms.reset();
        ms
    }

    pub fn reset(&mut self) {
        self.stack.clear();
        // add an identity matrix onto the stack so that further
        // scale/rotate/translate ops can work
        self.stack.push(Matrix::identity())
    }

    pub fn peek(&self) -> Option<&Matrix> {
        self.stack.last()
    }
    pub fn push(&mut self) {
        if let Some(top) = self.peek() {
            self.stack.push(Matrix::copy_matrix(top));
        }
    }
    pub fn pop(&mut self) -> Option<Matrix> {
        self.stack.pop()
    }

    pub fn scale(&mut self, sx: f32, sy: f32) {
        let mut m = Matrix::identity();
        m.scale(sx, sy, 1.0);

        let len = self.stack.len();
        self.stack[len - 1].multiply(&m);
    }

    pub fn translate(&mut self, tx: f32, ty: f32) {
        let mut m = Matrix::identity();
        m.translate(tx, ty, 0.0);

        let len = self.stack.len();
        self.stack[len - 1].multiply(&m);
    }

    pub fn rotate(&mut self, a: f32) {
        let mut m = Matrix::identity();
        m.rotate_z(a);

        let len = self.stack.len();
        self.stack[len - 1].multiply(&m);
    }

    // todo: should this return a Result? (and not the dodgy else clause)
    // is that too much of a performance hit?
    pub fn transform_vec2(&self, x: f32, y: f32) -> (f32, f32) {
        if let Some(top) = self.peek() {
            top.transform_vec2(x, y)
        } else {
            (x, y)
        }
    }

    // todo: should this return a Result? (and not the dodgy else clause)
    // is that too much of a performance hit?
    pub fn transform_vec3(&self, x: f32, y: f32, z: f32) -> (f32, f32, f32) {
        if let Some(top) = self.peek() {
            top.transform_vec3(x, y, z)
        } else {
            (x, y, z)
        }
    }
}
<|endoftext|>


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


<commit_before><commit_msg>Added a speed test example to help see the differences between various speeds<commit_after>extern crate turtle;

use turtle::Turtle;

/// This program draws several parallel lines to demonstrate each of the
/// different possible movement speeds
fn main() {
    let mut turtle = Turtle::new();

    turtle.pen_up();
    turtle.set_speed("fastest");
    turtle.left(90.0);
    turtle.forward(300.0);
    turtle.right(90.0);
    turtle.pen_down();

    let length = 200.0;

    for i in 1..12 {
        turtle.set_speed(i);
        turtle.forward(length);

        turtle.pen_up();
        turtle.set_speed("fastest");
        turtle.backward(length);
        turtle.right(90.0);
        turtle.forward(60.0);
        turtle.left(90.0);
        turtle.pen_down();
    }
}
<|endoftext|>