<commit_before>#[doc ="Process spawning"];
import option::{some, none};
import libc::{pid_t, c_void, c_int};

export program;
export run_program;
export start_program;
export program_output;
export spawn_process;
export waitpid;

#[abi = "cdecl"]
native mod rustrt {
    fn rust_run_program(argv: **libc::c_char, envp: *c_void,
                        dir: *libc::c_char,
                        in_fd: c_int, out_fd: c_int, err_fd: c_int)
        -> pid_t;
}

#[doc ="A value representing a child process"]
iface program {
    #[doc ="Returns the process id of the program"]
    fn get_id() -> pid_t;

    #[doc ="Returns an io::writer that can be used to write to stdin"]
    fn input() -> io::writer;

    #[doc ="Returns an io::reader that can be used to read from stdout"]
    fn output() -> io::reader;

    #[doc ="Returns an io::reader that can be used to read from stderr"]
    fn err() -> io::reader;

    #[doc = "Closes the handle to the child processes standard input"]
    fn close_input();

    #[doc = "
    Waits for the child process to terminate. Closes the handle
    to stdin if necessary.
    "]
    fn finish() -> int;

    #[doc ="Closes open handles"]
    fn destroy();
}

#[doc = "
Run a program, providing stdin, stdout and stderr handles

# Arguments

* prog - The path to an executable
* args - Vector of arguments to pass to the child process
* env - optional env-modification for child
* dir - optional dir to run child in (default current dir)
* in_fd - A file descriptor for the child to use as std input
* out_fd - A file descriptor for the child to use as std output
* err_fd - A file descriptor for the child to use as std error

# Return value

The process id of the spawned process
"]
fn spawn_process(prog: str, args: [str],
                 env: option<[(str,str)]>,
                 dir: option<str>,
                 in_fd: c_int, out_fd: c_int, err_fd: c_int)
   -> pid_t unsafe {
    with_argv(prog, args) {|argv|
        with_envp(env) { |envp|
            with_dirp(dir) { |dirp|
                rustrt::rust_run_program(argv, envp, dirp,
                                         in_fd, out_fd, err_fd)
            }
        }
    }
}

fn with_argv<T>(prog: str, args: [str],
                cb: fn(**libc::c_char) -> T) -> T unsafe {
    let mut argptrs = str::as_c_str(prog) {|b| [b] };
    let mut tmps = [];
    for arg in args {
        let t = @arg;
        tmps += [t];
        argptrs += str::as_c_str(*t) {|b| [b] };
    }
    argptrs += [ptr::null()];
    vec::as_buf(argptrs, cb)
}

