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

#![allow(bad_style, raw_pointer_derive)]

#[macro_use] mod macros;

#[repr(u8)]
pub enum c_void {
    __variant1,
    __variant2,
}

pub type int8_t = i8;
pub type int16_t = i16;
pub type int32_t = i32;
pub type int64_t = i64;
pub type uint8_t = u8;
pub type uint16_t = u16;
pub type uint32_t = u32;
pub type uint64_t = u64;

pub enum FILE {}
pub enum fpos_t {}
pub enum DIR {}
pub enum dirent {}

cfg_if! {
    if #[cfg(any(target_os = "macos", target_os = "ios"))] {
        mod apple;
        pub use apple::*;
    } else if #[cfg(any(target_os = "openbsd", target_os = "netbsd",
                        target_os = "dragonfly"))] {
        mod openbsdlike;
        pub use openbsdlike::*;
    } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] {
        mod freebsdlike;
        pub use freebsdlike::*;
    } else if #[cfg(any(target_os = "android", target_os = "linux"))] {
        mod linuxlike;
        pub use linuxlike::*;
    } else if #[cfg(windows)] {
        mod windows;
        pub use windows::*;
    } else {
        // ...
    }
}

#[cfg(unix)] mod unix;
#[cfg(unix)] pub use unix::*;

cfg_if! {
    if #[cfg(any(target_os = "macos",
                 target_os = "ios",
                 target_os = "freebsd",
                 target_os = "dragonfly",
                 target_os = "bitrig",
                 target_os = "netbsd",
                 target_os = "openbsd"))] {
        extern {
            pub fn sysctl(name: *mut c_int,
                          namelen: c_uint,
                          oldp: *mut c_void,
                          oldlenp: *mut size_t,
                          newp: *mut c_void,
                          newlen: size_t)
                          -> c_int;
            pub fn mincore(addr: *const c_void, len: size_t, vec: *mut c_char)
                           -> c_int;
            pub fn sysctlbyname(name: *const c_char,
                                oldp: *mut c_void,
                                oldlenp: *mut size_t,
                                newp: *mut c_void,
                                newlen: size_t)
                                -> c_int;
            pub fn sysctlnametomib(name: *const c_char,
                                   mibp: *mut c_int,
                                   sizep: *mut size_t)
                                   -> c_int;
        }
    } else {
        extern {
            pub fn sysctl(name: *mut c_int,
                          namelen: c_int,
                          oldp: *mut c_void,
                          oldlenp: *mut size_t,
                          newp: *mut c_void,
                          newlen: size_t)
                          -> c_int;
            pub fn mincore(addr: *mut c_void, len: size_t, vec: *mut c_uchar)
                           -> c_int;
        }
    }
}

extern {
    pub fn isalnum(c: c_int) -> c_int;
    pub fn isalpha(c: c_int) -> c_int;
    pub fn iscntrl(c: c_int) -> c_int;
    pub fn isdigit(c: c_int) -> c_int;
    pub fn isgraph(c: c_int) -> c_int;
    pub fn islower(c: c_int) -> c_int;
    pub fn isprint(c: c_int) -> c_int;
    pub fn ispunct(c: c_int) -> c_int;
    pub fn isspace(c: c_int) -> c_int;
    pub fn isupper(c: c_int) -> c_int;
    pub fn isxdigit(c: c_int) -> c_int;
    pub fn tolower(c: c_int) -> c_int;
    pub fn toupper(c: c_int) -> c_int;

    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "fopen$UNIX2003")]
    pub fn fopen(filename: *const c_char,
                 mode: *const c_char) -> *mut FILE;
    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "freopen$UNIX2003")]
    pub fn freopen(filename: *const c_char, mode: *const c_char,
                   file: *mut FILE)
                   -> *mut FILE;
    pub fn fflush(file: *mut FILE) -> c_int;
    pub fn fclose(file: *mut FILE) -> c_int;
    pub fn remove(filename: *const c_char) -> c_int;
    pub fn rename(oldname: *const c_char,
                  newname: *const c_char) -> c_int;
    pub fn tmpfile() -> *mut FILE;
    pub fn setvbuf(stream: *mut FILE,
                   buffer: *mut c_char,
                   mode: c_int,
                   size: size_t)
                   -> c_int;
    pub fn setbuf(stream: *mut FILE, buf: *mut c_char);
    // Omitted: printf and scanf variants.
    pub fn fgetc(stream: *mut FILE) -> c_int;
    pub fn fgets(buf: *mut c_char, n: c_int, stream: *mut FILE)
                 -> *mut c_char;
    pub fn fputc(c: c_int, stream: *mut FILE) -> c_int;
    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "fputs$UNIX2003")]
    pub fn fputs(s: *const c_char, stream: *mut FILE)-> c_int;
    pub fn puts(s: *const c_char) -> c_int;
    pub fn ungetc(c: c_int, stream: *mut FILE) -> c_int;
    pub fn fread(ptr: *mut c_void,
                 size: size_t,
                 nobj: size_t,
                 stream: *mut FILE)
                 -> size_t;
    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "fwrite$UNIX2003")]
    pub fn fwrite(ptr: *const c_void,
                  size: size_t,
                  nobj: size_t,
                  stream: *mut FILE)
                  -> size_t;
    pub fn fseek(stream: *mut FILE, offset: c_long, whence: c_int)
                 -> c_int;
    pub fn ftell(stream: *mut FILE) -> c_long;
    pub fn rewind(stream: *mut FILE);
    pub fn fgetpos(stream: *mut FILE, ptr: *mut fpos_t) -> c_int;
    pub fn fsetpos(stream: *mut FILE, ptr: *const fpos_t) -> c_int;
    pub fn feof(stream: *mut FILE) -> c_int;
    pub fn ferror(stream: *mut FILE) -> c_int;
    pub fn perror(s: *const c_char);
    pub fn abs(i: c_int) -> c_int;
    pub fn labs(i: c_long) -> c_long;
    pub fn atof(s: *const c_char) -> c_double;
    pub fn atoi(s: *const c_char) -> c_int;
    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "strtod$UNIX2003")]
    pub fn strtod(s: *const c_char,
                  endp: *mut *mut c_char) -> c_double;
    pub fn strtol(s: *const c_char,
                  endp: *mut *mut c_char, base: c_int) -> c_long;
    pub fn strtoul(s: *const c_char, endp: *mut *mut c_char,
                   base: c_int) -> c_ulong;
    pub fn calloc(nobj: size_t, size: size_t) -> *mut c_void;
    pub fn malloc(size: size_t) -> *mut c_void;
    pub fn realloc(p: *mut c_void, size: size_t) -> *mut c_void;
    pub fn free(p: *mut c_void);
    pub fn exit(status: c_int) -> !;
    pub fn _exit(status: c_int) -> !;
    pub fn atexit(cb: extern fn()) -> c_int;
    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "system$UNIX2003")]
    pub fn system(s: *const c_char) -> c_int;
    pub fn getenv(s: *const c_char) -> *mut c_char;
    pub fn rand() -> c_int;
    pub fn srand(seed: c_uint);

    pub fn strcpy(dst: *mut c_char, src: *const c_char) -> *mut c_char;
    pub fn strncpy(dst: *mut c_char, src: *const c_char, n: size_t)
                   -> *mut c_char;
    pub fn strcat(s: *mut c_char, ct: *const c_char) -> *mut c_char;
    pub fn strncat(s: *mut c_char, ct: *const c_char, n: size_t) -> *mut c_char;
    pub fn strcmp(cs: *const c_char, ct: *const c_char) -> c_int;
    pub fn strncmp(cs: *const c_char, ct: *const c_char, n: size_t) -> c_int;
    pub fn strcoll(cs: *const c_char, ct: *const c_char) -> c_int;
    pub fn strchr(cs: *const c_char, c: c_int) -> *mut c_char;
    pub fn strrchr(cs: *const c_char, c: c_int) -> *mut c_char;
    pub fn strspn(cs: *const c_char, ct: *const c_char) -> size_t;
    pub fn strcspn(cs: *const c_char, ct: *const c_char) -> size_t;
    pub fn strpbrk(cs: *const c_char, ct: *const c_char) -> *mut c_char;
    pub fn strstr(cs: *const c_char, ct: *const c_char) -> *mut c_char;
    pub fn strlen(cs: *const c_char) -> size_t;
    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "strerror$UNIX2003")]
    pub fn strerror(n: c_int) -> *mut c_char;
    pub fn strtok(s: *mut c_char, t: *const c_char) -> *mut c_char;
    pub fn strxfrm(s: *mut c_char, ct: *const c_char, n: size_t) -> size_t;
    pub fn wcslen(buf: *const wchar_t) -> size_t;

    pub fn memcmp(cx: *const c_void, ct: *const c_void, n: size_t) -> c_int;
    pub fn memchr(cx: *const c_void, c: c_int, n: size_t) -> *mut c_void;
}
<commit_msg>Remove now stray comment<commit_after>// Copyright 2012-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.

#![allow(bad_style, raw_pointer_derive)]

#[macro_use] mod macros;

#[repr(u8)]
pub enum c_void {
    __variant1,
    __variant2,
}

pub type int8_t = i8;
pub type int16_t = i16;
pub type int32_t = i32;
pub type int64_t = i64;
pub type uint8_t = u8;
pub type uint16_t = u16;
pub type uint32_t = u32;
pub type uint64_t = u64;

pub enum FILE {}
pub enum fpos_t {}
pub enum DIR {}
pub enum dirent {}

cfg_if! {
    if #[cfg(any(target_os = "macos", target_os = "ios"))] {
        mod apple;
        pub use apple::*;
    } else if #[cfg(any(target_os = "openbsd", target_os = "netbsd",
                        target_os = "dragonfly"))] {
        mod openbsdlike;
        pub use openbsdlike::*;
    } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] {
        mod freebsdlike;
        pub use freebsdlike::*;
    } else if #[cfg(any(target_os = "android", target_os = "linux"))] {
        mod linuxlike;
        pub use linuxlike::*;
    } else if #[cfg(windows)] {
        mod windows;
        pub use windows::*;
    } else {
        // ...
    }
}

#[cfg(unix)] mod unix;
#[cfg(unix)] pub use unix::*;

cfg_if! {
    if #[cfg(any(target_os = "macos",
                 target_os = "ios",
                 target_os = "freebsd",
                 target_os = "dragonfly",
                 target_os = "bitrig",
                 target_os = "netbsd",
                 target_os = "openbsd"))] {
        extern {
            pub fn sysctl(name: *mut c_int,
                          namelen: c_uint,
                          oldp: *mut c_void,
                          oldlenp: *mut size_t,
                          newp: *mut c_void,
                          newlen: size_t)
                          -> c_int;
            pub fn mincore(addr: *const c_void, len: size_t, vec: *mut c_char)
                           -> c_int;
            pub fn sysctlbyname(name: *const c_char,
                                oldp: *mut c_void,
                                oldlenp: *mut size_t,
                                newp: *mut c_void,
                                newlen: size_t)
                                -> c_int;
            pub fn sysctlnametomib(name: *const c_char,
                                   mibp: *mut c_int,
                                   sizep: *mut size_t)
                                   -> c_int;
        }
    } else {
        extern {
            pub fn sysctl(name: *mut c_int,
                          namelen: c_int,
                          oldp: *mut c_void,
                          oldlenp: *mut size_t,
                          newp: *mut c_void,
                          newlen: size_t)
                          -> c_int;
            pub fn mincore(addr: *mut c_void, len: size_t, vec: *mut c_uchar)
                           -> c_int;
        }
    }
}

extern {
    pub fn isalnum(c: c_int) -> c_int;
    pub fn isalpha(c: c_int) -> c_int;
    pub fn iscntrl(c: c_int) -> c_int;
    pub fn isdigit(c: c_int) -> c_int;
    pub fn isgraph(c: c_int) -> c_int;
    pub fn islower(c: c_int) -> c_int;
    pub fn isprint(c: c_int) -> c_int;
    pub fn ispunct(c: c_int) -> c_int;
    pub fn isspace(c: c_int) -> c_int;
    pub fn isupper(c: c_int) -> c_int;
    pub fn isxdigit(c: c_int) -> c_int;
    pub fn tolower(c: c_int) -> c_int;
    pub fn toupper(c: c_int) -> c_int;

    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "fopen$UNIX2003")]
    pub fn fopen(filename: *const c_char,
                 mode: *const c_char) -> *mut FILE;
    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "freopen$UNIX2003")]
    pub fn freopen(filename: *const c_char, mode: *const c_char,
                   file: *mut FILE)
                   -> *mut FILE;
    pub fn fflush(file: *mut FILE) -> c_int;
    pub fn fclose(file: *mut FILE) -> c_int;
    pub fn remove(filename: *const c_char) -> c_int;
    pub fn rename(oldname: *const c_char,
                  newname: *const c_char) -> c_int;
    pub fn tmpfile() -> *mut FILE;
    pub fn setvbuf(stream: *mut FILE,
                   buffer: *mut c_char,
                   mode: c_int,
                   size: size_t)
                   -> c_int;
    pub fn setbuf(stream: *mut FILE, buf: *mut c_char);
    pub fn fgetc(stream: *mut FILE) -> c_int;
    pub fn fgets(buf: *mut c_char, n: c_int, stream: *mut FILE)
                 -> *mut c_char;
    pub fn fputc(c: c_int, stream: *mut FILE) -> c_int;
    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "fputs$UNIX2003")]
    pub fn fputs(s: *const c_char, stream: *mut FILE)-> c_int;
    pub fn puts(s: *const c_char) -> c_int;
    pub fn ungetc(c: c_int, stream: *mut FILE) -> c_int;
    pub fn fread(ptr: *mut c_void,
                 size: size_t,
                 nobj: size_t,
                 stream: *mut FILE)
                 -> size_t;
    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "fwrite$UNIX2003")]
    pub fn fwrite(ptr: *const c_void,
                  size: size_t,
                  nobj: size_t,
                  stream: *mut FILE)
                  -> size_t;
    pub fn fseek(stream: *mut FILE, offset: c_long, whence: c_int)
                 -> c_int;
    pub fn ftell(stream: *mut FILE) -> c_long;
    pub fn rewind(stream: *mut FILE);
    pub fn fgetpos(stream: *mut FILE, ptr: *mut fpos_t) -> c_int;
    pub fn fsetpos(stream: *mut FILE, ptr: *const fpos_t) -> c_int;
    pub fn feof(stream: *mut FILE) -> c_int;
    pub fn ferror(stream: *mut FILE) -> c_int;
    pub fn perror(s: *const c_char);
    pub fn abs(i: c_int) -> c_int;
    pub fn labs(i: c_long) -> c_long;
    pub fn atof(s: *const c_char) -> c_double;
    pub fn atoi(s: *const c_char) -> c_int;
    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "strtod$UNIX2003")]
    pub fn strtod(s: *const c_char,
                  endp: *mut *mut c_char) -> c_double;
    pub fn strtol(s: *const c_char,
                  endp: *mut *mut c_char, base: c_int) -> c_long;
    pub fn strtoul(s: *const c_char, endp: *mut *mut c_char,
                   base: c_int) -> c_ulong;
    pub fn calloc(nobj: size_t, size: size_t) -> *mut c_void;
    pub fn malloc(size: size_t) -> *mut c_void;
    pub fn realloc(p: *mut c_void, size: size_t) -> *mut c_void;
    pub fn free(p: *mut c_void);
    pub fn exit(status: c_int) -> !;
    pub fn _exit(status: c_int) -> !;
    pub fn atexit(cb: extern fn()) -> c_int;
    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "system$UNIX2003")]
    pub fn system(s: *const c_char) -> c_int;
    pub fn getenv(s: *const c_char) -> *mut c_char;
    pub fn rand() -> c_int;
    pub fn srand(seed: c_uint);

    pub fn strcpy(dst: *mut c_char, src: *const c_char) -> *mut c_char;
    pub fn strncpy(dst: *mut c_char, src: *const c_char, n: size_t)
                   -> *mut c_char;
    pub fn strcat(s: *mut c_char, ct: *const c_char) -> *mut c_char;
    pub fn strncat(s: *mut c_char, ct: *const c_char, n: size_t) -> *mut c_char;
    pub fn strcmp(cs: *const c_char, ct: *const c_char) -> c_int;
    pub fn strncmp(cs: *const c_char, ct: *const c_char, n: size_t) -> c_int;
    pub fn strcoll(cs: *const c_char, ct: *const c_char) -> c_int;
    pub fn strchr(cs: *const c_char, c: c_int) -> *mut c_char;
    pub fn strrchr(cs: *const c_char, c: c_int) -> *mut c_char;
    pub fn strspn(cs: *const c_char, ct: *const c_char) -> size_t;
    pub fn strcspn(cs: *const c_char, ct: *const c_char) -> size_t;
    pub fn strpbrk(cs: *const c_char, ct: *const c_char) -> *mut c_char;
    pub fn strstr(cs: *const c_char, ct: *const c_char) -> *mut c_char;
    pub fn strlen(cs: *const c_char) -> size_t;
    #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
               link_name = "strerror$UNIX2003")]
    pub fn strerror(n: c_int) -> *mut c_char;
    pub fn strtok(s: *mut c_char, t: *const c_char) -> *mut c_char;
    pub fn strxfrm(s: *mut c_char, ct: *const c_char, n: size_t) -> size_t;
    pub fn wcslen(buf: *const wchar_t) -> size_t;

    pub fn memcmp(cx: *const c_void, ct: *const c_void, n: size_t) -> c_int;
    pub fn memchr(cx: *const c_void, c: c_int, n: size_t) -> *mut c_void;
}
<|endoftext|>


<commit_before><commit_msg>Created lib.rs.<commit_after>extern crate nom;
<|endoftext|>


<commit_before><commit_msg>Implemented the Lights::get_all_lights() function.<commit_after><|endoftext|>


<commit_before><commit_msg>Implemented UI drawing<commit_after><|endoftext|>


<commit_before><commit_msg>start working on persistence<commit_after>use std::cell::RefCell;

pub struct tdolist {
    table: bool,
    tick: bool,
    global_id: u32,
    categories: RefCell<Vec<category>>
}

pub struct category {
    name: String,
    todos: RefCell<Vec<todo>>,
}

pub struct todo {
    id: u32,
    todo_text: String,
    done: bool,
}

impl todo {
    pub fn new(list: tdolist, todo_text: String, category_str: String) -> Result< (), &'static str> {
        let id = get_id();

        let mut exists: bool = false;
        let mut in_category: category;
            for x in list.categories.borrow_mut().iter() {
                if category_str.to_lowercase() == x.name.to_lowercase() {
                    let exists = true;
                    let in_category = x;
                    break;
                }
            }

        if !exists {
            Err("Category does not exist.")
        } else {
            let result = todo {
                id: id,
                todo_text: todo_text,
                done: false,
            };
            in_category.todos.borrow_mut().push(result);
            Ok(())
        }
    }
}

fn get_id() -> u32 {
    1
}
<|endoftext|>