#[cfg(target_os = "macos")]
#[cfg(target_os = "linux")]
#[cfg(target_os = "freebsd")]
fn with_envp<T>(env: option<[(str,str)]>,
                cb: fn(*c_void) -> T) -> T unsafe {
    // On posixy systems we can pass a char** for envp, which is
    // a null-terminated array of "k=v\n" strings.
    alt env {
      some (es) {
        let mut tmps = [];
        let mut ptrs = [];

        for (k,v) in es {
            let t = @(#fmt("%s=%s", k, v));
            vec::push(tmps, t);
            ptrs += str::as_c_str(*t) {|b| [b]};
        }
        ptrs += [ptr::null()];
        vec::as_buf(ptrs) { |p| cb(::unsafe::reinterpret_cast(p)) }
      }
      none {
        cb(ptr::null())
      }
    }
}

#[cfg(target_os = "win32")]
fn with_envp<T>(env: option<[(str,str)]>,
                cb: fn(*c_void) -> T) -> T unsafe {
    // On win32 we pass an "environment block" which is not a char**, but
    // rather a concatenation of null-terminated k=v\0 sequences, with a final
    // \0 to terminate.
    alt env {
      some (es) {
        let mut blk : [u8] = [];
        for (k,v) in es {
            let t = #fmt("%s=%s", k, v);
            let mut v : [u8] = ::unsafe::reinterpret_cast(t);
            blk += v;
            ::unsafe::leak(v);
        }
        blk += [0_u8];
        vec::as_buf(blk) {|p| cb(::unsafe::reinterpret_cast(p)) }
      }
      none {
        cb(ptr::null())
      }
    }
}

fn with_dirp<T>(d: option<str>,
                cb: fn(*libc::c_char) -> T) -> T unsafe {
    alt d {
      some(dir) { str::as_c_str(dir, cb) }
      none { cb(ptr::null()) }
    }
}

#[doc ="
Spawns a process and waits for it to terminate

# Arguments

* prog - The path to an executable
* args - Vector of arguments to pass to the child process

# Return value

The process id
"]
fn run_program(prog: str, args: [str]) -> int {
    ret waitpid(spawn_process(prog, args, none, none,
                              0i32, 0i32, 0i32));
}

#[doc ="
Spawns a process and returns a program

The returned value is a boxed resource containing a <program> object that can
be used for sending and recieving data over the standard file descriptors.
The resource will ensure that file descriptors are closed properly.

# Arguments

* prog - The path to an executable
* args - Vector of arguments to pass to the child process

# Return value

A boxed resource of <program>
"]
fn start_program(prog: str, args: [str]) -> program {
    let pipe_input = os::pipe();
    let pipe_output = os::pipe();
    let pipe_err = os::pipe();
    let pid =
        spawn_process(prog, args, none, none,
                      pipe_input.in, pipe_output.out,
                      pipe_err.out);

    if pid == -1i32 { fail; }
    libc::close(pipe_input.in);
    libc::close(pipe_output.out);
    libc::close(pipe_err.out);

    type prog_repr = {pid: pid_t,
                      mutable in_fd: c_int,
                      out_file: *libc::FILE,
                      err_file: *libc::FILE,
                      mutable finished: bool};

    fn close_repr_input(r: prog_repr) {
        let invalid_fd = -1i32;
        if r.in_fd != invalid_fd {
            libc::close(r.in_fd);
            r.in_fd = invalid_fd;
        }
    }
    fn finish_repr(r: prog_repr) -> int {
        if r.finished { ret 0; }
        r.finished = true;
        close_repr_input(r);
        ret waitpid(r.pid);
    }
    fn destroy_repr(r: prog_repr) {
        finish_repr(r);
       libc::fclose(r.out_file);
       libc::fclose(r.err_file);
    }
    resource prog_res(r: prog_repr) { destroy_repr(r); }

    impl of program for prog_res {
        fn get_id() -> pid_t { ret self.pid; }
        fn input() -> io::writer { io::fd_writer(self.in_fd, false) }
        fn output() -> io::reader { io::FILE_reader(self.out_file, false) }
        fn err() -> io::reader { io::FILE_reader(self.err_file, false) }
        fn close_input() { close_repr_input(*self); }
        fn finish() -> int { finish_repr(*self) }
        fn destroy() { destroy_repr(*self); }
    }
    let repr = {pid: pid,
                mutable in_fd: pipe_input.out,
                out_file: os::fdopen(pipe_output.in),
                err_file: os::fdopen(pipe_err.in),
                mutable finished: false};
    ret prog_res(repr) as program;
}

fn read_all(rd: io::reader) -> str {
    let mut buf = "";
    while !rd.eof() {
        let bytes = rd.read_bytes(4096u);
        buf += str::from_bytes(bytes);
    }
    ret buf;
}

#[doc ="
Spawns a process, waits for it to exit, and returns the exit code, and
contents of stdout and stderr.

# Arguments

* prog - The path to an executable
* args - Vector of arguments to pass to the child process

# Return value

A record, {status: int, out: str, err: str} containing the exit code,
the contents of stdout and the contents of stderr.
"]
fn program_output(prog: str, args: [str]) ->
   {status: int, out: str, err: str} {
    let pr = start_program(prog, args);
    pr.close_input();
    let out = read_all(pr.output());
    let err = read_all(pr.err());
    ret {status: pr.finish(), out: out, err: err};
}

#[doc ="Waits for a process to exit and returns the exit code"]
fn waitpid(pid: pid_t) -> int {
    ret waitpid_os(pid);

    #[cfg(target_os = "win32")]
    fn waitpid_os(pid: pid_t) -> int {
        os::waitpid(pid) as int
    }

    #[cfg(target_os = "linux")]
    #[cfg(target_os = "macos")]
    #[cfg(target_os = "freebsd")]
    fn waitpid_os(pid: pid_t) -> int {
        #[cfg(target_os = "linux")]
        fn WIFEXITED(status: i32) -> bool {
            (status & 0xffi32) == 0i32
        }

        #[cfg(target_os = "macos")]
        #[cfg(target_os = "freebsd")]
        fn WIFEXITED(status: i32) -> bool {
            (status & 0x7fi32) == 0i32
        }

        #[cfg(target_os = "linux")]
        fn WEXITSTATUS(status: i32) -> i32 {
            (status >> 8i32) & 0xffi32
        }

        #[cfg(target_os = "macos")]
        #[cfg(target_os = "freebsd")]
        fn WEXITSTATUS(status: i32) -> i32 {
            status >> 8i32
        }

        let status = os::waitpid(pid);
        ret if WIFEXITED(status) {
            WEXITSTATUS(status) as int
        } else {
            1
        };
    }
}

#[cfg(test)]
mod tests {

    import io::writer_util;

    // Regression test for memory leaks
    #[ignore(cfg(target_os = "win32"))] // FIXME
    fn test_leaks() {
        run::run_program("echo", []);
        run::start_program("echo", []);
        run::program_output("echo", []);
    }

    #[test]
    fn test_pipes() {
        let pipe_in = os::pipe();
        let pipe_out = os::pipe();
        let pipe_err = os::pipe();

        let pid =
            run::spawn_process(
                "cat", [], none, none,
                pipe_in.in, pipe_out.out, pipe_err.out);
        os::close(pipe_in.in);
        os::close(pipe_out.out);
        os::close(pipe_err.out);

        if pid == -1i32 { fail; }
        let expected = "test";
        writeclose(pipe_in.out, expected);
        let actual = readclose(pipe_out.in);
        readclose(pipe_err.in);
        os::waitpid(pid);

        log(debug, expected);
        log(debug, actual);
        assert (expected == actual);

        fn writeclose(fd: c_int, s: str) {
            #error("writeclose %d, %s", fd as int, s);
            let writer = io::fd_writer(fd, false);
            writer.write_str(s);

            os::close(fd);
        }

        fn readclose(fd: c_int) -> str {
            // Copied from run::program_output
            let file = os::fdopen(fd);
            let reader = io::FILE_reader(file, false);
            let buf = "";
            while !reader.eof() {
                let bytes = reader.read_bytes(4096u);
                buf += str::from_bytes(bytes);
            }
            os::fclose(file);
            ret buf;
        }
    }

    #[test]
    fn waitpid() {
        let pid = run::spawn_process("false", [],
                                     none, none,
                                     0i32, 0i32, 0i32);
        let status = run::waitpid(pid);
        assert status == 1;
    }

}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<commit_msg>Fail when there's an error starting a process. Close #1778.<commit_after>#[doc ="Process spawning"];
import option::{some, none};
import libc::{pid_t, c_void, c_int};

export program;
export run_program;
export start_program;
export program_output;
export spawn_process;
export waitpid;

#[abi = "cdecl"]
native mod rustrt {
    fn rust_run_program(argv: **libc::c_char, envp: *c_void,
                        dir: *libc::c_char,
                        in_fd: c_int, out_fd: c_int, err_fd: c_int)
        -> pid_t;
}

#[doc ="A value representing a child process"]
iface program {
    #[doc ="Returns the process id of the program"]
    fn get_id() -> pid_t;

    #[doc ="Returns an io::writer that can be used to write to stdin"]
    fn input() -> io::writer;

    #[doc ="Returns an io::reader that can be used to read from stdout"]
    fn output() -> io::reader;

    #[doc ="Returns an io::reader that can be used to read from stderr"]
    fn err() -> io::reader;

    #[doc = "Closes the handle to the child processes standard input"]
    fn close_input();

    #[doc = "
    Waits for the child process to terminate. Closes the handle
    to stdin if necessary.
    "]
    fn finish() -> int;

    #[doc ="Closes open handles"]
    fn destroy();
}

#[doc = "
Run a program, providing stdin, stdout and stderr handles

# Arguments

* prog - The path to an executable
* args - Vector of arguments to pass to the child process
* env - optional env-modification for child
* dir - optional dir to run child in (default current dir)
* in_fd - A file descriptor for the child to use as std input
* out_fd - A file descriptor for the child to use as std output
* err_fd - A file descriptor for the child to use as std error

# Return value

The process id of the spawned process
"]
fn spawn_process(prog: str, args: [str],
                 env: option<[(str,str)]>,
                 dir: option<str>,
                 in_fd: c_int, out_fd: c_int, err_fd: c_int)
   -> pid_t unsafe {
    with_argv(prog, args) {|argv|
        with_envp(env) { |envp|
            with_dirp(dir) { |dirp|
                rustrt::rust_run_program(argv, envp, dirp,
                                         in_fd, out_fd, err_fd)
            }
        }
    }
}

fn with_argv<T>(prog: str, args: [str],
                cb: fn(**libc::c_char) -> T) -> T unsafe {
    let mut argptrs = str::as_c_str(prog) {|b| [b] };
    let mut tmps = [];
    for arg in args {
        let t = @arg;
        tmps += [t];
        argptrs += str::as_c_str(*t) {|b| [b] };
    }
    argptrs += [ptr::null()];
    vec::as_buf(argptrs, cb)
}

#[cfg(target_os = "macos")]
#[cfg(target_os = "linux")]
#[cfg(target_os = "freebsd")]
fn with_envp<T>(env: option<[(str,str)]>,
                cb: fn(*c_void) -> T) -> T unsafe {
    // On posixy systems we can pass a char** for envp, which is
    // a null-terminated array of "k=v\n" strings.
    alt env {
      some (es) {
        let mut tmps = [];
        let mut ptrs = [];

        for (k,v) in es {
            let t = @(#fmt("%s=%s", k, v));
            vec::push(tmps, t);
            ptrs += str::as_c_str(*t) {|b| [b]};
        }
        ptrs += [ptr::null()];
        vec::as_buf(ptrs) { |p| cb(::unsafe::reinterpret_cast(p)) }
      }
      none {
        cb(ptr::null())
      }
    }
}

#[cfg(target_os = "win32")]
fn with_envp<T>(env: option<[(str,str)]>,
                cb: fn(*c_void) -> T) -> T unsafe {
    // On win32 we pass an "environment block" which is not a char**, but
    // rather a concatenation of null-terminated k=v\0 sequences, with a final
    // \0 to terminate.
    alt env {
      some (es) {
        let mut blk : [u8] = [];
        for (k,v) in es {
            let t = #fmt("%s=%s", k, v);
            let mut v : [u8] = ::unsafe::reinterpret_cast(t);
            blk += v;
            ::unsafe::leak(v);
        }
        blk += [0_u8];
        vec::as_buf(blk) {|p| cb(::unsafe::reinterpret_cast(p)) }
      }
      none {
        cb(ptr::null())
      }
    }
}

fn with_dirp<T>(d: option<str>,
                cb: fn(*libc::c_char) -> T) -> T unsafe {
    alt d {
      some(dir) { str::as_c_str(dir, cb) }
      none { cb(ptr::null()) }
    }
}

#[doc ="
Spawns a process and waits for it to terminate

# Arguments

* prog - The path to an executable
* args - Vector of arguments to pass to the child process

# Return value

The process id
"]
fn run_program(prog: str, args: [str]) -> int {
    let pid = spawn_process(prog, args, none, none,
                            0i32, 0i32, 0i32);
    if pid == -1 as pid_t { fail; }
    ret waitpid(pid);
}

#[doc ="
Spawns a process and returns a program

The returned value is a boxed resource containing a <program> object that can
be used for sending and recieving data over the standard file descriptors.
The resource will ensure that file descriptors are closed properly.

# Arguments

* prog - The path to an executable
* args - Vector of arguments to pass to the child process

# Return value

A boxed resource of <program>
"]
fn start_program(prog: str, args: [str]) -> program {
    let pipe_input = os::pipe();
    let pipe_output = os::pipe();
    let pipe_err = os::pipe();
    let pid =
        spawn_process(prog, args, none, none,
                      pipe_input.in, pipe_output.out,
                      pipe_err.out);

    if pid == -1 as pid_t { fail; }
    libc::close(pipe_input.in);
    libc::close(pipe_output.out);
    libc::close(pipe_err.out);

    type prog_repr = {pid: pid_t,
                      mutable in_fd: c_int,
                      out_file: *libc::FILE,
                      err_file: *libc::FILE,
                      mutable finished: bool};

    fn close_repr_input(r: prog_repr) {
        let invalid_fd = -1i32;
        if r.in_fd != invalid_fd {
            libc::close(r.in_fd);
            r.in_fd = invalid_fd;
        }
    }
    fn finish_repr(r: prog_repr) -> int {
        if r.finished { ret 0; }
        r.finished = true;
        close_repr_input(r);
        ret waitpid(r.pid);
    }
    fn destroy_repr(r: prog_repr) {
        finish_repr(r);
       libc::fclose(r.out_file);
       libc::fclose(r.err_file);
    }
    resource prog_res(r: prog_repr) { destroy_repr(r); }

    impl of program for prog_res {
        fn get_id() -> pid_t { ret self.pid; }
        fn input() -> io::writer { io::fd_writer(self.in_fd, false) }
        fn output() -> io::reader { io::FILE_reader(self.out_file, false) }
        fn err() -> io::reader { io::FILE_reader(self.err_file, false) }
        fn close_input() { close_repr_input(*self); }
        fn finish() -> int { finish_repr(*self) }
        fn destroy() { destroy_repr(*self); }
    }
    let repr = {pid: pid,
                mutable in_fd: pipe_input.out,
                out_file: os::fdopen(pipe_output.in),
                err_file: os::fdopen(pipe_err.in),
                mutable finished: false};
    ret prog_res(repr) as program;
}

fn read_all(rd: io::reader) -> str {
    let mut buf = "";
    while !rd.eof() {
        let bytes = rd.read_bytes(4096u);
        buf += str::from_bytes(bytes);
    }
    ret buf;
}

#[doc ="
Spawns a process, waits for it to exit, and returns the exit code, and
contents of stdout and stderr.

# Arguments

* prog - The path to an executable
* args - Vector of arguments to pass to the child process

# Return value

A record, {status: int, out: str, err: str} containing the exit code,
the contents of stdout and the contents of stderr.
"]
fn program_output(prog: str, args: [str]) ->
   {status: int, out: str, err: str} {
    let pr = start_program(prog, args);
    pr.close_input();
    let out = read_all(pr.output());
    let err = read_all(pr.err());
    ret {status: pr.finish(), out: out, err: err};
}

#[doc ="Waits for a process to exit and returns the exit code"]
fn waitpid(pid: pid_t) -> int {
    ret waitpid_os(pid);

    #[cfg(target_os = "win32")]
    fn waitpid_os(pid: pid_t) -> int {
        os::waitpid(pid) as int
    }

    #[cfg(target_os = "linux")]
    #[cfg(target_os = "macos")]
    #[cfg(target_os = "freebsd")]
    fn waitpid_os(pid: pid_t) -> int {
        #[cfg(target_os = "linux")]
        fn WIFEXITED(status: i32) -> bool {
            (status & 0xffi32) == 0i32
        }

        #[cfg(target_os = "macos")]
        #[cfg(target_os = "freebsd")]
        fn WIFEXITED(status: i32) -> bool {
            (status & 0x7fi32) == 0i32
        }

        #[cfg(target_os = "linux")]
        fn WEXITSTATUS(status: i32) -> i32 {
            (status >> 8i32) & 0xffi32
        }

        #[cfg(target_os = "macos")]
        #[cfg(target_os = "freebsd")]
        fn WEXITSTATUS(status: i32) -> i32 {
            status >> 8i32
        }

        let status = os::waitpid(pid);
        ret if WIFEXITED(status) {
            WEXITSTATUS(status) as int
        } else {
            1
        };
    }
}

#[cfg(test)]
mod tests {

    import io::writer_util;

    // Regression test for memory leaks
    #[ignore(cfg(target_os = "win32"))] // FIXME
    fn test_leaks() {
        run::run_program("echo", []);
        run::start_program("echo", []);
        run::program_output("echo", []);
    }

    #[test]
    fn test_pipes() {
        let pipe_in = os::pipe();
        let pipe_out = os::pipe();
        let pipe_err = os::pipe();

        let pid =
            run::spawn_process(
                "cat", [], none, none,
                pipe_in.in, pipe_out.out, pipe_err.out);
        os::close(pipe_in.in);
        os::close(pipe_out.out);
        os::close(pipe_err.out);

        if pid == -1i32 { fail; }
        let expected = "test";
        writeclose(pipe_in.out, expected);
        let actual = readclose(pipe_out.in);
        readclose(pipe_err.in);
        os::waitpid(pid);

        log(debug, expected);
        log(debug, actual);
        assert (expected == actual);

        fn writeclose(fd: c_int, s: str) {
            #error("writeclose %d, %s", fd as int, s);
            let writer = io::fd_writer(fd, false);
            writer.write_str(s);

            os::close(fd);
        }

        fn readclose(fd: c_int) -> str {
            // Copied from run::program_output
            let file = os::fdopen(fd);
            let reader = io::FILE_reader(file, false);
            let buf = "";
            while !reader.eof() {
                let bytes = reader.read_bytes(4096u);
                buf += str::from_bytes(bytes);
            }
            os::fclose(file);
            ret buf;
        }
    }

    #[test]
    fn waitpid() {
        let pid = run::spawn_process("false", [],
                                     none, none,
                                     0i32, 0i32, 0i32);
        let status = run::waitpid(pid);
        assert status == 1;
    }

}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<|endoftext|>


<commit_before><commit_msg>Rust: cash units (#53)<commit_after>use std::collections::HashMap;

const CASH_UNITS: [u128; 15] = [
    500_00, 200_00, 100_00, 50_00, 20_00, 10_00, 5_00, 2_00, 1_00, 50, 20, 10, 5, 2, 1,
];

fn cash_units(amount: u128) -> HashMap<u128, u128> {
    let mut rest = amount;
    let mut result = HashMap::new();

    for cash_unit in &CASH_UNITS {
        let n = rest / cash_unit;
        result.insert(*cash_unit, n);
        rest %= cash_unit;
    }

    result
}

fn main() {
    let result = cash_units(197_278);
    assert_eq!(3, result[&500_00]);
    assert_eq!(2, result[&200_00]);
    assert_eq!(0, result[&100_00]);
    assert_eq!(1, result[&50_00]);
    assert_eq!(1, result[&20_00]);
    assert_eq!(0, result[&10_00]);
    assert_eq!(0, result[&5_00]);
    assert_eq!(1, result[&2_00]);
    assert_eq!(0, result[&1_00]);
    assert_eq!(1, result[&50]);
    assert_eq!(1, result[&20]);
    assert_eq!(0, result[&10]);
    assert_eq!(1, result[&5]);
    assert_eq!(1, result[&2]);
    assert_eq!(1, result[&1]);
}
<|endoftext|>


<commit_before><commit_msg>Added solution for problem 3 in rust.<commit_after>/*
The MIT License (MIT)

Copyright (c) 2016 Jakob Sinclair

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

fn main()
{
        let mut number: i64 = 600851475143;

        for i in 2..number / 2 + 1 {
                if i * i > number {
                        break;
                }
                while number % i == 0 {
                        number /= i;
                }
        }
        println!("Answer: {}", number);
}
<|endoftext|>


<commit_before><commit_msg>Closed Loops in Rustlang<commit_after>use std::string::ToString;

fn get_loops(c: char) -> u32 {
    match c {
      '0' | '6' | '9' => 1,
      '8' => 2,
      _ => 0,
    }
}

fn closed_loops<T>(n: T) -> u32 where T: ToString {
  n.to_string().chars().map(get_loops).sum()
}

fn main() {
  assert_eq!(closed_loops(16780), 4);
}
<|endoftext|>


<commit_before>struct PipelinedWriter<S, W>
where S: Stream,
S::Item: Encode<W>,
W: Send + 'static
{
    items: Fuse<S>,
    state: State<<<S::Item as Encode<W>>::Fut as IntoFuture>::Future, W, S::Item>,
}

impl<S, W> PipelinedWriter<S, W>
    where W: Write + Send + 'static,
S: Stream,
S::Item: Encode<W, Error = S::Error>,
S::Error: From<io::Error>
{
    fn new(stream: S, writer: BufWriter<W>) -> PipelinedWriter<S, W> {
        PipelinedWriter {
            items: stream.fuse(),
            state: State::Read(writer.flush()),
        }
    }
}

enum State<Fut, W, Item> {
    Empty,
    Read(Flush<W>),
    Reserve(Reserve<W>, Item),
    Write(Fut),
    Flush(Flush<W>),
}

impl<S, W> Future for PipelinedWriter<S, W>
    where W: Write + Send + 'static,
S: Stream,
S::Item: Encode<W, Error = S::Error>,
S::Error: From<io::Error>
{
    type Item = ();
    type Error = S::Error;

    fn poll(&mut self, mut tokens: &Tokens) -> Poll<(), S::Error> {
        // "steady state" is always Read or Write
        if let State::Flush(_) = self.state {
            panic!("Attempted to poll a PipelinedWriter in Flush state");
        }

        // First read and write (into a buffer) as many items as we can;
        // then, if possible, try to flush them out.
        loop {
            match mem::replace(&mut self.state, State::Empty) {
                State::Read(flush) => {
                    match self.items.poll(tokens) {
                        Poll::Err(e) => return Poll::Err(e),
                        Poll::Ok(Some(item)) => {
                            let writer = flush.into_inner();
                            if let Some(n) = item.size_hint() {
                                self.state = State::Reserve(writer.reserve(n), item);
                            } else {
                                self.state = State::Write(item.encode(writer).into_future());
                            }
                        }
                        Poll::Ok(None) | Poll::NotReady => {
                            self.state = State::Flush(flush);
                        }
                    }
                }
                State::Reserve(mut res, item) => {
                    match res.poll(tokens) {
                        Poll::Err((e, _)) => return Poll::Err(e.into()),
                        Poll::Ok(writer) => {
                            self.state = State::Write(item.encode(writer).into_future())
                        }
                        Poll::NotReady => {
                            self.state = State::Reserve(res, item);
                            return Poll::NotReady;
                        }
                    }
                }
                State::Write(mut fut) => {
                    match fut.poll(tokens) {
                        Poll::Err(e) => return Poll::Err(e.into()),
                        Poll::Ok(writer) => self.state = State::Read(writer.flush()),
                        Poll::NotReady => {
                            self.state = State::Write(fut);
                            return Poll::NotReady;
                        }
                    }
                }
                State::Flush(mut flush) => {
                    match flush.poll(tokens) {
                        Poll::Err((e, _)) => return Poll::Err(e.into()),
                        Poll::Ok(writer) => {
                            if self.items.is_done() {
                                // Nothing more to write to sink, and no more incoming items;
                                // we're done!
                                return Poll::Ok(());
                            } else {
                                self.state = State::Read(writer.flush());
                                return Poll::NotReady;
                            }
                        }
                        Poll::NotReady => {
                            self.state = State::Read(flush);
                            return Poll::NotReady;
                        }
                    }
                }
                State::Empty => unreachable!(),
            }

            tokens = &TOKENS_ALL;
        }
    }

    fn schedule(&mut self, wake: &Arc<Wake>) {
        match self.state {
            State::Read(ref mut flush) => {
                self.items.schedule(wake);
                if flush.is_dirty() {
                    flush.schedule(wake);
                }
            }
            State::Reserve(ref mut res, _) => res.schedule(wake),
            State::Write(ref mut fut) => fut.schedule(wake),
            State::Flush(_) => unreachable!(),
            State::Empty => unreachable!(),
        }
    }
}
<commit_msg>Delete old_pipe.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Added line app test<commit_after>
// Allow dead code since this is an example app.
#![allow(dead_code)]

use graphics::*;
use piston::*;
use {
    GameWindowBackEnd,
};

pub struct App;

fn return_test(c: &Context) -> BevelRectangleContext {
    c.rect(0.0, 0.0, 0.5, 0.5).bevel(0.1).clone()
}

impl Game<GameWindowBackEnd> for App {
    fn render(&self, c: &Context, gl: &mut Gl) {
        c.line(0.0, 0.0, 0.5, 0.5).square_border_radius(0.1).rgb(1.0, 0.0, 0.0).stroke(gl);
        match return_test(c) {
            c => c.rgb(0.0, 1.0, 0.0).fill(gl)
        };
    }
}

impl App {
    pub fn new() -> App {
        App
    }
}

<|endoftext|>


<commit_before><commit_msg>HTTP RPC request post method wrong name<commit_after><|endoftext|>


<commit_before><commit_msg>Add fixed point math types to util.<commit_after>#[derive(Copy, Clone)]
pub struct FixedPoint16 {
    inner: i16,
}

impl FixedPoint16 {
    #[inline]
    pub const fn wrap(value: i16) -> Self {
        FixedPoint16 { inner: value }
    }

    #[inline]
    pub const fn to_inner(self) -> i16 {
        self.inner
    }

    #[inline]
    pub const fn integer(self) -> i16 {
        self.inner >> 8
    }

    #[inline]
    pub const fn fractional(self) -> u16 {
        (self.inner & 0xFF) as u16
    }
}

impl Default for FixedPoint16 {
    fn default() -> Self {
        Self::wrap(0)
    }
}

impl std::ops::Add for FixedPoint16 {
    type Output = Self;
    #[inline]
    fn add(self, other: Self) -> Self {
        FixedPoint16::wrap(self.inner.wrapping_add(other.inner))
    }
}

impl std::ops::AddAssign for FixedPoint16 {
    #[inline]
    fn add_assign(&mut self, other: Self) {
        self.inner = self.inner.wrapping_add(other.inner);
    }
}

impl std::ops::Sub for FixedPoint16 {
    type Output = Self;
    #[inline]
    fn sub(self, other: Self) -> Self {
        FixedPoint16::wrap(self.inner.wrapping_sub(other.inner))
    }
}

impl std::ops::SubAssign for FixedPoint16 {
    #[inline]
    fn sub_assign(&mut self, other: Self) {
        self.inner = self.inner.wrapping_sub(other.inner);
    }
}

impl std::ops::Mul for FixedPoint16 {
    type Output = Self;
    #[inline]
    #[allow(clippy::suspicious_arithmetic_impl)]
    fn mul(self, other: Self) -> Self {
        FixedPoint16::wrap(self.inner.wrapping_mul(other.inner) >> 8)
    }
}

impl std::ops::MulAssign for FixedPoint16 {
    #[inline]
    #[allow(clippy::suspicious_op_assign_impl)]
    fn mul_assign(&mut self, other: Self) {
        self.inner = self.inner.wrapping_mul(other.inner) >> 8;
    }
}

impl std::ops::Neg for FixedPoint16 {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self {
        FixedPoint16::wrap(-self.inner)
    }
}

#[derive(Copy, Clone)]
pub struct FixedPoint32 {
    inner: i32,
}

impl FixedPoint32 {
    #[inline]
    pub const fn wrap(value: i32) -> Self {
        FixedPoint32 { inner: value }
    }

    #[inline]
    pub const fn to_inner(self) -> i32 {
        self.inner
    }

    #[inline]
    pub const fn integer(self) -> i32 {
        self.inner >> 8
    }

    #[inline]
    pub const fn fractional(self) -> u32 {
        (self.inner & 0xFF) as u32
    }
}

impl Default for FixedPoint32 {
    fn default() -> Self {
        Self::wrap(0)
    }
}

impl std::convert::From<u32> for FixedPoint32 {
    #[inline]
    fn from(original: u32) -> Self {
        FixedPoint32::wrap((original as i32) << 8)
    }
}

impl std::convert::From<u16> for FixedPoint32 {
    #[inline]
    fn from(original: u16) -> Self {
        FixedPoint32::wrap((original as u32 as i32) << 8)
    }
}

impl std::convert::From<i32> for FixedPoint32 {
    fn from(original: i32) -> Self {
        FixedPoint32::wrap(original << 8)
    }
}

impl std::convert::From<FixedPoint16> for FixedPoint32 {
    #[inline]
    fn from(original: FixedPoint16) -> Self {
        FixedPoint32::wrap(original.inner as i32)
    }
}

impl std::ops::Add for FixedPoint32 {
    type Output = Self;
    #[inline]
    fn add(self, other: Self) -> Self {
        FixedPoint32::wrap(self.inner.wrapping_add(other.inner))
    }
}

impl std::ops::AddAssign for FixedPoint32 {
    #[inline]
    fn add_assign(&mut self, other: Self) {
        self.inner = self.inner.wrapping_add(other.inner);
    }
}

impl std::ops::Sub for FixedPoint32 {
    type Output = Self;
    #[inline]
    fn sub(self, other: Self) -> Self {
        FixedPoint32::wrap(self.inner.wrapping_sub(other.inner))
    }
}

impl std::ops::SubAssign for FixedPoint32 {
    #[inline]
    fn sub_assign(&mut self, other: Self) {
        self.inner = self.inner.wrapping_sub(other.inner);
    }
}

impl std::ops::Mul for FixedPoint32 {
    type Output = Self;
    #[inline]
    #[allow(clippy::suspicious_arithmetic_impl)]
    fn mul(self, other: Self) -> Self {
        FixedPoint32::wrap(self.inner.wrapping_mul(other.inner) >> 8)
    }
}

impl std::ops::MulAssign for FixedPoint32 {
    #[inline]
    #[allow(clippy::suspicious_op_assign_impl)]
    fn mul_assign(&mut self, other: Self) {
        self.inner = self.inner.wrapping_mul(other.inner) >> 8;
    }
}

impl std::ops::Div for FixedPoint32 {
    type Output = Self;
    #[inline]
    fn div(self, other: Self) -> Self {
        FixedPoint32::wrap((self.inner << 16) / (other.inner << 8))
    }
}

impl std::ops::DivAssign for FixedPoint32 {
    #[inline]
    fn div_assign(&mut self, other: Self) {
        self.inner = (self.inner << 16) / (other.inner << 8);
    }
}

impl std::ops::Neg for FixedPoint32 {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self {
        FixedPoint32::wrap(-self.inner)
    }
}

impl std::fmt::Debug for FixedPoint32 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}fp32", self.integer(), self.fractional())
    }
}

impl std::fmt::Display for FixedPoint32 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}fp32", self.integer(), self.fractional())
    }
}
<|endoftext|>


<commit_before><commit_msg>Swap arg order for out/st op disassembly<commit_after><|endoftext|>


<commit_before><commit_msg>extra: Introduce a mutex type for native/green threads<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.

//! A proper mutex implementation regardless of the "flavor of task" which is
//! acquiring the lock.

// # Implementation of Rust mutexes
//
// Most answers to the question of "how do I use a mutex" are "use pthreads",
// but for Rust this isn't quite sufficient. Green threads cannot acquire an OS
// mutex because they can context switch among many OS threads, leading to
// deadlocks with other green threads.
//
// Another problem for green threads grabbing an OS mutex is that POSIX dictates
// that unlocking a mutex on a different thread from where it was locked is
// undefined behavior. Remember that green threads can migrate among OS threads,
// so this would mean that we would have to pin green threads to OS threads,
// which is less than ideal.
//
// ## Using deschedule/reawaken
//
// We already have primitives for descheduling/reawakening tasks, so they're the
// first obvious choice when implementing a mutex. The idea would be to have a
// concurrent queue that everyone is pushed on to, and then the owner of the
// mutex is the one popping from the queue.
//
// Unfortunately, this is not very performant for native tasks. The suspected
// reason for this is that each native thread is suspended on its own condition
// variable, unique from all the other threads. In this situation, the kernel
// has no idea what the scheduling semantics are of the user program, so all of
// the threads are distributed among all cores on the system. This ends up
// having very expensive wakeups of remote cores high up in the profile when
// handing off the mutex among native tasks. On the other hand, when using an OS
// mutex, the kernel knows that all native threads are contended on the same
// mutex, so they're in theory all migrated to a single core (fast context
// switching).
//
// ## Mixing implementations
//
// From that above information, we have two constraints. The first is that
// green threads can't touch os mutexes, and the second is that native tasks
// pretty much *must* touch an os mutex.
//
// As a compromise, the queueing implementation is used for green threads and
// the os mutex is used for native threads (why not have both?). This ends up
// leading to fairly decent performance for both native threads and green
// threads on various workloads (uncontended and contended).
//
// The crux of this implementation is an atomic work which is CAS'd on many many
// times in order to manage a few flags about who's blocking where and whether
// it's locked or not.

use std::rt::local::Local;
use std::rt::task::{BlockedTask, Task};
use std::rt::thread::Thread;
use std::sync::atomics;
use std::unstable::mutex;

use q = sync::mpsc_intrusive;

pub static LOCKED: uint = 1 << 0;
pub static GREEN_BLOCKED: uint = 1 << 1;
pub static NATIVE_BLOCKED: uint = 1 << 2;

/// A mutual exclusion primitive useful for protecting shared data
///
/// This mutex is an implementation of a lock for all flavors of tasks which may
/// be grabbing. A common problem with green threads is that they cannot grab
/// locks (if they reschedule during the lock a contender could deadlock the
/// system), but this mutex does *not* suffer this problem.
///
/// This mutex will properly block tasks waiting for the lock to become
/// available. The mutex can also be statically initialized or created via a
/// `new` constructor.
///
/// # Example
///
/// ```rust
/// use extra::sync::mutex::Mutex;
///
/// let mut m = Mutex::new();
/// let guard = m.lock();
/// // do some work
/// drop(guard); // unlock the lock
///
/// {
///     let _g = m.lock();
///     // do some work in a scope
/// }
///
/// // now the mutex is unlocked
/// ```
pub struct Mutex {
    priv lock: StaticMutex,
}

#[deriving(Eq)]
enum Flavor {
    Unlocked,
    TryLockAcquisition,
    GreenAcquisition,
    NativeAcquisition,
}

/// The static mutex type is provided to allow for static allocation of mutexes.
///
/// Note that this is a separate type because using a Mutex correctly means that
/// it needs to have a destructor run. In Rust, statics are not allowed to have
/// destructors. As a result, a `StaticMutex` has one extra method when compared
/// to a `Mutex`, a `destroy` method. This method is unsafe to call, and
/// documentation can be found directly on the method.
///
/// # Example
///
/// ```rust
/// use extra::sync::mutex::{StaticMutex, MUTEX_INIT};
///
/// static mut LOCK: StaticMutex = MUTEX_INIT;
///
/// unsafe {
///     let _g = LOCK.lock();
///     // do some productive work
/// }
/// // lock is unlocked here.
/// ```
pub struct StaticMutex {
    /// Current set of flags on this mutex
    priv state: atomics::AtomicUint,
    /// Type of locking operation currently on this mutex
    priv flavor: Flavor,
    /// uint-cast of the green thread waiting for this mutex
    priv green_blocker: uint,
    /// uint-cast of the native thread waiting for this mutex
    priv native_blocker: uint,
    /// an OS mutex used by native threads
    priv lock: mutex::Mutex,

    /// A concurrent mpsc queue used by green threads, along with a count used
    /// to figure out when to dequeue and enqueue.
    priv q: q::Queue<uint>,
    priv green_cnt: atomics::AtomicUint,
}

/// An RAII implementation of a "scoped lock" of a mutex. When this structure is
/// dropped (falls out of scope), the lock will be unlocked.
pub struct Guard<'a> {
    priv lock: &'a mut StaticMutex,
}

/// Static initialization of a mutex. This constant can be used to initialize
/// other mutex constants.
pub static MUTEX_INIT: StaticMutex = StaticMutex {
    lock: mutex::MUTEX_INIT,
    state: atomics::INIT_ATOMIC_UINT,
    flavor: Unlocked,
    green_blocker: 0,
    native_blocker: 0,
    green_cnt: atomics::INIT_ATOMIC_UINT,
    q: q::Queue {
        head: atomics::INIT_ATOMIC_UINT,
        tail: 0 as *mut q::Node<uint>,
        stub: q::DummyNode {
            next: atomics::INIT_ATOMIC_UINT,
        }
    }
};

impl StaticMutex {
    /// Attempts to grab this lock, see `Mutex::try_lock`
    pub fn try_lock<'a>(&'a mut self) -> Option<Guard<'a>> {
        // Attempt to steal the mutex from an unlocked state.
        //
        // FIXME: this can mess up the fairness of the mutex, seems bad
        match self.state.compare_and_swap(0, LOCKED, atomics::SeqCst) {
            0 => {
                assert!(self.flavor == Unlocked);
                self.flavor = TryLockAcquisition;
                Some(Guard::new(self))
            }
            _ => None
        }
    }

    /// Acquires this lock, see `Mutex::lock`
    pub fn lock<'a>(&'a mut self) -> Guard<'a> {
        // First, attempt to steal the mutex from an unlocked state. The "fast
        // path" needs to have as few atomic instructions as possible, and this
        // one cmpxchg is already pretty expensive.
        //
        // FIXME: this can mess up the fairness of the mutex, seems bad
        match self.state.compare_and_swap(0, LOCKED, atomics::SeqCst) {
            0 => {
                assert!(self.flavor == Unlocked);
                self.flavor = TryLockAcquisition;
                return Guard::new(self)
            }
            _ => {}
        }

        // After we've failed the fast path, then we delegate to the differnet
        // locking protocols for green/native tasks. This will select two tasks
        // to continue further (one native, one green).
        let t: ~Task = Local::take();
        let can_block = t.can_block();
        let native_bit;
        if can_block {
            self.native_lock(t);
            native_bit = NATIVE_BLOCKED;
        } else {
            self.green_lock(t);
            native_bit = GREEN_BLOCKED;
        }

        // After we've arbitrated among task types, attempt to re-acquire the
        // lock (avoids a deschedule). This is very important to do in order to
        // allow threads coming out of the native_lock function to try their
        // best to not hit a cvar in deschedule.
        let mut old = match self.state.compare_and_swap(0, LOCKED,
                                                        atomics::SeqCst) {
            0 => {
                self.flavor = if can_block {
                    NativeAcquisition
                } else {
                    GreenAcquisition
                };
                return Guard::new(self)
            }
            old => old,
        };

        // Alright, everything else failed. We need to deschedule ourselves and
        // flag ourselves as waiting. Note that this case should only happen
        // regularly in native/green contention. Due to try_lock and the header
        // of lock stealing the lock, it's also possible for native/native
        // contention to hit this location, but as less common.
        let t: ~Task = Local::take();
        t.deschedule(1, |task| {
            let task = unsafe { task.cast_to_uint() };
            if can_block {
                assert_eq!(self.native_blocker, 0);
                self.native_blocker = task;
            } else {
                assert_eq!(self.green_blocker, 0);
                self.green_blocker = task;
            }

            loop {
                assert_eq!(old & native_bit, 0);
                // If the old state was locked, then we need to flag ourselves
                // as blocking in the state. If the old state was unlocked, then
                // we attempt to acquire the mutex. Everything here is a CAS
                // loop that'll eventually make progress.
                if old & LOCKED != 0 {
                    old = match self.state.compare_and_swap(old,
                                                            old | native_bit,
                                                            atomics::SeqCst) {
                        n if n == old => return Ok(()),
                        n => n
                    };
                } else {
                    assert_eq!(old, 0);
                    old = match self.state.compare_and_swap(old,
                                                            old | LOCKED,
                                                            atomics::SeqCst) {
                        n if n == old => {
                            assert_eq!(self.flavor, Unlocked);
                            if can_block {
                                self.native_blocker = 0;
                                self.flavor = NativeAcquisition;
                            } else {
                                self.green_blocker = 0;
                                self.flavor = GreenAcquisition;
                            }
                            return Err(unsafe {
                                BlockedTask::cast_from_uint(task)
                            })
                        }
                        n => n,
                    };
                }
            }
        });

        Guard::new(self)
    }

    // Tasks which can block are super easy. These tasks just call the blocking
    // `lock()` function on an OS mutex
    fn native_lock(&mut self, t: ~Task) {
        Local::put(t);
        unsafe { self.lock.lock(); }
    }

    fn native_unlock(&mut self) {
        unsafe { self.lock.unlock(); }
    }

    fn green_lock(&mut self, t: ~Task) {
        // Green threads flag their presence with an atomic counter, and if they
        // fail to be the first to the mutex, they enqueue themselves on a
        // concurrent internal queue with a stack-allocated node.
        //
        // FIXME: There isn't a cancellation currently of an enqueue, forcing
        //        the unlocker to spin for a bit.
        if self.green_cnt.fetch_add(1, atomics::SeqCst) == 0 {
            Local::put(t);
            return
        }

        let mut node = q::Node::new(0);
        t.deschedule(1, |task| {
            unsafe {
                node.data = task.cast_to_uint();
                self.q.push(&mut node);
            }
            Ok(())
        });
    }

    fn green_unlock(&mut self) {
        // If we're the only green thread, then no need to check the queue,
        // otherwise the fixme above forces us to spin for a bit.
        if self.green_cnt.fetch_sub(1, atomics::SeqCst) == 1 { return }
        let node;
        loop {
            match unsafe { self.q.pop() } {
                Some(t) => { node = t; break; }
                None => Thread::yield_now(),
            }
        }
        let task = unsafe { BlockedTask::cast_from_uint((*node).data) };
        task.wake().map(|t| t.reawaken());
    }

    fn unlock(&mut self) {
        // Unlocking this mutex is a little tricky. We favor any task that is
        // manually blocked (not in each of the separate locks) in order to help
        // provide a little fairness (green threads will wake up the pending
        // native thread and native threads will wake up the pending green
        // thread).
        //
        // There's also the question of when we unlock the actual green/native
        // locking halves as well. If we're waking up someone, then we can wait
        // to unlock until we've acquired the task to wake up (we're guaranteed
        // the mutex memory is still valid when there's contenders), but as soon
        // as we don't find any contenders we must unlock the mutex, and *then*
        // flag the mutex as unlocked.
        //
        // This flagging can fail, leading to another round of figuring out if a
        // task needs to be woken, and in this case it's ok that the "mutex
        // halves" are unlocked, we're just mainly dealing with the atomic state
        // of the outer mutex.
        let flavor = self.flavor;
        self.flavor = Unlocked;

        let mut state = self.state.load(atomics::SeqCst);
        let mut unlocked = false;
        let task;
        loop {
            assert!(state & LOCKED != 0);
            if state & GREEN_BLOCKED != 0 {
                self.unset(state, GREEN_BLOCKED);
                task = unsafe {
                    BlockedTask::cast_from_uint(self.green_blocker)
                };
                self.green_blocker = 0;
                self.flavor = GreenAcquisition;
                break;
            } else if state & NATIVE_BLOCKED != 0 {
                self.unset(state, NATIVE_BLOCKED);
                task = unsafe {
                    BlockedTask::cast_from_uint(self.native_blocker)
                };
                self.native_blocker = 0;
                self.flavor = NativeAcquisition;
                break;
            } else {
                assert_eq!(state, LOCKED);
                if !unlocked {
                    match flavor {
                        GreenAcquisition => { self.green_unlock(); }
                        NativeAcquisition => { self.native_unlock(); }
                        TryLockAcquisition => {}
                        Unlocked => unreachable!()
                    }
                    unlocked = true;
                }
                match self.state.compare_and_swap(LOCKED, 0, atomics::SeqCst) {
                    LOCKED => return,
                    n => { state = n; }
                }
            }
        }
        if !unlocked {
            match flavor {
                GreenAcquisition => { self.green_unlock(); }
                NativeAcquisition => { self.native_unlock(); }
                TryLockAcquisition => {}
                Unlocked => unreachable!()
            }
        }

        task.wake().map(|t| t.reawaken());
    }

    /// Loops around a CAS to unset the `bit` in `state`
    fn unset(&mut self, mut state: uint, bit: uint) {
        loop {
            assert!(state & bit != 0);
            let new = state ^ bit;
            match self.state.compare_and_swap(state, new, atomics::SeqCst) {
                n if n == state => break,
                n => { state = n; }
            }
        }
    }

    /// Deallocates resources associated with this static mutex.
    ///
    /// This method is unsafe because it provides no guarantees that there are
    /// no active users of this mutex, and safety is not guaranteed if there are
    /// active users of this mutex.
    ///
    /// This method is required to ensure that there are no memory leaks on
    /// *all* platforms. It may be the case that some platforms do not leak
    /// memory if this method is not called, but this is not guaranteed to be
    /// true on all platforms.
    pub unsafe fn destroy(&mut self) {
        self.lock.destroy()
    }
}

impl Mutex {
    /// Creates a new mutex in an unlocked state ready for use.
    pub fn new() -> Mutex {
        Mutex {
            lock: StaticMutex {
                state: atomics::AtomicUint::new(0),
                flavor: Unlocked,
                green_blocker: 0,
                native_blocker: 0,
                green_cnt: atomics::AtomicUint::new(0),
                q: q::Queue::new(),
                lock: unsafe { mutex::Mutex::new() },
            }
        }
    }

    /// Attempts to acquire this lock.
    ///
    /// If the lock could not be acquired at this time, then `None` is returned.
    /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
    /// guard is dropped.
    ///
    /// This function does not block.
    pub fn try_lock<'a>(&'a mut self) -> Option<Guard<'a>> {
        self.lock.try_lock()
    }

    /// Acquires a mutex, blocking the current task until it is able to do so.
    ///
    /// This function will block the local task until it is availble to acquire
    /// the mutex. Upon returning, the task is the only task with the mutex
    /// held. An RAII guard is returned to allow scoped unlock of the lock. When
    /// the guard goes out of scope, the mutex will be unlocked.
    pub fn lock<'a>(&'a mut self) -> Guard<'a> { self.lock.lock() }
}

impl<'a> Guard<'a> {
    fn new<'b>(lock: &'b mut StaticMutex) -> Guard<'b> {
        if cfg!(debug) {
            assert!(lock.flavor != Unlocked);
            assert!(lock.state.load(atomics::SeqCst) & LOCKED != 0);
        }
        Guard { lock: lock }
    }
}

#[unsafe_destructor]
impl<'a> Drop for Guard<'a> {
    #[inline]
    fn drop(&mut self) {
        self.lock.unlock();
    }
}

impl Drop for Mutex {
    fn drop(&mut self) {
        // This is actually safe b/c we know that there is no further usage of
        // this mutex (it's up to the user to arrange for a mutex to get
        // dropped, that's not our job)
        unsafe { self.lock.destroy() }
    }
}

#[cfg(test)]
mod test {
    extern mod native;
    use super::{Mutex, StaticMutex, MUTEX_INIT};

    #[test]
    fn smoke() {
        let mut m = Mutex::new();
        drop(m.lock());
        drop(m.lock());
    }

    #[test]
    fn smoke_static() {
        static mut m: StaticMutex = MUTEX_INIT;
        unsafe {
            drop(m.lock());
            drop(m.lock());
            m.destroy();
        }
    }

    #[test]
    fn lots_and_lots() {
        static mut m: StaticMutex = MUTEX_INIT;
        static mut CNT: uint = 0;
        static M: uint = 1000;
        static N: uint = 3;

        fn inc() {
            for _ in range(0, M) {
                unsafe {
                    let _g = m.lock();
                    CNT += 1;
                }
            }
        }

        let (p, c) = SharedChan::new();
        for _ in range(0, N) {
            let c2 = c.clone();
            do native::task::spawn { inc(); c2.send(()); }
            let c2 = c.clone();
            do spawn { inc(); c2.send(()); }
        }

        drop(c);
        for _ in range(0, 2 * N) {
            p.recv();
        }
        assert_eq!(unsafe {CNT}, M * N * 2);
        unsafe {
            m.destroy();
        }
    }

    #[test]
    fn trylock() {
        let mut m = Mutex::new();
        assert!(m.try_lock().is_some());
    }
}
<|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 sync::{Mutex, Condvar};

/// A barrier enables multiple threads to synchronize the beginning
/// of some computation.
///
/// ```
/// use std::sync::{Arc, Barrier};
/// use std::thread;
///
/// let barrier = Arc::new(Barrier::new(10));
/// for _ in 0..10 {
///     let c = barrier.clone();
///     // The same messages will be printed together.
///     // You will NOT see any interleaving.
///     thread::spawn(move|| {
///         println!("before wait");
///         c.wait();
///         println!("after wait");
///     });
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Barrier {
    lock: Mutex<BarrierState>,
    cvar: Condvar,
    num_threads: usize,
}

// The inner state of a double barrier
struct BarrierState {
    count: usize,
    generation_id: usize,
}

/// A result returned from wait.
///
/// Currently this opaque structure only has one method, `.is_leader()`. Only
/// one thread will receive a result that will return `true` from this function.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct BarrierWaitResult(bool);

impl Barrier {
    /// Creates a new barrier that can block a given number of threads.
    ///
    /// A barrier will block `n`-1 threads which call `wait` and then wake up
    /// all threads at once when the `n`th thread calls `wait`.
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn new(n: usize) -> Barrier {
        Barrier {
            lock: Mutex::new(BarrierState {
                count: 0,
                generation_id: 0,
            }),
            cvar: Condvar::new(),
            num_threads: n,
        }
    }

    /// Blocks the current thread until all threads has rendezvoused here.
    ///
    /// Barriers are re-usable after all threads have rendezvoused once, and can
    /// be used continuously.
    ///
    /// A single (arbitrary) thread will receive a `BarrierWaitResult` that
    /// returns `true` from `is_leader` when returning from this function, and
    /// all other threads will receive a result that will return `false` from
    /// `is_leader`
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn wait(&self) -> BarrierWaitResult {
        let mut lock = self.lock.lock().unwrap();
        let local_gen = lock.generation_id;
        lock.count += 1;
        if lock.count < self.num_threads {
            // We need a while loop to guard against spurious wakeups.
            // http://en.wikipedia.org/wiki/Spurious_wakeup
            while local_gen == lock.generation_id &&
                  lock.count < self.num_threads {
                lock = self.cvar.wait(lock).unwrap();
            }
            BarrierWaitResult(false)
        } else {
            lock.count = 0;
            lock.generation_id += 1;
            self.cvar.notify_all();
            BarrierWaitResult(true)
        }
    }
}

impl BarrierWaitResult {
    /// Returns whether this thread from `wait` is the "leader thread".
    ///
    /// Only one thread will have `true` returned from their result, all other
    /// threads will have `false` returned.
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn is_leader(&self) -> bool { self.0 }
}

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

    use sync::{Arc, Barrier};
    use sync::mpsc::{channel, TryRecvError};
    use thread;

    #[test]
    fn test_barrier() {
        const N: usize = 10;

        let barrier = Arc::new(Barrier::new(N));
        let (tx, rx) = channel();

        for _ in 0..N - 1 {
            let c = barrier.clone();
            let tx = tx.clone();
            thread::spawn(move|| {
                tx.send(c.wait().is_leader()).unwrap();
            });
        }

        // At this point, all spawned threads should be blocked,
        // so we shouldn't get anything from the port
        assert!(match rx.try_recv() {
            Err(TryRecvError::Empty) => true,
            _ => false,
        });

        let mut leader_found = barrier.wait().is_leader();

        // Now, the barrier is cleared and we should get data.
        for _ in 0..N - 1 {
            if rx.recv().unwrap() {
                assert!(!leader_found);
                leader_found = true;
            }
        }
        assert!(leader_found);
    }
}
<commit_msg>Fix missing console output in `Barrier` example<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 sync::{Mutex, Condvar};

/// A barrier enables multiple threads to synchronize the beginning
/// of some computation.
///
/// ```
/// use std::sync::{Arc, Barrier};
/// use std::thread;
///
/// let mut handles = Vec::with_capacity(10);
/// let barrier = Arc::new(Barrier::new(10));
/// for _ in 0..10 {
///     let c = barrier.clone();
///     // The same messages will be printed together.
///     // You will NOT see any interleaving.
///     handles.push(thread::spawn(move|| {
///         println!("before wait");
///         c.wait();
///         println!("after wait");
///     }));
/// }
/// // Wait for other threads to finish.
/// for handle in handles {
///     handle.join().unwrap();
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Barrier {
    lock: Mutex<BarrierState>,
    cvar: Condvar,
    num_threads: usize,
}

// The inner state of a double barrier
struct BarrierState {
    count: usize,
    generation_id: usize,
}

/// A result returned from wait.
///
/// Currently this opaque structure only has one method, `.is_leader()`. Only
/// one thread will receive a result that will return `true` from this function.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct BarrierWaitResult(bool);

impl Barrier {
    /// Creates a new barrier that can block a given number of threads.
    ///
    /// A barrier will block `n`-1 threads which call `wait` and then wake up
    /// all threads at once when the `n`th thread calls `wait`.
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn new(n: usize) -> Barrier {
        Barrier {
            lock: Mutex::new(BarrierState {
                count: 0,
                generation_id: 0,
            }),
            cvar: Condvar::new(),
            num_threads: n,
        }
    }

    /// Blocks the current thread until all threads has rendezvoused here.
    ///
    /// Barriers are re-usable after all threads have rendezvoused once, and can
    /// be used continuously.
    ///
    /// A single (arbitrary) thread will receive a `BarrierWaitResult` that
    /// returns `true` from `is_leader` when returning from this function, and
    /// all other threads will receive a result that will return `false` from
    /// `is_leader`
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn wait(&self) -> BarrierWaitResult {
        let mut lock = self.lock.lock().unwrap();
        let local_gen = lock.generation_id;
        lock.count += 1;
        if lock.count < self.num_threads {
            // We need a while loop to guard against spurious wakeups.
            // http://en.wikipedia.org/wiki/Spurious_wakeup
            while local_gen == lock.generation_id &&
                  lock.count < self.num_threads {
                lock = self.cvar.wait(lock).unwrap();
            }
            BarrierWaitResult(false)
        } else {
            lock.count = 0;
            lock.generation_id += 1;
            self.cvar.notify_all();
            BarrierWaitResult(true)
        }
    }
}

impl BarrierWaitResult {
    /// Returns whether this thread from `wait` is the "leader thread".
    ///
    /// Only one thread will have `true` returned from their result, all other
    /// threads will have `false` returned.
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn is_leader(&self) -> bool { self.0 }
}

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

    use sync::{Arc, Barrier};
    use sync::mpsc::{channel, TryRecvError};
    use thread;

    #[test]
    fn test_barrier() {
        const N: usize = 10;

        let barrier = Arc::new(Barrier::new(N));
        let (tx, rx) = channel();

        for _ in 0..N - 1 {
            let c = barrier.clone();
            let tx = tx.clone();
            thread::spawn(move|| {
                tx.send(c.wait().is_leader()).unwrap();
            });
        }

        // At this point, all spawned threads should be blocked,
        // so we shouldn't get anything from the port
        assert!(match rx.try_recv() {
            Err(TryRecvError::Empty) => true,
            _ => false,
        });

        let mut leader_found = barrier.wait().is_leader();

        // Now, the barrier is cleared and we should get data.
        for _ in 0..N - 1 {
            if rx.recv().unwrap() {
                assert!(!leader_found);
                leader_found = true;
            }
        }
        assert!(leader_found);
    }
}
<|endoftext|>


<commit_before><commit_msg>added aggregation query test<commit_after><|endoftext|>


<commit_before><commit_msg>Simple multiplication using stdin<commit_after>// Compute product of two numbers while accepting value from standard input.

use std::io; // imports io library from standard library
fn main() {
    let mut a = String::new(); //creates new, empty  String
    let mut b = String::new();
    let c: u32;

    println!("Enter value a:");
    io::stdin().read_line(&mut a)
             .ok()
             .expect("Failed to read value");

    println!("Enter value b:");
    io::stdin().read_line(&mut b)
             .ok()
             .expect("Failed to read value");

    //Shadowing lets us to re-use the old name.
    // parse() method on String converts the String into number
    let a: u32 = a.trim().parse()
              .ok()
              .expect("Please type a number");

    let b: u32 = b.trim().parse()
              .ok()
              .expect("Please type a number");

    c = a * b;
    println!("Product of {} * {} is {} ", a, b, c);
}
<|endoftext|>


<commit_before><commit_msg>Add rust collatz snippet<commit_after>fn main() {
    println!("Basic collatz fun - recursive go function");
    r(15);
}

fn r(n: i32) -> i32 {
    println!("{}", n);
    if n == 1 {
        return 1;
    } else {
        let n2 = if n%2 == 0 { n/2 } else { n*3 + 1 };
        return r(n2);
    }
}
<|endoftext|>


<commit_before><commit_msg>added enums example<commit_after>#![allow(dead_code)]

// Enums are an Algebric Data Type
enum NumberorNothing {
Number(i32),
Nothing
}

// hoisting helper to avoid boilerplate code
use self::NumberorNothing::{Number,Nothing};

fn vec_min(vec: Vec<i32>) -> NumberorNothing {
	let mut min = NumberorNothing::Nothing;
	for el in vec {
	match min {
		NumberorNothing::Nothing => {min = NumberorNothing::Number(el);},
		NumberorNothing::Number(n) => {let new_min = min_i32(n, el); min = NumberorNothing::Number(new_min);}
	}
	}
return min;
}

// comparision function
fn min_i32(a:i32,b:i32) -> i32 {

if a > b { a }
else { b }

}

fn read_vec() -> Vec<i32> {
	vec![2,5,3,56,7,4]
}

fn print_min_result(n:NumberorNothing) {
	match n {
		Nothing => print!("Error: The vector is Empty"),
		Number(n) => printl!("The minimum element is: {} ",n);
	}
}

// Entry point
fn main(){
	let vec = read_vec();
	let min = vec_min(vec);
	print_min_result(min);
}
<|endoftext|>


<commit_before><commit_msg>chore: app with clap<commit_after><|endoftext|>


<commit_before><commit_msg>add test for where clauses mentioning const params<commit_after>// check-pass
// revisions: full min
#![cfg_attr(full, feature(const_generics))]
#![cfg_attr(full, allow(incomplete_features))]
#![cfg_attr(min, feature(min_const_generics))]

trait Bar<const N: usize> { fn bar() {} }
trait Foo<const N: usize>: Bar<N> {}

fn test<T, const N: usize>() where T: Foo<N> {
    <T as Bar<N>>::bar();
}

struct Faz<const N: usize>;

impl<const N: usize> Faz<N> {
    fn test<T>() where T: Foo<N> {
        <T as Bar<N>>::bar()
    }
}

trait Fiz<const N: usize> {
    fn fiz<T>() where T: Foo<N> {
        <T as Bar<N>>::bar();
    }
}

impl<const N: usize> Bar<N> for u8 {}
impl<const N: usize> Foo<N> for u8 {}
impl<const N: usize> Fiz<N> for u8 {}
fn main() {
    test::<u8, 13>();
    Faz::<3>::test::<u8>();
    <u8 as Fiz<13>>::fiz::<u8>();
}
<|endoftext|>


<commit_before><commit_msg>(feat) Implement Priority Frame<commit_after>use super::super::StreamId;
use super::frames::{
    Frame,
    Flag,
    parse_padded_payload,
    pack_header,
    RawFrame,
    FrameHeader
};

/// The struct represents the dependency information that can be attached to a stream
/// and sent within HEADERS frame
#[derive(PartialEq)]
#[derive(Debug)]
#[derive(Clone)]
pub struct StreamDependency {
    /// The ID of the stream that a particular stream depends on
    pub stream_id: StreamId,
    /// The weight for the stream. The value exposed (and set) here is always
    /// in the range [0, 255], instead of [1, 256] so that the value fits
    /// into a `u8`.
    pub weight: u8,
    /// A flag indicating whether the stream dependency is exclusive.
    pub is_exclusive: bool,
}

impl StreamDependency {
    /// Creates a new `StreamDependency` with the given stream Id, weight, and
    /// exclusivity.
    pub fn new(stream_id: StreamId, weight: u8, is_exclusive: bool)
            -> StreamDependency {
        StreamDependency {
            stream_id: stream_id,
            weight: weight,
            is_exclusive: is_exclusive,
        }
    }

    /// Parses the 5-byte length frame
    ///
    /// # Panics
    ///
    /// If the frame is less than 5 bytes, the method will panic
    pub fn parse(buf: &[u8]) -> StreamDependency {
        // The most significant bit of the first byte is the "E" bit indicating
        // whether the dependency is exclusive.
        let is_exclusive = buf[0] & 0x80 != 0;
        let stream_id = {
            // Parse the first 4 bytes into a u32
            let mut id = unpack_octets_4!(buf, 0, u32);
            // and clear the first bit since the stream id is only 31 bits.
            id &= !(1 << 31);
            id
        };

        StreamDependency {
            stream_id: stream_id,
            weight: buf[4],
            is_exclusive: is_exclusive,
        }
    }

    /// Serializes the `StreamDependency` into a 5-byte buffer representing the
    /// dependency description.
    pub fn serialize(&self) -> [u8: 5] {
        let e_bit = if self.is_exclusive {
            1 << 7
        } else {
            0
        };
        [
            (((self.stream_id >> 24) & 0x000000FF) as u8) | e_bit,
            (((self.stream_id >> 16) & 0x000000FF) as u8),
            (((self.stream_id >>  8) & 0x000000FF) as u8),
            (((self.stream_id >>  0) & 0x000000FF) as u8),
            self.weight,
        ]
    }
}

/// A struct representing the PRIORITY frmas of HTTP/2
#[derive(PartialEq)]
#[derive(Debug)]
pub struct PriorityFrame {
    /// The id of the stream with which this frame is associated
    pub stream_id: StreamId,
    /// The stream dependency information
    pub stream_dep: StreamDependency,
    /// The data in frame
    pub data: Vec<u8>,
}

impl PriorityFrame {
    pub fn new(stream_id: StreamId, stream_dep: StreamDependency)
            -> PriorityFrame {
        PriorityFrame {
            stream_id: stream_id,
            stream_dep: stream_dep,
        }
    }

    /// Returns the length of the payload of the current frame
    fn payload_len(&self) -> u32 {
        &self.data.len() as u32
    }
}

impl Frame for PriorityFrame {
    /// Creates a new `PriorityFrame` with the given `RawFrame` (i.e. header and
    /// payload), if possible.
    ///
    /// # Returns
    ///
    /// `None` if a valid `PriorityFrame` cannot be constructed from the give
    /// `RawFrame`. The stream ID *MUST NOT* be 0.
    ///
    /// Otherwise, returns a newly contructed `PriorityFrame`
    fn from_raw(raw_frame: RawFrame) -> Option<PriorityFrame> {
        // Unpack the header
        let (len, frame_type, flags, stream_id) = raw_frame.header;
        // Check that the frame type is correct for this frame implementation
        if frame_type != 0x2 {
            return None;
        }
        // Check that the length given in the header matches the payload
        // if not, soemthing went wrong and we do not consider this as
        // a valid frame.
        if (len as u32) != raw_frame.payload.len() {
            return None;
        }
        // Check that the length of the payload is 5 bytes
        // If not, this is not a valid frame
        if raw_frame.payload.len() != 5 {
            return None;
        }
        // Check that the PRIORITY frame is not associated to stream 0
        // If it is, this is not a valid frame
        if stream_id == 0 {
            return None;
        }
        // Extract the stream dependecy info from the payload
        let stream_dep = Some(StreamDependency::parse(&raw_frame.payload));

        Some(PriorityFrame {
            stream_id: stream_id,
            stream_dep: stream_dep,
        })
    }

    /// Returns the `StreamId` of the stream to which the frame is associated
    ///
    /// A `PriorityFrame` always has to be associated to stream `0`.
    fn get_stream_id(&self) -> StreamId {
        self.stream_id
    }

    /// Returns a `FrameHeader` based on the current state of the `Frame`.
    fn get_header(&self) -> FrameHeader {
        (self.payload_len(), 0x2, 0, self.stream_id)
    }

    /// Returns a `Vec` with the serialized representation of the frame.
    fn serialize(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(self.payload_len() as usize);
        // The header
        buf.extend(pack_header(&self.get_header()).to_vec().into_iter());
        // and then the body
        buf.extend(&self.payload.serialize().to_vec().into_iter());

        buf
    }
}

<|endoftext|>


<commit_before><commit_msg>examples: add hyphenation example<commit_after>#[cfg(feature = "hyphenation")]
extern crate hyphenation;
extern crate textwrap;

#[cfg(feature = "hyphenation")]
use hyphenation::{Language, Load, Standard};
#[cfg(feature = "hyphenation")]
use textwrap::Wrapper;

#[cfg(not(feature = "hyphenation"))]
fn main() {
    println!("Please run this example as");
    println!();
    println!("  cargo run --example hyphenation --features hyphenation");
}

#[cfg(feature = "hyphenation")]
fn main() {
    let text = "textwrap: a small library for wrapping text.";
    let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
    let wrapper = Wrapper::with_splitter(18, dictionary);
    println!("{}", wrapper.fill(text));
}
<|endoftext|>


<commit_before><commit_msg>Add problem #13<commit_after>use std;

fn main() {
    let input = "
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690";

    let sum = vec::foldl(0u, vec::filter_map(str::lines(str::trim(input))) { |line|
        ret uint::from_str(str::slice(line, 0u, 12u));
    }) { |sum, num| sum + num };

    std::io::println(str::slice(#fmt("%u", sum), 0u, 10u));
}<|endoftext|>


<commit_before><commit_msg>Remove redundant acceleration reset<commit_after><|endoftext|>


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

extern crate immutable_map;
extern crate rand;
extern crate test;

use immutable_map::Map;
use rand::{Rng, IsaacRng};
use test::Bencher;

#[bench]
fn insert(b: &mut Bencher) {
    let mut rng = IsaacRng::new_unseeded();
    let mut map = Map::new();
    let mut v: usize = 0;

    b.iter(|| {
        let k = rng.gen::<u16>() as usize;

        map = map.insert(k, v);

        v += 1;
    })
}

#[bench]
fn get(b: &mut Bencher) {
    let mut rng = IsaacRng::new_unseeded();
    let mut map = Map::new();
    let mut v: usize = 0;

    for _ in 0 .. 10000 {
        let k = rng.gen::<u16>() as usize;
        map = map.insert(k, v);
        v += 1;
    }

    b.iter(|| {
        let k = rng.gen::<u16>() as usize;

        map.get(&k);
    })
}

#[bench]
fn remove(b: &mut Bencher) {
    let input_size = 10000;

    let mut rng = IsaacRng::new_unseeded();
    let mut inputs = Vec::new();
    let mut map = Map::new();
    let mut v = 0usize;

    for _ in 0 .. input_size {
        let k = rng.gen::<u16>() as usize;
        inputs.push(k);
        map = map.insert(k, v);
        v += 1;
    }

    rng.shuffle(&mut inputs);
    let mut idx = 0;

    b.iter(|| {
        let k = inputs[idx];

        if let Some((removed, _)) = map.remove(&k) {
            map = removed;
        }

        idx = (idx + 1) % input_size;
    })
}

#[bench]
fn iter_small(b: &mut Bencher) {
    let mut rng = IsaacRng::new_unseeded();
    let mut map = Map::new();
    let mut v: usize = 0;

    for _ in 0 .. 10 {
        let k = rng.gen::<u16>() as usize;
        map = map.insert(k, v);
        v += 1;
    }

    b.iter(|| {
        map.iter().count();
    })
}

#[bench]
fn iter_large(b: &mut Bencher) {
    let mut rng = IsaacRng::new_unseeded();
    let mut map = Map::new();
    let mut v: usize = 0;

    for _ in 0 .. 1000 {
        let k = rng.gen::<u16>() as usize;
        map = map.insert(k, v);
        v += 1;
    }

    b.iter(|| {
        map.iter().count();
    })
}
<|endoftext|>


<commit_before><commit_msg>auto merge of #7802 : catamorphism/rust/issue-6128, r=catamorphism<commit_after>// Copyright 2013 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.

// xfail-test

use std::hashmap::HashMap;

trait Graph<Node, Edge> {
    fn f(&self, Edge);

}

impl<E> Graph<int, E> for HashMap<int, int> {
    fn f(&self, _e: E) {
        fail!();
    }
}

fn main() {
    let g : ~HashMap<int, int> = ~HashMap::new();
    let _g2 : ~Graph<int,int> = g as ~Graph<int,int>;
}
<|endoftext|>


<commit_before><commit_msg>Rust dispatch options<commit_after>fn main() {
    "hello".to_string(); // implicit dispatch

    // Group of `qualified` methods:
    str::to_string("hello"); // explicit dispatch by struct
    ToString::to_string("hello"); // explicit dispatch by trait

    // `Fully qualified` method call ()
    <str as ToString>::to_string("hello"); // wow!
}
<|endoftext|>


<commit_before><commit_msg>Implement day 14 in rust.<commit_after>use std::io;
use std::collections::VecDeque;

fn hash(input: &str, output: &mut[u8])
{
    let mut buffer = [0u8; 256];
    for i in {0..256} {
        buffer[i] = i as u8;
    }

    let mut actual_key = String::from(input);
    // Needed to convert to hex
    actual_key += "\x11\x1f\x49\x2f\x17";

    let mut index = 0u8;
    let mut skip = 0u8;

    for _ in 0..64 {
        for c in actual_key.chars() {
            let offset = c as u8;

            for i in 0..(offset / 2) {
                let i1 = index.wrapping_add(i) as usize;
                let i2 = index.wrapping_add(offset).wrapping_sub(i).wrapping_sub(1) as usize;

                let temp = buffer[i1];
                buffer[i1] = buffer[i2];
                buffer[i2] = temp;
            }

            index = index.wrapping_add(offset).wrapping_add(skip);
            skip = skip.wrapping_add(1);
        }
    }

    for (i, b) in buffer.iter().enumerate() {
        output[i / 16] ^= b;
    }
}

fn count_ones(input: &[[u8; 16]]) -> u32
{
    let mut total: u32 = 0;
    for row in input {
        let row_total: u32 = row.iter().map(|x| x.count_ones()).sum();
        total += row_total;
    }

    return total;
}

fn get_hash(input: &str) -> [[u8; 16]; 128]
{
    let mut hash_buffer = [[0u8; 16]; 128];

    for i in 0..128 {
        let mut hash_key = String::from(input);
        hash_key += "-";
        hash_key += &i.to_string();

        hash(&hash_key, &mut hash_buffer[i]);
    }

    return hash_buffer;
}

fn is_used(hashes: &[[u8; 16]], y: usize, x: usize) -> bool
{
    let byte = hashes[y][x / 8];

    return (byte & (1 << (7 - (x % 8)))) != 0;
}

fn count_groups(hashes: &[[u8; 16]]) -> u32
{
    let mut visited = [[false; 128]; 128];

    let mut groups = 0u32;

    for x in 0..128 {
        for y in 0..128 {
            if visited[x][y] || !is_used(hashes, x, y) {
                continue;
            }
            visited[x][y] = true;
            groups += 1;

            let mut todo = VecDeque::new();
            todo.push_back((x, y));

            while !todo.is_empty() {
                let (cur_x, cur_y) = todo.pop_front().unwrap();

                let x_min = if cur_x == 0 { 0 } else { cur_x - 1 };
                let y_min = if cur_y == 0 { 0 } else { cur_y - 1 };
                let x_max = if cur_x == 127 { 128 } else { cur_x + 2 };
                let y_max = if cur_y == 127 { 128 } else { cur_y + 2 };

                for x_new in x_min..(x_max) {
                    for y_new in y_min..(y_max) {
                        if (cur_x != x_new) ^ (cur_y != y_new) && !visited[x_new][y_new] && is_used(hashes, x_new, y_new) {
                            visited[x_new][y_new] = true;
                            todo.push_back((x_new, y_new));
                        }
                    }
                }
            }
        }
    }

    return groups;
}

fn main()
{
    let reader = io::stdin();

    let mut input = String::new();
    reader.read_line(&mut input).unwrap();

    let hashes = get_hash(input.trim());

    println!("Part 1: {}", count_ones(&hashes));
    println!("Part 2: {}", count_groups(&hashes));
}
<|endoftext|>


<commit_before><commit_msg>Explicitly specify the features that the engine requires from Vulkan<commit_after><|endoftext|>


<commit_before><commit_msg>Further improvements towards getting Vulkan multithreaded rendering working<commit_after><|endoftext|>