<commit_before><commit_msg>fix tests in peg.rs (#185)<commit_after><|endoftext|>


<commit_before><commit_msg>Add some docs<commit_after><|endoftext|>


<commit_before><commit_msg>Adds copy creator.<commit_after><|endoftext|>


<commit_before><commit_msg>libimagnotes: Replace read with typed read<commit_after><|endoftext|>


<commit_before><commit_msg>An example using pipes with most of the synchronization code in place.<commit_after>/*
The first test case using pipes. The idea is to break this into
several stages for prototyping. Here's the plan:

1. Write an already-compiled protocol using existing ports and chans.

2. Take the already-compiled version and add the low-level
synchronization code instead. (That's what this file attempts to do)

3. Write a syntax extension to compile the protocols.

At some point, we'll need to add support for select.

*/

// Hopefully someday we'll move this into core.
mod pipes {
    import unsafe::{forget, reinterpret_cast};

    enum state {
        empty,
        full,
        blocked,
        terminated
    }

    type packet<T: send> = {
        mut state: state,
        mut blocked_task: option<task::task>,
        mut payload: option<T>
    };

    fn packet<T: send>() -> *packet<T> unsafe {
        let p: *packet<T> = unsafe::transmute(~{
            mut state: empty,
            mut blocked_task: none::<task::task>,
            mut payload: none::<T>
        });
        p
    }

    #[abi = "rust-intrinsic"]
    native mod rusti {
        fn atomic_xchng(&dst: int, src: int) -> int;
        fn atomic_xchng_acq(&dst: int, src: int) -> int;
        fn atomic_xchng_rel(&dst: int, src: int) -> int;
    }

    // We should consider moving this to core::unsafe, although I
    // suspect graydon would want us to use void pointers instead.
    unsafe fn uniquify<T>(x: *T) -> ~T {
        unsafe { unsafe::reinterpret_cast(x) }
    }

    fn swap_state_acq(&dst: state, src: state) -> state {
        unsafe {
            reinterpret_cast(rusti::atomic_xchng_acq(
                *(ptr::mut_addr_of(dst) as *mut int),
                src as int))
        }
    }

    fn swap_state_rel(&dst: state, src: state) -> state {
        unsafe {
            reinterpret_cast(rusti::atomic_xchng_rel(
                *(ptr::mut_addr_of(dst) as *mut int),
                src as int))
        }
    }

    fn send<T: send>(p: *packet<T>, -payload: T) {
        let p = unsafe { uniquify(p) };
        assert (*p).payload == none;
        (*p).payload <- some(payload);
        let old_state = swap_state_rel((*p).state, full);
        alt old_state {
          empty {
            // Yay, fastpath.

            // The receiver will eventually clean this up.
            unsafe { forget(p); }
          }
          full { fail "duplicate send" }
          blocked {
            // FIXME: once the target will actually block, tell the
            // scheduler to wake it up.

            // The receiver will eventually clean this up.
            unsafe { forget(p); }
          }
          terminated {
            // The receiver will never receive this. Rely on drop_glue
            // to clean everything up.
          }
        }
    }

    fn recv<T: send>(p: *packet<T>) -> option<T> {
        let p = unsafe { uniquify(p) };
        loop {
            let old_state = swap_state_acq((*p).state,
                                           blocked);
            alt old_state {
              empty | blocked { task::yield(); }
              full {
                let mut payload = none;
                payload <-> (*p).payload;
                ret some(option::unwrap(payload))
              }
              terminated {
                assert old_state == terminated;
                ret none;
              }
            }
        }
    }

    fn sender_terminate<T: send>(p: *packet<T>) {
        let p = unsafe { uniquify(p) };
        alt swap_state_rel((*p).state, terminated) {
          empty | blocked {
            // The receiver will eventually clean up.
            unsafe { forget(p) }
          }
          full {
            // This is impossible
            fail "you dun goofed"
          }
          terminated {
            // I have to clean up, use drop_glue
          }
        }
    }

    fn receiver_terminate<T: send>(p: *packet<T>) {
        let p = unsafe { uniquify(p) };
        alt swap_state_rel((*p).state, terminated) {
          empty {
            // the sender will clean up
            unsafe { forget(p) }
          }
          blocked {
            // this shouldn't happen.
            fail "terminating a blocked packet"
          }
          terminated | full {
            // I have to clean up, use drop_glue
          }
        }
    }
}

mod pingpong {
    enum ping = *pipes::packet<pong>;
    enum pong = *pipes::packet<ping>;

    fn init() -> (client::ping, server::ping) {
        let p = pipes::packet();
        let p = pingpong::ping(p);

        let client = client::ping(p);
        let server = server::ping(p);

        (client, server)
    }

    mod client {
        enum ping = pingpong::ping;
        enum pong = pingpong::pong;

        fn do_ping(-c: ping) -> pong {
            let packet = pipes::packet();
            let packet = pingpong::pong(packet);

            pipes::send(**c, copy packet);
            pong(packet)
        }

        fn do_pong(-c: pong) -> (ping, ()) {
            let packet = pipes::recv(**c);
            alt packet {
              none {
                fail "sender closed the connection"
              }
              some(new_packet) {
                (ping(new_packet), ())
              }
            }
        }
    }

    mod server {
        enum ping = pingpong::ping;
        enum pong = pingpong::pong;

        fn do_ping(-c: ping) -> (pong, ()) {
            let packet = pipes::recv(**c);
            alt packet {
              none { fail "sender closed the connection" }
              some(new_packet) {
                (pong(new_packet), ())
              }
            }
        }

        fn do_pong(-c: pong) -> ping {
            let packet = pipes::packet();
            let packet = pingpong::ping(packet);

            pipes::send(**c, copy packet);
            ping(packet)
        }
    }
}

fn client(-chan: pingpong::client::ping) {
    let chan = pingpong::client::do_ping(chan);
    log(error, "Sent ping");
    let (chan, _data) = pingpong::client::do_pong(chan);
    log(error, "Received pong");
    pipes::sender_terminate(**chan);
}

fn server(-chan: pingpong::server::ping) {
    let (chan, _data) = pingpong::server::do_ping(chan);
    log(error, "Received ping");
    let chan = pingpong::server::do_pong(chan);
    log(error, "Sent pong");
    pipes::receiver_terminate(**chan);
}

fn main() {
    let (client_, server_) = pingpong::init();
    let client_ = ~mut some(client_);
    let server_ = ~mut some(server_);

    task::spawn {|move client_|
        let mut client__ = none;
        *client_ <-> client__;
        client(option::unwrap(client__));
    };
    task::spawn {|move server_|
        let mut server_ˊ = none;
        *server_ <-> server_ˊ;
        server(option::unwrap(server_ˊ));
    };
}
<|endoftext|>


<commit_before><commit_msg>test: Add a test for vector reference counts, XFAIL'd in rustc<commit_after>// xfail-stage0

use std;
import std._vec;

fn main() {
    auto v = vec(1, 2, 3);
    check (_vec.refcount[int](v) == 1u);
    check (_vec.refcount[int](v) == 1u);
}

<|endoftext|>


<commit_before><commit_msg>Add a Monte-Carlo integration test<commit_after>/*
 * Cymbalum, Molecular Simulation in Rust
 * Copyright (C) 2015 Guillaume Fraux
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
//! Testing physical properties of a Lennard-Jones gaz of Helium using
//! Monte-Carlo simulation
extern crate cymbalum;
use self::cymbalum::*;

use std::sync::{Once, ONCE_INIT};
static START: Once = ONCE_INIT;

use std::path::Path;

fn get_universe() -> Universe {
    let data_dir = Path::new(file!()).parent().unwrap();
    let configuration = data_dir.join("data").join("helium.xyz");
    let mut universe = Universe::from_file(configuration.to_str().unwrap()).unwrap();
    universe.set_cell(UnitCell::cubic(10.0));

    let mut velocities = BoltzmanVelocities::new(units::from(300.0, "K").unwrap());
    velocities.init(&mut universe);

    universe.add_pair_interaction("He", "He",
        Box::new(LennardJones{
            sigma: units::from(2.0, "A").unwrap(),
            epsilon: units::from(0.2, "kJ/mol").unwrap()
        })
    );

    return universe;
}

#[test]
fn perfect_gaz() {
    START.call_once(|| {Logger::stdout();});
    let mut universe = get_universe();
    let mut mc = MonteCarlo::new(units::from(300.0, "K").unwrap());
    mc.add(Box::new(Translate::new(units::from(3.0, "A").unwrap())), 1.0);
    let mut simulation = Simulation::new(mc);

    // dilating the universe!
    for particle in universe.iter_mut() {
        particle.position = 10.0 * particle.position;
    }
    universe.set_cell(UnitCell::cubic(100.0));

    simulation.run(&mut universe, 5000);
    let pressure = universe.pressure();
    let volume = universe.volume();
    let temperature = universe.temperature();
    let n = universe.size() as f64;

    assert!(f64::abs(pressure * volume - n * constants::K_BOLTZMANN * temperature) < 1e-3);
}
<|endoftext|>


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

use deriving::generic::*;
use deriving::generic::ty::*;

use syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::{Span, respan, DUMMY_SP};
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax::parse::token;
use syntax::ptr::P;

pub fn expand_deriving_debug(cx: &mut ExtCtxt,
                            span: Span,
                            mitem: &MetaItem,
                            item: &Annotatable,
                            push: &mut FnMut(Annotatable))
{
    // &mut ::std::fmt::Formatter
    let fmtr = Ptr(Box::new(Literal(path_std!(cx, core::fmt::Formatter))),
                   Borrowed(None, ast::Mutability::Mutable));

    let trait_def = TraitDef {
        span: span,
        attributes: Vec::new(),
        path: path_std!(cx, core::fmt::Debug),
        additional_bounds: Vec::new(),
        generics: LifetimeBounds::empty(),
        is_unsafe: false,
        methods: vec![
            MethodDef {
                name: "fmt",
                generics: LifetimeBounds::empty(),
                explicit_self: borrowed_explicit_self(),
                args: vec!(fmtr),
                ret_ty: Literal(path_std!(cx, core::fmt::Result)),
                attributes: Vec::new(),
                is_unsafe: false,
                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                    show_substructure(a, b, c)
                }))
            }
        ],
        associated_types: Vec::new(),
    };
    trait_def.expand(cx, mitem, item, push)
}

/// We use the debug builders to do the heavy lifting here
fn show_substructure(cx: &mut ExtCtxt, span: Span,
                     substr: &Substructure) -> P<Expr> {
    // build fmt.debug_struct(<name>).field(<fieldname>, &<fieldval>)....build()
    // or fmt.debug_tuple(<name>).field(&<fieldval>)....build()
    // based on the "shape".
    let ident = match *substr.fields {
        Struct(..) => substr.type_ident,
        EnumMatching(_, v, _) => v.node.name,
        EnumNonMatchingCollapsed(..) | StaticStruct(..) | StaticEnum(..) => {
            cx.span_bug(span, "nonsensical .fields in `#[derive(Debug)]`")
        }
    };

    // We want to make sure we have the expn_id set so that we can use unstable methods
    let span = Span { expn_id: cx.backtrace(), .. span };
    let name = cx.expr_lit(span, ast::LitKind::Str(ident.name.as_str(), ast::StrStyle::Cooked));
    let builder = token::str_to_ident("builder");
    let builder_expr = cx.expr_ident(span, builder.clone());

    let fmt = substr.nonself_args[0].clone();
    let is_struct = match *substr.fields {
        Struct(vdata, _) => vdata,
        EnumMatching(_, v, _) => &v.node.data,
        _ => unreachable!()
    }.is_struct();

    let stmts = match *substr.fields {
        Struct(_, ref fields) | EnumMatching(_, _, ref fields) => {
            let mut stmts = vec![];
            if !is_struct {
                // tuple struct/"normal" variant
                let expr = cx.expr_method_call(span,
                                               fmt,
                                               token::str_to_ident("debug_tuple"),
                                               vec![name]);
                stmts.push(cx.stmt_let(DUMMY_SP, true, builder, expr));

                for field in fields {
                    // Use double indirection to make sure this works for unsized types
                    let field = cx.expr_addr_of(field.span, field.self_.clone());
                    let field = cx.expr_addr_of(field.span, field);

                    let expr = cx.expr_method_call(span,
                                                   builder_expr.clone(),
                                                   token::str_to_ident("field"),
                                                   vec![field]);

                    // Use `let _ = expr;` to avoid triggering the
                    // unused_results lint.
                    stmts.push(stmt_let_undescore(cx, span, expr));
                }
            } else {
                // normal struct/struct variant
                let expr = cx.expr_method_call(span,
                                               fmt,
                                               token::str_to_ident("debug_struct"),
                                               vec![name]);
                stmts.push(cx.stmt_let(DUMMY_SP, true, builder, expr));

                for field in fields {
                    let name = cx.expr_lit(field.span, ast::LitKind::Str(
                            field.name.unwrap().name.as_str(),
                            ast::StrStyle::Cooked));

                    // Use double indirection to make sure this works for unsized types
                    let field = cx.expr_addr_of(field.span, field.self_.clone());
                    let field = cx.expr_addr_of(field.span, field);
                    let expr = cx.expr_method_call(span,
                                                   builder_expr.clone(),
                                                   token::str_to_ident("field"),
                                                   vec![name, field]);
                    stmts.push(stmt_let_undescore(cx, span, expr));
                }
            }
            stmts
        }
        _ => unreachable!()
    };

    let expr = cx.expr_method_call(span,
                                   builder_expr,
                                   token::str_to_ident("finish"),
                                   vec![]);

    let block = cx.block(span, stmts, Some(expr));
    cx.expr_block(block)
}

fn stmt_let_undescore(cx: &mut ExtCtxt,
                      sp: Span,
                      expr: P<ast::Expr>) -> ast::Stmt {
    let local = P(ast::Local {
        pat: cx.pat_wild(sp),
        ty: None,
        init: Some(expr),
        id: ast::DUMMY_NODE_ID,
        span: sp,
        attrs: None,
    });
    let decl = respan(sp, ast::DeclKind::Local(local));
    respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID))
}
<commit_msg>Some refactoring in deriving/debug.rs<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.

use deriving::generic::*;
use deriving::generic::ty::*;

use syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::{Span, respan, DUMMY_SP};
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax::parse::token;
use syntax::ptr::P;

pub fn expand_deriving_debug(cx: &mut ExtCtxt,
                            span: Span,
                            mitem: &MetaItem,
                            item: &Annotatable,
                            push: &mut FnMut(Annotatable))
{
    // &mut ::std::fmt::Formatter
    let fmtr = Ptr(Box::new(Literal(path_std!(cx, core::fmt::Formatter))),
                   Borrowed(None, ast::Mutability::Mutable));

    let trait_def = TraitDef {
        span: span,
        attributes: Vec::new(),
        path: path_std!(cx, core::fmt::Debug),
        additional_bounds: Vec::new(),
        generics: LifetimeBounds::empty(),
        is_unsafe: false,
        methods: vec![
            MethodDef {
                name: "fmt",
                generics: LifetimeBounds::empty(),
                explicit_self: borrowed_explicit_self(),
                args: vec!(fmtr),
                ret_ty: Literal(path_std!(cx, core::fmt::Result)),
                attributes: Vec::new(),
                is_unsafe: false,
                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                    show_substructure(a, b, c)
                }))
            }
        ],
        associated_types: Vec::new(),
    };
    trait_def.expand(cx, mitem, item, push)
}

/// We use the debug builders to do the heavy lifting here
fn show_substructure(cx: &mut ExtCtxt, span: Span,
                     substr: &Substructure) -> P<Expr> {
    // build fmt.debug_struct(<name>).field(<fieldname>, &<fieldval>)....build()
    // or fmt.debug_tuple(<name>).field(&<fieldval>)....build()
    // based on the "shape".
    let (ident, is_struct) = match *substr.fields {
        Struct(vdata, _) => (substr.type_ident, vdata.is_struct()),
        EnumMatching(_, v, _) => (v.node.name, v.node.data.is_struct()),
        EnumNonMatchingCollapsed(..) | StaticStruct(..) | StaticEnum(..) => {
            cx.span_bug(span, "nonsensical .fields in `#[derive(Debug)]`")
        }
    };

    // We want to make sure we have the expn_id set so that we can use unstable methods
    let span = Span { expn_id: cx.backtrace(), .. span };
    let name = cx.expr_lit(span, ast::LitKind::Str(ident.name.as_str(), ast::StrStyle::Cooked));
    let builder = token::str_to_ident("builder");
    let builder_expr = cx.expr_ident(span, builder.clone());

    let fmt = substr.nonself_args[0].clone();

    let stmts = match *substr.fields {
        Struct(_, ref fields) | EnumMatching(_, _, ref fields) => {
            let mut stmts = vec![];
            if !is_struct {
                // tuple struct/"normal" variant
                let expr = cx.expr_method_call(span,
                                               fmt,
                                               token::str_to_ident("debug_tuple"),
                                               vec![name]);
                stmts.push(cx.stmt_let(DUMMY_SP, true, builder, expr));

                for field in fields {
                    // Use double indirection to make sure this works for unsized types
                    let field = cx.expr_addr_of(field.span, field.self_.clone());
                    let field = cx.expr_addr_of(field.span, field);

                    let expr = cx.expr_method_call(span,
                                                   builder_expr.clone(),
                                                   token::str_to_ident("field"),
                                                   vec![field]);

                    // Use `let _ = expr;` to avoid triggering the
                    // unused_results lint.
                    stmts.push(stmt_let_undescore(cx, span, expr));
                }
            } else {
                // normal struct/struct variant
                let expr = cx.expr_method_call(span,
                                               fmt,
                                               token::str_to_ident("debug_struct"),
                                               vec![name]);
                stmts.push(cx.stmt_let(DUMMY_SP, true, builder, expr));

                for field in fields {
                    let name = cx.expr_lit(field.span, ast::LitKind::Str(
                            field.name.unwrap().name.as_str(),
                            ast::StrStyle::Cooked));

                    // Use double indirection to make sure this works for unsized types
                    let field = cx.expr_addr_of(field.span, field.self_.clone());
                    let field = cx.expr_addr_of(field.span, field);
                    let expr = cx.expr_method_call(span,
                                                   builder_expr.clone(),
                                                   token::str_to_ident("field"),
                                                   vec![name, field]);
                    stmts.push(stmt_let_undescore(cx, span, expr));
                }
            }
            stmts
        }
        _ => unreachable!()
    };

    let expr = cx.expr_method_call(span,
                                   builder_expr,
                                   token::str_to_ident("finish"),
                                   vec![]);

    let block = cx.block(span, stmts, Some(expr));
    cx.expr_block(block)
}

fn stmt_let_undescore(cx: &mut ExtCtxt,
                      sp: Span,
                      expr: P<ast::Expr>) -> ast::Stmt {
    let local = P(ast::Local {
        pat: cx.pat_wild(sp),
        ty: None,
        init: Some(expr),
        id: ast::DUMMY_NODE_ID,
        span: sp,
        attrs: None,
    });
    let decl = respan(sp, ast::DeclKind::Local(local));
    respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID))
}
<|endoftext|>


<commit_before><commit_msg>(test) adding test for #433<commit_after>use handlebars::{Context, Handlebars, Helper, HelperDef, RenderContext, RenderError, ScopedJson};
use serde_json::json;

struct MyHelper;

impl HelperDef for MyHelper {
    fn call_inner<'reg: 'rc, 'rc>(
        &self,
        _: &Helper<'reg, 'rc>,
        _: &'reg Handlebars,
        _: &'rc Context,
        _: &mut RenderContext<'reg, 'rc>,
    ) -> Result<Option<ScopedJson<'reg, 'rc>>, RenderError> {
        Ok(Some(ScopedJson::Derived(json!({
            "a": 1,
            "b": 2,
        }))))
    }
}

#[test]
fn test_lookup_with_subexpression() {
    let mut registry = Handlebars::new();
    registry.register_helper("myhelper", Box::new(MyHelper {}));

    let result = registry
        .render_template("{{ lookup (myhelper) \"a\" }}", &json!({}))
        .unwrap();

    assert_eq!("1", result);
}
<|endoftext|>


<commit_before><commit_msg>Test + len<commit_after><|endoftext|>


<commit_before><commit_msg>Little change<commit_after><|endoftext|>


<commit_before><commit_msg>Better check for origin change<commit_after><|endoftext|>


<commit_before><commit_msg>add more info on Unpin and connect paragraphs better<commit_after><|endoftext|>


<commit_before><commit_msg>Call try less often on AREAS<commit_after><|endoftext|>


<commit_before><commit_msg>I think I might have finished 4?<commit_after><|endoftext|>


<commit_before><commit_msg>Add jit_macro again<commit_after>#![crate_id = "jit_macro"]
#![comment = "LibJIT Macro"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![feature(quote, globs, macro_registrar, managed_boxes)]
#![deny(non_uppercase_statics, missing_doc, unnecessary_parens, unrecognized_lint, unreachable_code, unnecessary_allocation, unnecessary_typecast, unnecessary_allocation, uppercase_variables, non_camel_case_types, unused_must_use)]
//! This crate provides a macro `jit_type` which can compile a Rust type
//! into its LibJIT counterpart. It even supports functions *and* structs!
//!
//! For example:
//!
//! ```rust
//! #![feature(phase)]
//! extern crate jit;
//! #[phase(syntax)]
//! extern crate jit_macro;
//! fn main() {
//! 	let ty = jit_type!(i64);
//! 	assert_eq(ty.get_size(), 8);
//! 	let floor_sig = jit_type!((f64) -> i32);
//! 	let double_array_ty = jit_type!({
//! 		len: int,
//! 		ptr: **f64
//! 	});
//! }
//! ```
extern crate syntax;
use syntax::ext::quote::rt::ToSource;
use syntax::ast::*;
use syntax::codemap::Span;
use syntax::ext::base::*;
use syntax::ext::build::AstBuilder;
use syntax::parse::token;
use syntax::parse::token::*;
use std::iter::Peekable;
use std::slice::Items;
#[macro_registrar]
#[doc(hidden)]
pub fn macro_registrar(register: |Name, SyntaxExtension|) {
	let expander = box BasicMacroExpander { expander: jit_type, span: None };
	register(token::intern("jit_type"), NormalTT(expander, None))
}
fn error(e:Option<TokenTree>, tok:Token) -> Result<(), String> {
	match e {
		Some(TTTok(_, ref got)) => Err(format!("Bad syntax - got {} but expected {}", got, tok)),
		Some(TTNonterminal(_, ref got)) => Err(format!("Bad syntax - got {} but expected {}", got, tok)),
		Some(TTDelim(ref trees)) => error(Some(trees.deref().get(0).clone()), tok),
		Some(_) => Err("Bad syntax".into_string()),
		None => Err("Abrupt end".into_string())
	}
}
fn expect<'a>(_: &mut ExtCtxt, tts:&mut Peekable<&'a TokenTree, Items<'a, TokenTree>>, tok:Token) -> Result<(), String> {
	match tts.next().map(|v| v.clone()) {
		Some(TTTok(_, ref got)) if *got == tok => {
			Ok(())
		},
		Some(TTDelim(ref trees)) => {
			let curr = trees.deref().get(0).clone();
			match curr {
				TTTok(_, ref got) if *got == tok =>
					Ok(()),
				TTTok(_, ref tok) =>
					Err(format!("Bad result {}", tok)),
				_ =>
					Err("Bad result".into_string())
			}
		},
		v => error(v, tok)
	}
}
fn jit_parse_type<'a>(cx: &mut ExtCtxt, tts:&mut Peekable<&'a TokenTree, Items<'a, TokenTree>>) -> Result<P<Expr>, String> {
	let val:Option<&TokenTree> = tts.peek().map(|v|*v);
	match val {
		Some(ref val) => {
			match **val {
				TTDelim(ref toks) => {
					match *toks.get(0) {
						TTTok(span, LPAREN) => {
							let toks = toks.slice(1, toks.len() - 1);
							if toks.len() == 0 {
								Ok(quote_expr!(cx, ::jit::Types::get_void()))
							} else {
								let mut arg_types : Vec<P<Expr>> = Vec::new();
								{
									let mut tts = toks.iter().peekable();
									loop {
										let parsed = try!(jit_parse_type(cx, &mut tts));
										arg_types.push(cx.expr_addr_of(parsed.span, parsed));
										match tts.next() {
											Some(v) =>
												match *v {
													TTTok(_, COMMA) => {
														continue;
													},
													_ => return Err("Unexpected token in function decl".into_string())
												},
											None => break
										}
									}
								}
								tts.next();
								try!(expect(cx, tts, RARROW));
								let parsed_ret = try!(jit_parse_type(cx, tts));
								let ret = cx.expr_addr_of(parsed_ret.span, parsed_ret);
								let arg_types_ex = cx.expr(span, ExprVec(arg_types));
								let func = quote_expr!(&mut*cx, ::jit::Type::create_signature);
								let cdecl = quote_expr!(&mut*cx, ::jit::CDECL);
								let arg_types_ex = cx.expr_mut_addr_of(arg_types_ex.span, arg_types_ex);
								let arg_types_ex = cx.expr_method_call(span, arg_types_ex, cx.ident_of("as_mut_slice"), vec!());
								let call = cx.expr_call(span, func, vec!(cdecl, ret, arg_types_ex));
								Ok(call)

							}
						},
						TTTok(span, LBRACE) => {
							let toks = toks.slice(1, toks.len() - 1);
							let mut tts = toks.iter().peekable();
							let mut names:Vec<P<Expr>> = Vec::new();
							let mut types:Vec<P<Expr>> = Vec::new();
							loop {
								match tts.next() {
									Some(ref v) => {
										match **v {
											TTTok(_, COMMA) =>
												continue,
											TTTok(span, IDENT(field_name, _)) => {
												try!(expect(cx, &mut tts, COLON));
												let field_type = try!(jit_parse_type(cx, &mut tts));
												names.push(cx.expr_method_call(span, cx.expr_str(span, get_ident(field_name)), cx.ident_of("into_string"), vec!()));
												types.push(cx.expr_addr_of(field_type.span, field_type));
											},
											_ => return Err("Expected ident".into_string())
										}
									},
									None => break
								}
							}
							let func = quote_expr!(&mut*cx, ::jit::Type::create_struct);
							let types_vec = cx.expr(span, ExprVec(types));
							let types_vec_slices = cx.expr_method_call(span, types_vec, cx.ident_of("as_mut_slice"), vec!());
							let names_vec = cx.expr(span, ExprVec(names));
							let ident_type = cx.ident_of("ty");
							let final = cx.expr_block(cx.block(span, vec!(
								cx.stmt_let(span, false, ident_type, cx.expr_call(span, func, vec!(types_vec_slices))),
								cx.stmt_expr(cx.expr_method_call(span, cx.expr_ident(span, ident_type), cx.ident_of("set_names"), vec!(names_vec)))
							), Some(cx.expr_ident(span, ident_type))));
							println!("{}", final.to_source());
							Ok(final)
						},
						_ => Err("Expected bracket".into_string())
					}
				},
				TTTok(_, IDENT(ident, _)) => {
					let ident = ident.to_source();
					let type_id = match ident.as_slice() {
						"void" => "void",
						"int" | "i32" => "int",
						"uint" | "u32" => "uint",
						"i64" => "long",
						"u64" => "ulong",
						"char" => "char",
						"bool" => "bool",
						"f64" => "float64",
						"f32" => "float32",
						"String" => "cstring",
						"Vec" => "vec",
						id => return Err(format!("Unexpected identifier {}", id))
					};
					let full_type_id = cx.ident_of("get_".into_string().append(type_id).as_slice());
					tts.next();
					Ok(quote_expr!(cx, ::jit::Types::$full_type_id()))
				},
				TTTok(span, BINOP(STAR)) => {
					tts.next();
					let func = quote_expr!(&mut*cx, ::jit::Type::create_pointer);
					let parsed_type = try!(jit_parse_type(&mut*cx, tts));
					let wv = cx.expr_addr_of(span, parsed_type);
					Ok(cx.expr_call(span, func, vec!(wv)))
				},
				TTTok(_, DOLLAR) => {
					tts.next();
					match tts.next() {
						Some(ref tks) => {
							match **tks {
								TTTok(span, IDENT(ident, _)) => {
									Ok(cx.expr_ident(span, ident))
								}
								_ => Err("Expected next".into_string())
							}
						},
						None => Err("Abrupt end".into_string())
					}
				},
				ref token => {
					try!(error(Some(token.clone()), DOLLAR));
					Err("...".into_string())
				}
			}
		},
		None =>
			Err("Not a type".into_string())
	}
}
fn jit_type(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult> {
	let mut iter = tts.iter().peekable();
	MacExpr::new(match jit_parse_type(cx, &mut iter) {
		Ok(v) => v,
		Err(e) => {
			cx.span_err(sp, e.as_slice());
			quote_expr!(cx, fail!("Invalid"))
		}
	})
}<|endoftext|>


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

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

use core::ops::DerefMut;
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use core::usize;

use common::elf::Elf;
use common::event::Event;
use common::get_slice::GetSlice;
use common::memory;

use scheduler::context::{context_switch, Context, ContextMemory};

use schemes::{Result, KScheme, Resource, ResourceSeek, Url};

use sync::Intex;

use syscall::SysError;
use syscall::handle::*;

pub enum Msg {
    Start,
    Stop,
    Open(*const u8, usize),
    Close(usize),
    Dup(usize),
    Path(usize, *mut u8, usize),
    Read(usize, *mut u8, usize),
    Write(usize, *const u8, usize),
    Seek(usize, isize, isize),
    Sync(usize),
    Truncate(usize, usize),
    Event(*const Event),
}

pub struct Response {
    msg: Msg,
    result: AtomicUsize,
    ready: AtomicBool,
}

impl Response {
    pub fn new(msg: Msg) -> Box<Response> {
        box Response {
            msg: msg,
            result: AtomicUsize::new(0),
            ready: AtomicBool::new(false),
        }
    }

    pub fn set(&mut self, result: usize) {
        self.result.store(result, Ordering::SeqCst);
        self.ready.store(true, Ordering::SeqCst);
    }

    pub fn get(&self) -> usize {
        while !self.ready.load(Ordering::SeqCst) {
            unsafe { context_switch(false) };
        }

        return self.result.load(Ordering::SeqCst);
    }
}

impl Drop for Response {
    fn drop(&mut self) {
        while !self.ready.load(Ordering::SeqCst) {
            unsafe { context_switch(false) };
        }
    }
}

/// A scheme resource
pub struct SchemeResource {
    /// Pointer to parent
    pub parent: *mut SchemeItem,
    /// File handle
    pub handle: usize,
}

impl SchemeResource {
    pub fn send(&self, msg: Msg) -> Result<usize> {
        unsafe { (*self.parent).send(msg) }
    }
}

impl Resource for SchemeResource {
    /// Duplicate the resource
    fn dup(&self) -> Result<Box<Resource>> {
        match self.send(Msg::Dup(self.handle)) {
            Ok(fd) => Ok(box SchemeResource {
                parent: self.parent,
                handle: fd,
            }),
            Err(err) => Err(err)
        }
    }

    /// Return the url of this resource
    fn url(&self) -> Url {
        let mut buf: [u8; 4096] = [0; 4096];
        match self.send(Msg::Path(self.handle, buf.as_mut_ptr(), buf.len())) {
            Ok(result) => Url::from_string(unsafe {
                String::from_utf8_unchecked(Vec::from(buf.get_slice(None, Some(result))))
            }),
            Err(err) => Url::new()
        }
    }

    /// Read data to buffer
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        let mut ptr = buf.as_mut_ptr();

        let contexts = ::env().contexts.lock();
        if let Some(current) = contexts.current() {
            if let Some(translated) = unsafe { current.translate(ptr as usize) } {
                ptr = translated as *mut u8;
            }
        }

        self.send(Msg::Read(self.handle, ptr, buf.len()))
    }

    /// Write to resource
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let mut ptr = buf.as_ptr();

        let contexts = ::env().contexts.lock();
        if let Some(current) = contexts.current() {
            if let Some(translated) = unsafe { current.translate(ptr as usize) } {
                ptr = translated as *const u8;
            }
        }

        self.send(Msg::Write(self.handle, ptr, buf.len()))
    }

    /// Seek
    fn seek(&mut self, pos: ResourceSeek) -> Result<usize> {
        let offset;
        let whence;
        match pos {
            ResourceSeek::Start(off) => {
                whence = 0;
                offset = off as isize;
            }
            ResourceSeek::Current(off) => {
                whence = 1;
                offset = off;
            }
            ResourceSeek::End(off) => {
                whence = 2;
                offset = off;
            }
        }

        self.send(Msg::Seek(self.handle, offset, whence))
    }

    /// Sync the resource
    fn sync(&mut self) -> Result<()> {
        match self.send(Msg::Sync(self.handle)) {
            Ok(_) => Ok(()),
            Err(err) => Err(err)
        }
    }

    fn truncate(&mut self, len: usize) -> Result<()> {
        match self.send(Msg::Truncate(self.handle, len)) {
            Ok(_) => Ok(()),
            Err(err) => Err(err)
        }
    }
}

impl Drop for SchemeResource {
    fn drop(&mut self) {
        self.send(Msg::Close(self.handle));
    }
}

/// A scheme item
pub struct SchemeItem {
    /// The URL
    url: Url,
    /// The scheme
    scheme: String,
    /// The binary for the scheme
    binary: Url,
    /// Messages to be responded to
    responses: Intex<VecDeque<*mut Response>>,
    /// The handle
    handle: usize,
    _start: usize,
    _stop: usize,
    _open: usize,
    _dup: usize,
    _fpath: usize,
    _read: usize,
    _write: usize,
    _lseek: usize,
    _fsync: usize,
    _ftruncate: usize,
    _close: usize,
    _event: usize,
}

impl SchemeItem {
    /// Load scheme item from URL
    pub fn from_url(url: &Url) -> Box<SchemeItem> {
        let mut scheme_item = box SchemeItem {
            url: url.clone(),
            scheme: String::new(),
            binary: Url::from_string(url.to_string() + "main.bin"),
            responses: Intex::new(VecDeque::new()),
            handle: 0,
            _start: 0,
            _stop: 0,
            _open: 0,
            _dup: 0,
            _fpath: 0,
            _read: 0,
            _write: 0,
            _lseek: 0,
            _fsync: 0,
            _ftruncate: 0,
            _close: 0,
            _event: 0,
        };

        for part in url.reference().rsplit('/') {
            if !part.is_empty() {
                scheme_item.scheme = part.to_string();
                break;
            }
        }

        let mut memory = Vec::new();
        if let Ok(mut resource) = scheme_item.binary.open() {
            let mut vec: Vec<u8> = Vec::new();
            resource.read_to_end(&mut vec);

            unsafe {
                let executable = Elf::from_data(vec.as_ptr() as usize);

                scheme_item._start = executable.symbol("_start");
                scheme_item._stop = executable.symbol("_stop");
                scheme_item._open = executable.symbol("_open");
                scheme_item._dup = executable.symbol("_dup");
                scheme_item._fpath = executable.symbol("_fpath");
                scheme_item._read = executable.symbol("_read");
                scheme_item._write = executable.symbol("_write");
                scheme_item._lseek = executable.symbol("_lseek");
                scheme_item._fsync = executable.symbol("_fsync");
                scheme_item._ftruncate = executable.symbol("_ftruncate");
                scheme_item._close = executable.symbol("_close");
                scheme_item._event = executable.symbol("_event");

                for segment in executable.load_segment().iter() {
                    let virtual_address = segment.vaddr as usize;
                    let virtual_size = segment.mem_len as usize;

                    //TODO: Warning: Investigate this hack!
                    let hack = virtual_address % 4096;

                    let physical_address = memory::alloc(virtual_size + hack);

                    if physical_address > 0 {
                        debugln!("VADDR: {:X} OFF: {:X} FLG: {:X} HACK: {:X}", segment.vaddr, segment.off, segment.flags, hack);

                        // Copy progbits
                        ::memcpy((physical_address + hack) as *mut u8,
                                 (executable.data + segment.off as usize) as *const u8,
                                 segment.file_len as usize);
                        // Zero bss
                        if segment.mem_len > segment.file_len {
                            debugln!("BSS: {:X} {}", segment.vaddr + segment.file_len, segment.mem_len - segment.file_len);
                            ::memset((physical_address + hack + segment.file_len as usize) as *mut u8,
                                    0,
                                    segment.mem_len as usize - segment.file_len as usize);
                        }

                        memory.push(ContextMemory {
                            physical_address: physical_address,
                            virtual_address: virtual_address - hack,
                            virtual_size: virtual_size + hack,
                            writeable: segment.flags & 2 == 2
                        });
                    }
                }
            }
        }

        let wd = url.to_string();
        let scheme_item_ptr: *mut SchemeItem = scheme_item.deref_mut();
        Context::spawn(scheme_item.binary.to_string(),
                       box move || {
                           unsafe {
                               {
                                   let wd_c = wd + "\0";
                                   do_sys_chdir(wd_c.as_ptr());

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

                                   let mut contexts = ::env().contexts.lock();
                                   if let Some(mut current) = contexts.current_mut() {
                                       current.unmap();
                                       (*current.memory.get()) = memory;
                                       current.map();
                                   }
                               }

                               (*scheme_item_ptr).run();
                           }
                       });

        scheme_item.handle = match scheme_item.send(Msg::Start) {
            Ok(handle) => handle,
            Err(_) => 0
        };

        scheme_item
    }
}

impl KScheme for SchemeItem {
    fn scheme(&self) -> &str {
        return &self.scheme;
    }

    // TODO: Hack for orbital
    fn event(&mut self, event: &Event) {
        self.send(Msg::Event(event));
    }

    fn open(&mut self, url: &Url, flags: usize) -> Result<Box<Resource>> {
        let c_str = url.to_string() + "\0";
        match self.send(Msg::Open(c_str.as_ptr(), flags)) {
            Ok(fd) => Ok(box SchemeResource {
                parent: self,
                handle: fd,
            }),
            Err(err) => Err(err)
        }
    }
}

impl Drop for SchemeItem {
    fn drop(&mut self) {
        self.send(Msg::Stop);
    }
}

impl SchemeItem {
    pub fn send(&mut self, msg: Msg) -> Result<usize> {
        let mut response = Response::new(msg);

        self.responses.lock().push_back(response.deref_mut());

        SysError::demux(response.get())
    }

    // TODO: More advanced check
    pub fn valid(&self, call: usize) -> bool {
        call > 0
    }

    pub unsafe fn run(&mut self) {
        let mut running = true;
        while running {
            let response_option = self.responses.lock().pop_front();

            if let Some(response_ptr) = response_option {
                let ret = match (*response_ptr).msg {
                    Msg::Start => if self.valid(self._start) {
                        let fn_ptr: *const usize = &self._start;
                        (*(fn_ptr as *const extern "C" fn() -> usize))()
                    } else {
                        0
                    },
                    Msg::Stop => if self.valid(self._stop) {
                        running = false;
                        let fn_ptr: *const usize = &self._stop;
                        (*(fn_ptr as *const extern "C" fn(usize) -> usize))(self.handle)
                    } else {
                        usize::MAX
                    },
                    Msg::Open(path, flags) => if self.valid(self._open) {
                        let fn_ptr: *const usize = &self._open;
                        (*(fn_ptr as *const extern "C" fn(usize, *const u8, usize) -> usize))(self.handle, path, flags)
                    } else {
                        usize::MAX
                    },
                    Msg::Event(event_ptr) => if self.valid(self._event) {
                        let fn_ptr: *const usize = &self._event;
                        (*(fn_ptr as *const extern "C" fn(usize, usize) -> usize))(self.handle, event_ptr as usize)
                    } else {
                        usize::MAX
                    },
                    Msg::Dup(fd) => if self.valid(self._dup) {
                        let fn_ptr: *const usize = &self._dup;
                        (*(fn_ptr as *const extern "C" fn(usize) -> usize))(fd)
                    } else {
                        usize::MAX
                    },
                    Msg::Path(fd, ptr, len) => if self.valid(self._fpath) {
                        let fn_ptr: *const usize = &self._fpath;
                        (*(fn_ptr as *const extern "C" fn(usize, *mut u8, usize) -> usize))(fd,
                                                                                ptr,
                                                                                len)
                    } else {
                        usize::MAX
                    },
                    Msg::Read(fd, ptr, len) => if self.valid(self._read) {
                        let fn_ptr: *const usize = &self._read;
                        (*(fn_ptr as *const extern "C" fn(usize, *mut u8, usize) -> usize))(fd,
                                                                                ptr,
                                                                                len)
                    } else {
                        usize::MAX
                    },
                    Msg::Write(fd, ptr, len) =>
                        if self.valid(self._write) {
                            let fn_ptr: *const usize = &self._write;
                            (*(fn_ptr as *const extern "C" fn(usize, *const u8, usize) -> usize))(fd, ptr, len)
                        } else {
                            usize::MAX
                        },
                    Msg::Seek(fd, offset, whence) =>
                        if self.valid(self._lseek) {
                            let fn_ptr: *const usize = &self._lseek;
                            (*(fn_ptr as *const extern "C" fn(usize, isize, isize) -> usize))(fd, offset, whence)
                        } else {
                            usize::MAX
                        },
                    Msg::Sync(fd) => if self.valid(self._fsync) {
                        let fn_ptr: *const usize = &self._fsync;
                        (*(fn_ptr as *const extern "C" fn(usize) -> usize))(fd)
                    } else {
                        usize::MAX
                    },
                    Msg::Truncate(fd, len) => if self.valid(self._ftruncate) {
                        let fn_ptr: *const usize = &self._ftruncate;
                        (*(fn_ptr as *const extern "C" fn(usize, usize) -> usize))(fd, len)
                    } else {
                        usize::MAX
                    },
                    Msg::Close(fd) => if self.valid(self._close) {
                        let fn_ptr: *const usize = &self._close;
                        (*(fn_ptr as *const extern "C" fn(usize) -> usize))(fd)
                    } else {
                        usize::MAX
                    },
                };

                (*response_ptr).set(ret);
            } else {
                context_switch(false);
            }
        }
    }
}
<commit_msg>Segment unsafe code from safe code in scheme.rs<commit_after>use alloc::boxed::Box;

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

use core::ops::DerefMut;
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use core::usize;

use common::elf::Elf;
use common::event::Event;
use common::get_slice::GetSlice;
use common::memory;

use scheduler::context::{context_switch, Context, ContextMemory};

use schemes::{Result, KScheme, Resource, ResourceSeek, Url};

use sync::Intex;

use syscall::SysError;
use syscall::handle::*;

#[derive(Copy, Clone, Debug)]
pub enum Msg {
    Start,
    Stop,
    Open(*const u8, usize),
    Close(usize),
    Dup(usize),
    Path(usize, *mut u8, usize),
    Read(usize, *mut u8, usize),
    Write(usize, *const u8, usize),
    Seek(usize, isize, isize),
    Sync(usize),
    Truncate(usize, usize),
    Event(*const Event),
}

pub struct Response {
    msg: Msg,
    result: AtomicUsize,
    ready: AtomicBool,
}

impl Response {
    pub fn new(msg: Msg) -> Box<Response> {
        box Response {
            msg: msg,
            result: AtomicUsize::new(0),
            ready: AtomicBool::new(false),
        }
    }

    pub fn set(&mut self, result: usize) {
        self.result.store(result, Ordering::SeqCst);
        self.ready.store(true, Ordering::SeqCst);
    }

    pub fn get(&self) -> usize {
        while !self.ready.load(Ordering::SeqCst) {
            unsafe { context_switch(false) };
        }

        return self.result.load(Ordering::SeqCst);
    }
}

impl Drop for Response {
    fn drop(&mut self) {
        while !self.ready.load(Ordering::SeqCst) {
            unsafe { context_switch(false) };
        }
    }
}

/// A scheme resource
pub struct SchemeResource {
    /// Pointer to parent
    pub parent: *mut SchemeItem,
    /// File handle
    pub handle: usize,
}

impl SchemeResource {
    pub fn send(&self, msg: Msg) -> Result<usize> {
        unsafe { (*self.parent).send(msg) }
    }
}

impl Resource for SchemeResource {
    /// Duplicate the resource
    fn dup(&self) -> Result<Box<Resource>> {
        match self.send(Msg::Dup(self.handle)) {
            Ok(fd) => Ok(box SchemeResource {
                parent: self.parent,
                handle: fd,
            }),
            Err(err) => Err(err)
        }
    }

    /// Return the url of this resource
    fn url(&self) -> Url {
        let mut buf: [u8; 4096] = [0; 4096];
        match self.send(Msg::Path(self.handle, buf.as_mut_ptr(), buf.len())) {
            Ok(result) => Url::from_string(unsafe {
                String::from_utf8_unchecked(Vec::from(buf.get_slice(None, Some(result))))
            }),
            Err(err) => Url::new()
        }
    }

    /// Read data to buffer
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        let mut ptr = buf.as_mut_ptr();

        let contexts = ::env().contexts.lock();
        if let Some(current) = contexts.current() {
            if let Some(translated) = unsafe { current.translate(ptr as usize) } {
                ptr = translated as *mut u8;
            }
        }

        self.send(Msg::Read(self.handle, ptr, buf.len()))
    }

    /// Write to resource
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let mut ptr = buf.as_ptr();

        let contexts = ::env().contexts.lock();
        if let Some(current) = contexts.current() {
            if let Some(translated) = unsafe { current.translate(ptr as usize) } {
                ptr = translated as *const u8;
            }
        }

        self.send(Msg::Write(self.handle, ptr, buf.len()))
    }

    /// Seek
    fn seek(&mut self, pos: ResourceSeek) -> Result<usize> {
        let offset;
        let whence;
        match pos {
            ResourceSeek::Start(off) => {
                whence = 0;
                offset = off as isize;
            }
            ResourceSeek::Current(off) => {
                whence = 1;
                offset = off;
            }
            ResourceSeek::End(off) => {
                whence = 2;
                offset = off;
            }
        }

        self.send(Msg::Seek(self.handle, offset, whence))
    }

    /// Sync the resource
    fn sync(&mut self) -> Result<()> {
        match self.send(Msg::Sync(self.handle)) {
            Ok(_) => Ok(()),
            Err(err) => Err(err)
        }
    }

    fn truncate(&mut self, len: usize) -> Result<()> {
        match self.send(Msg::Truncate(self.handle, len)) {
            Ok(_) => Ok(()),
            Err(err) => Err(err)
        }
    }
}

impl Drop for SchemeResource {
    fn drop(&mut self) {
        self.send(Msg::Close(self.handle));
    }
}

/// A scheme item
pub struct SchemeItem {
    /// The URL
    url: Url,
    /// The scheme
    scheme: String,
    /// The binary for the scheme
    binary: Url,
    /// Messages to be responded to
    responses: Intex<VecDeque<*mut Response>>,
    /// The handle
    handle: usize,
    _start: usize,
    _stop: usize,
    _open: usize,
    _dup: usize,
    _fpath: usize,
    _read: usize,
    _write: usize,
    _lseek: usize,
    _fsync: usize,
    _ftruncate: usize,
    _close: usize,
    _event: usize,
}

impl SchemeItem {
    /// Load scheme item from URL
    pub fn from_url(url: &Url) -> Box<SchemeItem> {
        let mut scheme_item = box SchemeItem {
            url: url.clone(),
            scheme: String::new(),
            binary: Url::from_string(url.to_string() + "main.bin"),
            responses: Intex::new(VecDeque::new()),
            handle: 0,
            _start: 0,
            _stop: 0,
            _open: 0,
            _dup: 0,
            _fpath: 0,
            _read: 0,
            _write: 0,
            _lseek: 0,
            _fsync: 0,
            _ftruncate: 0,
            _close: 0,
            _event: 0,
        };

        for part in url.reference().rsplit('/') {
            if !part.is_empty() {
                scheme_item.scheme = part.to_string();
                break;
            }
        }

        let mut memory = Vec::new();
        if let Ok(mut resource) = scheme_item.binary.open() {
            let mut vec: Vec<u8> = Vec::new();
            resource.read_to_end(&mut vec);

            unsafe {
                let executable = Elf::from_data(vec.as_ptr() as usize);

                scheme_item._start = executable.symbol("_start");
                scheme_item._stop = executable.symbol("_stop");
                scheme_item._open = executable.symbol("_open");
                scheme_item._dup = executable.symbol("_dup");
                scheme_item._fpath = executable.symbol("_fpath");
                scheme_item._read = executable.symbol("_read");
                scheme_item._write = executable.symbol("_write");
                scheme_item._lseek = executable.symbol("_lseek");
                scheme_item._fsync = executable.symbol("_fsync");
                scheme_item._ftruncate = executable.symbol("_ftruncate");
                scheme_item._close = executable.symbol("_close");
                scheme_item._event = executable.symbol("_event");

                for segment in executable.load_segment().iter() {
                    let virtual_address = segment.vaddr as usize;
                    let virtual_size = segment.mem_len as usize;

                    //TODO: Warning: Investigate this hack!
                    let hack = virtual_address % 4096;

                    let physical_address = memory::alloc(virtual_size + hack);

                    if physical_address > 0 {
                        debugln!("VADDR: {:X} OFF: {:X} FLG: {:X} HACK: {:X}", segment.vaddr, segment.off, segment.flags, hack);

                        // Copy progbits
                        ::memcpy((physical_address + hack) as *mut u8,
                                 (executable.data + segment.off as usize) as *const u8,
                                 segment.file_len as usize);
                        // Zero bss
                        if segment.mem_len > segment.file_len {
                            debugln!("BSS: {:X} {}", segment.vaddr + segment.file_len, segment.mem_len - segment.file_len);
                            ::memset((physical_address + hack + segment.file_len as usize) as *mut u8,
                                    0,
                                    segment.mem_len as usize - segment.file_len as usize);
                        }

                        memory.push(ContextMemory {
                            physical_address: physical_address,
                            virtual_address: virtual_address - hack,
                            virtual_size: virtual_size + hack,
                            writeable: segment.flags & 2 == 2
                        });
                    }
                }
            }
        }

        let wd = url.to_string();
        let scheme_item_ptr: *mut SchemeItem = scheme_item.deref_mut();
        Context::spawn(scheme_item.binary.to_string(),
                       box move || {
                           unsafe {
                               {
                                   let wd_c = wd + "\0";
                                   do_sys_chdir(wd_c.as_ptr());

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

                                   let mut contexts = ::env().contexts.lock();
                                   if let Some(mut current) = contexts.current_mut() {
                                       current.unmap();
                                       (*current.memory.get()) = memory;
                                       current.map();
                                   }
                               }

                               (*scheme_item_ptr).run();
                           }
                       });

        scheme_item.handle = match scheme_item.send(Msg::Start) {
            Ok(handle) => handle,
            Err(_) => 0
        };

        scheme_item
    }
}

impl KScheme for SchemeItem {
    fn scheme(&self) -> &str {
        return &self.scheme;
    }

    // TODO: Hack for orbital
    fn event(&mut self, event: &Event) {
        self.send(Msg::Event(event));
    }

    fn open(&mut self, url: &Url, flags: usize) -> Result<Box<Resource>> {
        let c_str = url.to_string() + "\0";
        match self.send(Msg::Open(c_str.as_ptr(), flags)) {
            Ok(fd) => Ok(box SchemeResource {
                parent: self,
                handle: fd,
            }),
            Err(err) => Err(err)
        }
    }
}

impl Drop for SchemeItem {
    fn drop(&mut self) {
        self.send(Msg::Stop);
    }
}

impl SchemeItem {
    pub fn send(&mut self, msg: Msg) -> Result<usize> {
        let mut response = Response::new(msg);

        self.responses.lock().push_back(response.deref_mut());

        SysError::demux(response.get())
    }

    // TODO: More advanced check
    pub fn valid(&self, call: usize) -> bool {
        call > 0
    }

    pub fn run(&mut self) {
        let mut running = true;
        while running {
            let response_option = self.responses.lock().pop_front();

            if let Some(response_ptr) = response_option {
                let ret = match unsafe { (*response_ptr).msg } {
                    Msg::Start => if self.valid(self._start) {
                        let fn_ptr: *const usize = &self._start;
                        unsafe { (*(fn_ptr as *const extern "C" fn() -> usize))() }
                    } else {
                        0
                    },
                    Msg::Stop => if self.valid(self._stop) {
                        running = false;
                        let fn_ptr: *const usize = &self._stop;
                        unsafe { (*(fn_ptr as *const extern "C" fn(usize) -> usize))(self.handle) }
                    } else {
                        usize::MAX
                    },
                    Msg::Open(path, flags) => if self.valid(self._open) {
                        let fn_ptr: *const usize = &self._open;
                        unsafe { (*(fn_ptr as *const extern "C" fn(usize, *const u8, usize) -> usize))(self.handle, path, flags) }
                    } else {
                        usize::MAX
                    },
                    Msg::Event(event_ptr) => if self.valid(self._event) {
                        let fn_ptr: *const usize = &self._event;
                        unsafe { (*(fn_ptr as *const extern "C" fn(usize, usize) -> usize))(self.handle, event_ptr as usize) }
                    } else {
                        usize::MAX
                    },
                    Msg::Dup(fd) => if self.valid(self._dup) {
                        let fn_ptr: *const usize = &self._dup;
                        unsafe { (*(fn_ptr as *const extern "C" fn(usize) -> usize))(fd) }
                    } else {
                        usize::MAX
                    },
                    Msg::Path(fd, ptr, len) => if self.valid(self._fpath) {
                        let fn_ptr: *const usize = &self._fpath;
                        unsafe {
                            (*(fn_ptr as *const extern "C" fn(usize, *mut u8, usize) -> usize))(fd,
                                                                                ptr,
                                                                                len)
                        }
                    } else {
                        usize::MAX
                    },
                    Msg::Read(fd, ptr, len) => if self.valid(self._read) {
                        let fn_ptr: *const usize = &self._read;
                        unsafe {
                            (*(fn_ptr as *const extern "C" fn(usize, *mut u8, usize) -> usize))(fd,
                                                                                ptr,
                                                                                len)
                        }
                    } else {
                        usize::MAX
                    },
                    Msg::Write(fd, ptr, len) =>
                        if self.valid(self._write) {
                            let fn_ptr: *const usize = &self._write;
                            unsafe { (*(fn_ptr as *const extern "C" fn(usize, *const u8, usize) -> usize))(fd, ptr, len) }
                        } else {
                            usize::MAX
                        },
                    Msg::Seek(fd, offset, whence) =>
                        if self.valid(self._lseek) {
                            let fn_ptr: *const usize = &self._lseek;
                            unsafe { (*(fn_ptr as *const extern "C" fn(usize, isize, isize) -> usize))(fd, offset, whence) }
                        } else {
                            usize::MAX
                        },
                    Msg::Sync(fd) => if self.valid(self._fsync) {
                        let fn_ptr: *const usize = &self._fsync;
                        unsafe { (*(fn_ptr as *const extern "C" fn(usize) -> usize))(fd) }
                    } else {
                        usize::MAX
                    },
                    Msg::Truncate(fd, len) => if self.valid(self._ftruncate) {
                        let fn_ptr: *const usize = &self._ftruncate;
                        unsafe { (*(fn_ptr as *const extern "C" fn(usize, usize) -> usize))(fd, len) }
                    } else {
                        usize::MAX
                    },
                    Msg::Close(fd) => if self.valid(self._close) {
                        let fn_ptr: *const usize = &self._close;
                        unsafe { (*(fn_ptr as *const extern "C" fn(usize) -> usize))(fd) }
                    } else {
                        usize::MAX
                    },
                };

                unsafe { (*response_ptr).set(ret); }
            } else {
                unsafe { context_switch(false); }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>/bin/sh default<commit_after><|endoftext|>


<commit_before><commit_msg>Added AttemptResult struct<commit_after><|endoftext|>


<commit_before><commit_msg>Add regression test for UFCS formatting error<commit_after>// Regression test for issue 64

pub fn header_name<T: Header>() -> &'static str {
    let name = <T as Header>::header_name();
    let func = <T as Header>::header_name;
    name
}
<|endoftext|>


<commit_before><commit_msg>File index is now storing relative paths only to reduce memory size.<commit_after><|endoftext|>


<commit_before><commit_msg>Add a unit test file about write module<commit_after>extern crate snatch;

#[cfg(test)]
mod test_http_versions {
    use snatch::write::write_file;
    use snatch::SChunks;

    use std::fs::File;
    use std::sync::{Arc, Mutex};

    #[test]
    fn empty_chunks_should_only_create_a_file() {
        let file_name = "tests/test_files/write_test.txt";
        let mut test_file : File = File::create(file_name).unwrap();
        let empty_chunk : SChunks = Arc::new(Mutex::new(vec![]));

        assert!(write_file(&mut test_file, &empty_chunk).is_ok());
        assert!(test_file.metadata().unwrap().len() == 0);
    }

    #[test]
    fn simple_hello_world_msg_should_pass() {
        let file_name = "tests/test_files/write_test.txt";
        let mut test_file : File = File::create(file_name).unwrap();
        let hello_world_msg : Vec<u8> = String::from("Hello World!").into_bytes();
        let msg_chunk : SChunks = Arc::new(Mutex::new(vec![hello_world_msg.clone()]));

        assert!(write_file(&mut test_file, &msg_chunk).is_ok());
        assert!(test_file.metadata().unwrap().len() == hello_world_msg.len() as u64);
    }

    #[test]
    fn complex_msg_should_pass() {
        let file_name = "tests/test_files/write_test.txt";
        let mut test_file : File = File::create(file_name).unwrap();
        let fst_msg : Vec<u8> = String::from("This mess").into_bytes();
        let snd_msg : Vec<u8> = String::from("age is ").into_bytes();
        let trd_msg : Vec<u8> = String::from("complex\n").into_bytes();
        let msg_chunk : SChunks = Arc::new(Mutex::new(vec![fst_msg.clone(), snd_msg.clone(), trd_msg.clone()]));

        assert!(write_file(&mut test_file, &msg_chunk).is_ok());
        assert!(test_file.metadata().unwrap().len() == (fst_msg.len() + snd_msg.len() + trd_msg.len()) as u64);
    }

}<|endoftext|>


<commit_before><commit_msg>Added another test.<commit_after>// build-pass (FIXME(62277): could be check-pass?)

#![feature(associated_type_bounds)]

pub struct Flatten<I>
where
    I: Iterator<Item: IntoIterator>,
{
    inner: <I::Item as IntoIterator>::IntoIter,
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>pub again<commit_after><|endoftext|>


<commit_before><commit_msg>Rust: Problem 1<commit_after>/// # Multiples of 3 and 5
/// ## Problem 1
/// If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
/// Find the sum of all the multiples of 3 or 5 below 1000.

fn main() {
    let mut total = 0;

    for n in range(1, 1000) {
        match n {
            v if v % 3 == 0 => total += v,
            v if v % 5 == 0 => total += v,
            _ => { /* do nothing */ }
        }
    }

    println!("result is {}", total);

}
<|endoftext|>


<commit_before><commit_msg>Encapsulate scalar mult in GroupCurve25519's exp_on method<commit_after><|endoftext|>


<commit_before><commit_msg>add rust hello world<commit_after>// to run: rustc hw.rs && ./hw
fn main() {
    println!("Hello World!");
}
<|endoftext|>


<commit_before>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::{fs, str};
use std::collections::HashSet;
use std::io::ErrorKind;
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};

use super::super::errors::EngineResult;

use engine::Pool;
use engine::types::{Name, PoolUuid};

pub const DEV_PATH: &str = "/dev/stratis";

/// Set up directories and symlinks under /dev/stratis based on current
/// config. Clear out any directory or file that doesn't correspond to a pool
/// or filesystem.
// Don't just remove and recreate everything in case there are processes
// (e.g. user shells) with the current working directory within the tree.
pub fn setup_devlinks<'a, I: Iterator<Item = &'a (Name, PoolUuid, &'a Pool)>>
    (pools: I)
     -> EngineResult<()> {
    if let Err(err) = fs::create_dir(DEV_PATH) {
        if err.kind() != ErrorKind::AlreadyExists {
            return Err(From::from(err));
        }
    }

    let mut existing_dirs = fs::read_dir(DEV_PATH)?
        .map(|dir_e| dir_e.and_then(|d| Ok(d.file_name().into_string().expect("Unix is utf-8"))))
        .collect::<Result<HashSet<_>, _>>()?;

    for &(ref pool_name, _, pool) in pools {
        if !existing_dirs.remove(&pool_name.to_owned()) {
            pool_added(pool_name)?;
        }

        let pool_path: PathBuf = vec![DEV_PATH, pool_name].iter().collect();

        let mut existing_files = fs::read_dir(pool_path)?
            .map(|dir_e| {
                     dir_e.and_then(|d| Ok(d.file_name().into_string().expect("Unix is utf-8")))
                 })
            .collect::<Result<HashSet<_>, _>>()?;

        for (fs_name, _, fs) in pool.filesystems() {
            filesystem_added(pool_name, &fs_name, &fs.devnode())?;
            existing_files.remove(&fs_name.to_owned());
        }

        for leftover in existing_files {
            filesystem_removed(pool_name, &leftover)?;
        }
    }

    for leftover in existing_dirs {
        pool_removed(&Name::new(leftover))?
    }

    Ok(())
}

/// Create a directory when a pool is added.
pub fn pool_added(pool: &str) -> EngineResult<()> {
    let p: PathBuf = vec![DEV_PATH, pool].iter().collect();
    fs::create_dir(&p)?;
    Ok(())
}

/// Remove the directory and its contents when the pool is removed.
pub fn pool_removed(pool: &str) -> EngineResult<()> {
    let p: PathBuf = vec![DEV_PATH, pool].iter().collect();
    fs::remove_dir_all(&p)?;
    Ok(())
}

/// Rename the directory to match the pool's new name.
pub fn pool_renamed(old_name: &str, new_name: &str) -> EngineResult<()> {
    let old: PathBuf = vec![DEV_PATH, old_name].iter().collect();
    let new: PathBuf = vec![DEV_PATH, new_name].iter().collect();
    fs::rename(&old, &new)?;
    Ok(())
}

/// Create a symlink to the new filesystem's block device within its pool's
/// directory.
pub fn filesystem_added(pool_name: &str, fs_name: &str, devnode: &Path) -> EngineResult<()> {
    let p: PathBuf = vec![DEV_PATH, pool_name, fs_name].iter().collect();

    // Remove existing and recreate to ensure it points to the correct devnode
    let _ = fs::remove_file(&p);
    symlink(devnode, &p)?;
    Ok(())
}

/// Remove the symlink when the filesystem is destroyed.
pub fn filesystem_removed(pool_name: &str, fs_name: &str) -> EngineResult<()> {
    let p: PathBuf = vec![DEV_PATH, pool_name, fs_name].iter().collect();
    fs::remove_file(&p)?;
    Ok(())
}

/// Rename the symlink to track the filesystem's new name.
pub fn filesystem_renamed(pool_name: &str, old_name: &str, new_name: &str) -> EngineResult<()> {
    let old: PathBuf = vec![DEV_PATH, pool_name, old_name].iter().collect();
    let new: PathBuf = vec![DEV_PATH, pool_name, new_name].iter().collect();
    fs::rename(&old, &new)?;
    Ok(())
}
<commit_msg>Re-arrange some imports<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::{fs, str};
use std::collections::HashSet;
use std::io::ErrorKind;
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};

use super::super::engine::Pool;
use super::super::errors::EngineResult;
use super::super::types::{Name, PoolUuid};

pub const DEV_PATH: &str = "/dev/stratis";

/// Set up directories and symlinks under /dev/stratis based on current
/// config. Clear out any directory or file that doesn't correspond to a pool
/// or filesystem.
// Don't just remove and recreate everything in case there are processes
// (e.g. user shells) with the current working directory within the tree.
pub fn setup_devlinks<'a, I: Iterator<Item = &'a (Name, PoolUuid, &'a Pool)>>
    (pools: I)
     -> EngineResult<()> {
    if let Err(err) = fs::create_dir(DEV_PATH) {
        if err.kind() != ErrorKind::AlreadyExists {
            return Err(From::from(err));
        }
    }

    let mut existing_dirs = fs::read_dir(DEV_PATH)?
        .map(|dir_e| dir_e.and_then(|d| Ok(d.file_name().into_string().expect("Unix is utf-8"))))
        .collect::<Result<HashSet<_>, _>>()?;

    for &(ref pool_name, _, pool) in pools {
        if !existing_dirs.remove(&pool_name.to_owned()) {
            pool_added(pool_name)?;
        }

        let pool_path: PathBuf = vec![DEV_PATH, pool_name].iter().collect();

        let mut existing_files = fs::read_dir(pool_path)?
            .map(|dir_e| {
                     dir_e.and_then(|d| Ok(d.file_name().into_string().expect("Unix is utf-8")))
                 })
            .collect::<Result<HashSet<_>, _>>()?;

        for (fs_name, _, fs) in pool.filesystems() {
            filesystem_added(pool_name, &fs_name, &fs.devnode())?;
            existing_files.remove(&fs_name.to_owned());
        }

        for leftover in existing_files {
            filesystem_removed(pool_name, &leftover)?;
        }
    }

    for leftover in existing_dirs {
        pool_removed(&Name::new(leftover))?
    }

    Ok(())
}

/// Create a directory when a pool is added.
pub fn pool_added(pool: &str) -> EngineResult<()> {
    let p: PathBuf = vec![DEV_PATH, pool].iter().collect();
    fs::create_dir(&p)?;
    Ok(())
}

/// Remove the directory and its contents when the pool is removed.
pub fn pool_removed(pool: &str) -> EngineResult<()> {
    let p: PathBuf = vec![DEV_PATH, pool].iter().collect();
    fs::remove_dir_all(&p)?;
    Ok(())
}

/// Rename the directory to match the pool's new name.
pub fn pool_renamed(old_name: &str, new_name: &str) -> EngineResult<()> {
    let old: PathBuf = vec![DEV_PATH, old_name].iter().collect();
    let new: PathBuf = vec![DEV_PATH, new_name].iter().collect();
    fs::rename(&old, &new)?;
    Ok(())
}

/// Create a symlink to the new filesystem's block device within its pool's
/// directory.
pub fn filesystem_added(pool_name: &str, fs_name: &str, devnode: &Path) -> EngineResult<()> {
    let p: PathBuf = vec![DEV_PATH, pool_name, fs_name].iter().collect();

    // Remove existing and recreate to ensure it points to the correct devnode
    let _ = fs::remove_file(&p);
    symlink(devnode, &p)?;
    Ok(())
}

/// Remove the symlink when the filesystem is destroyed.
pub fn filesystem_removed(pool_name: &str, fs_name: &str) -> EngineResult<()> {
    let p: PathBuf = vec![DEV_PATH, pool_name, fs_name].iter().collect();
    fs::remove_file(&p)?;
    Ok(())
}

/// Rename the symlink to track the filesystem's new name.
pub fn filesystem_renamed(pool_name: &str, old_name: &str, new_name: &str) -> EngineResult<()> {
    let old: PathBuf = vec![DEV_PATH, pool_name, old_name].iter().collect();
    let new: PathBuf = vec![DEV_PATH, pool_name, new_name].iter().collect();
    fs::rename(&old, &new)?;
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>discipline<commit_after>fn main() {
    println!("Discipline the first things");
}
<|endoftext|>


<commit_before><commit_msg>example of non-blocking udp-socket (we'll use it for stream)<commit_after>// cargo run --example just_udp_socket
// echo -n "hello" > /dev/udp/0.0.0.0/5546 // this isn't working version

// this one requires socat, but works like a breeze
// echo -e "\xff" | socat - UDP-DATAGRAM:0.0.0.0:5546,broadcast

use std::net::UdpSocket;
use std::time::{Duration, Instant};
use std::io::ErrorKind;
use std::thread;

fn main() {
    let sock = UdpSocket::bind("0.0.0.0:5546").expect("Failed to bind socket");
    sock.set_nonblocking(true) .expect("Failed to enter non-blocking mode");

    // Poll for data every 5 milliseconds for 5 seconds.
    let start = Instant::now();
    let mut buf = [0u8; 1024];

    // for 50 seconds...
    while start.elapsed().as_secs() < 50 {
        let result = sock.recv(&mut buf);
        match result {
            // If `recv` was successfull, print the number of bytes received.
            // The received data is stored in `buf`.
            Ok(num_bytes) => println!("I received {} bytes!", num_bytes),
            // If we get an error other than "would block", print the error.
            Err(ref err) if err.kind() != ErrorKind::WouldBlock => {
            // Do nothing otherwise.
                println!("Something went wrong: {}", err)
            }
            _ => {}
        }

        thread::sleep(Duration::from_millis(5));
    }

    println!("Done");
}
<|endoftext|>


<commit_before><commit_msg>audio.restore method<commit_after><|endoftext|>


<commit_before><commit_msg>Refactored quit and restart commands into methods<commit_after><|endoftext|>


<commit_before><commit_msg>Adjust comments<commit_after><|endoftext|>


<commit_before><commit_msg>Add Client and Server types<commit_after><|endoftext|>


<commit_before><commit_msg>Add missing query.rs file<commit_after>use rusqlite::ToSql;

macro_rules! vec_params {
    ($($param:expr),* $(,)?) => {
        vec![$(Box::new($param) as Box<dyn ToSql>),*]
    };
}

pub trait QueryNode {
    fn to_sql_clause(&self) -> (String, Vec<Box<dyn ToSql>>);
}

#[derive(Debug)]
pub struct Empty {}

impl QueryNode for Empty {
    fn to_sql_clause(&self) -> (String, Vec<Box<dyn ToSql>>) {
        ("1=1".to_string(), vec_params![])
    }
}

#[derive(Debug)]
pub struct PropEqual {
    pub name: String,
    pub value: String,
}

impl QueryNode for PropEqual {
    fn to_sql_clause(&self) -> (String, Vec<Box<dyn ToSql>>) {
        (
            format!("json_extract(properties, \"$.{}\") = ?", self.name).to_string(),
            vec_params![self.value.clone()],
        )
    }
}

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

    macro_rules! query_test {
        ( $query:expr, $where_clause:expr, [$($params:expr),*] $(,)?) => {
            (Box::new($query) as Box<dyn QueryNode>, $where_clause.to_string(), vec_params![$($params,),*])
        }
    }

    #[test]
    fn queries_convert_correctly() {
        let tests = [
            query_test!(Empty {}, "1=1".to_string(), []),
            query_test!(
                PropEqual {
                    name: "name".to_string(),
                    value: "value".to_string(),
                },
                "json_extract(properties, \"$.name\") = ?",
                ["value"],
            ),
        ];

        for (query, expected_where_clause, expected_params) in &tests {
            let (actual_where_clause, actual_params) = &query.to_sql_clause();

            let expected_params_output: Vec<rusqlite::types::ToSqlOutput> = expected_params
                .iter()
                .map(|x| x.to_sql().unwrap())
                .collect();
            let actual_params_output: Vec<rusqlite::types::ToSqlOutput> =
                actual_params.iter().map(|x| x.to_sql().unwrap()).collect();

            assert_eq!(expected_where_clause, actual_where_clause);
            assert_eq!(expected_params_output, actual_params_output);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>chore: Result<T, V><commit_after><|endoftext|>


<commit_before><commit_msg>changed arrangements of fields in query, some comments<commit_after><|endoftext|>


<commit_before><commit_msg>token.rs<commit_after><|endoftext|>