<commit_before>extern crate tempdir;

use nix::unistd::*;
use nix::unistd::ForkResult::*;
use nix::sys::wait::*;
use nix::sys::stat;
use std::{env, iter};
use std::ffi::CString;
use std::fs::File;
use std::io::Write;
use std::os::unix::prelude::*;
use tempfile::tempfile;
use tempdir::TempDir;
use libc::{_exit, off_t};

#[test]
fn test_fork_and_waitpid() {
    #[allow(unused_variables)]
    let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");

    // Safe: Child only calls `_exit`, which is signal-safe
    match fork() {
        Ok(Child) => unsafe { _exit(0) },
        Ok(Parent { child }) => {
            // assert that child was created and pid > 0
            let child_raw: ::libc::pid_t = child.into();
            assert!(child_raw > 0);
            let wait_status = waitpid(child, None);
            match wait_status {
                // assert that waitpid returned correct status and the pid is the one of the child
                Ok(WaitStatus::Exited(pid_t, _)) =>  assert!(pid_t == child),

                // panic, must never happen
                s @ Ok(_) => panic!("Child exited {:?}, should never happen", s),

                // panic, waitpid should never fail
                Err(s) => panic!("Error: waitpid returned Err({:?}", s)
            }

        },
        // panic, fork should never fail unless there is a serious problem with the OS
        Err(_) => panic!("Error: Fork Failed")
    }
}

#[test]
fn test_wait() {
    // Grab FORK_MTX so wait doesn't reap a different test's child process
    #[allow(unused_variables)]
    let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");

    // Safe: Child only calls `_exit`, which is signal-safe
    let pid = fork();
    match pid {
        Ok(Child) => unsafe { _exit(0) },
        Ok(Parent { child }) => {
            let wait_status = wait();

            // just assert that (any) one child returns with WaitStatus::Exited
            assert_eq!(wait_status, Ok(WaitStatus::Exited(child, 0)));
        },
        // panic, fork should never fail unless there is a serious problem with the OS
        Err(_) => panic!("Error: Fork Failed")
    }
}

#[test]
fn test_mkstemp() {
    let mut path = env::temp_dir();
    path.push("nix_tempfile.XXXXXX");

    let result = mkstemp(&path);
    match result {
        Ok((fd, path)) => {
            close(fd).unwrap();
            unlink(path.as_path()).unwrap();
        },
        Err(e) => panic!("mkstemp failed: {}", e)
    }
}

#[test]
fn test_mkstemp_directory() {
    // mkstemp should fail if a directory is given
    assert!(mkstemp(&env::temp_dir()).is_err());
}

#[test]
fn test_mkfifo() {
    let tempdir = TempDir::new("nix-test_mkfifo").unwrap();
    let mkfifo_fifo = tempdir.path().join("mkfifo_fifo");

    mkfifo(&mkfifo_fifo, stat::S_IRUSR).unwrap();

    let stats = stat::stat(&mkfifo_fifo).unwrap();
    let typ = stat::SFlag::from_bits_truncate(stats.st_mode);
    assert!(typ == stat::S_IFIFO);
}

#[test]
fn test_mkfifo_directory() {
    // mkfifo should fail if a directory is given
    assert!(mkfifo(&env::temp_dir(), stat::S_IRUSR).is_err());
}

#[test]
fn test_getpid() {
    let pid: ::libc::pid_t = getpid().into();
    let ppid: ::libc::pid_t = getppid().into();
    assert!(pid > 0);
    assert!(ppid > 0);
}

#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux_android {
    use nix::unistd::gettid;

    #[test]
    fn test_gettid() {
        let tid: ::libc::pid_t = gettid().into();
        assert!(tid > 0);
    }
}

macro_rules! execve_test_factory(
    ($test_name:ident, $syscall:ident, $exe: expr) => (
    #[test]
    fn $test_name() {
        #[allow(unused_variables)]
        let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");
        // The `exec`d process will write to `writer`, and we'll read that
        // data from `reader`.
        let (reader, writer) = pipe().unwrap();

        // Safe: Child calls `exit`, `dup`, `close` and the provided `exec*` family function.
        // NOTE: Technically, this makes the macro unsafe to use because you could pass anything.
        //       The tests make sure not to do that, though.
        match fork().unwrap() {
            Child => {
                // Close stdout.
                close(1).unwrap();
                // Make `writer` be the stdout of the new process.
                dup(writer).unwrap();
                // exec!
                $syscall(
                    $exe,
                    &[CString::new(b"".as_ref()).unwrap(),
                      CString::new(b"-c".as_ref()).unwrap(),
                      CString::new(b"echo nix!!! && echo foo=$foo && echo baz=$baz"
                                   .as_ref()).unwrap()],
                    &[CString::new(b"foo=bar".as_ref()).unwrap(),
                      CString::new(b"baz=quux".as_ref()).unwrap()]).unwrap();
            },
            Parent { child } => {
                // Wait for the child to exit.
                waitpid(child, None).unwrap();
                // Read 1024 bytes.
                let mut buf = [0u8; 1024];
                read(reader, &mut buf).unwrap();
                // It should contain the things we printed using `/bin/sh`.
                let string = String::from_utf8_lossy(&buf);
                assert!(string.contains("nix!!!"));
                assert!(string.contains("foo=bar"));
                assert!(string.contains("baz=quux"));
            }
        }
    }
    )
);

cfg_if!{
    if #[cfg(target_os = "android")] {
        execve_test_factory!(test_execve, execve, &CString::new("/system/bin/sh").unwrap());
        execve_test_factory!(test_fexecve, fexecve, File::open("/system/bin/sh").unwrap().into_raw_fd());
    } else if #[cfg(any(target_os = "dragonfly",
                        target_os = "freebsd",
                        target_os = "netbsd",
                        target_os = "openbsd",
                        target_os = "linux", ))] {
        execve_test_factory!(test_execve, execve, &CString::new("/bin/sh").unwrap());
        execve_test_factory!(test_fexecve, fexecve, File::open("/bin/sh").unwrap().into_raw_fd());
    } else if #[cfg(any(target_os = "ios", target_os = "macos", ))] {
        execve_test_factory!(test_execve, execve, &CString::new("/bin/sh").unwrap());
        // No fexecve() on macos/ios.
    }
}

#[test]
fn test_fchdir() {
    // fchdir changes the process's cwd
    #[allow(unused_variables)]
    let m = ::CWD_MTX.lock().expect("Mutex got poisoned by another test");

    let tmpdir = TempDir::new("test_fchdir").unwrap();
    let tmpdir_path = tmpdir.path().canonicalize().unwrap();
    let tmpdir_fd = File::open(&tmpdir_path).unwrap().into_raw_fd();

    assert!(fchdir(tmpdir_fd).is_ok());
    assert_eq!(getcwd().unwrap(), tmpdir_path);

    assert!(close(tmpdir_fd).is_ok());
}

#[test]
fn test_getcwd() {
    // chdir changes the process's cwd
    #[allow(unused_variables)]
    let m = ::CWD_MTX.lock().expect("Mutex got poisoned by another test");

    let tmpdir = TempDir::new("test_getcwd").unwrap();
    let tmpdir_path = tmpdir.path().canonicalize().unwrap();
    assert!(chdir(&tmpdir_path).is_ok());
    assert_eq!(getcwd().unwrap(), tmpdir_path);

    // make path 500 chars longer so that buffer doubling in getcwd
    // kicks in.  Note: One path cannot be longer than 255 bytes
    // (NAME_MAX) whole path cannot be longer than PATH_MAX (usually
    // 4096 on linux, 1024 on macos)
    let mut inner_tmp_dir = tmpdir_path.to_path_buf();
    for _ in 0..5 {
        let newdir = iter::repeat("a").take(100).collect::<String>();
        inner_tmp_dir.push(newdir);
        assert!(mkdir(inner_tmp_dir.as_path(), stat::S_IRWXU).is_ok());
    }
    assert!(chdir(inner_tmp_dir.as_path()).is_ok());
    assert_eq!(getcwd().unwrap(), inner_tmp_dir.as_path());
}

#[test]
fn test_lseek() {
    const CONTENTS: &'static [u8] = b"abcdef123456";
    let mut tmp = tempfile().unwrap();
    tmp.write_all(CONTENTS).unwrap();
    let tmpfd = tmp.into_raw_fd();

    let offset: off_t = 5;
    lseek(tmpfd, offset, Whence::SeekSet).unwrap();

    let mut buf = [0u8; 7];
    ::read_exact(tmpfd, &mut buf);
    assert_eq!(b"f123456", &buf);

    close(tmpfd).unwrap();
}

#[cfg(any(target_os = "linux", target_os = "android"))]
#[test]
fn test_lseek64() {
    const CONTENTS: &'static [u8] = b"abcdef123456";
    let mut tmp = tempfile().unwrap();
    tmp.write(CONTENTS).unwrap();
    let tmpfd = tmp.into_raw_fd();

    lseek64(tmpfd, 5, Whence::SeekSet).unwrap();

    let mut buf = [0u8; 7];
    ::read_exact(tmpfd, &mut buf);
    assert_eq!(b"f123456", &buf);

    close(tmpfd).unwrap();
}

#[test]
fn test_fpathconf_limited() {
    let f = tempfile().unwrap();
    // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test
    let path_max = fpathconf(f.as_raw_fd(), PathconfVar::PATH_MAX);
    assert!(path_max.expect("fpathconf failed").expect("PATH_MAX is unlimited") > 0);
}

#[test]
fn test_pathconf_limited() {
    // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test
    let path_max = pathconf("/", PathconfVar::PATH_MAX);
    assert!(path_max.expect("pathconf failed").expect("PATH_MAX is unlimited") > 0);
}

#[test]
fn test_sysconf_limited() {
    // AFAIK, OPEN_MAX is limited on all platforms, so it makes a good test
    let open_max = sysconf(SysconfVar::OPEN_MAX);
    assert!(open_max.expect("sysconf failed").expect("OPEN_MAX is unlimited") > 0);
}

#[cfg(target_os = "freebsd")]
#[test]
fn test_sysconf_unsupported() {
    // I know of no sysconf variables that are unsupported everywhere, but
    // _XOPEN_CRYPT is unsupported on FreeBSD 11.0, which is one of the platforms
    // we test.
    let open_max = sysconf(SysconfVar::_XOPEN_CRYPT);
    assert!(open_max.expect("sysconf failed").is_none())
}
<commit_msg>test_unistd: Add test for getgroups/setgroups()<commit_after>extern crate tempdir;

use nix::unistd::*;
use nix::unistd::ForkResult::*;
use nix::sys::wait::*;
use nix::sys::stat;
use std::{env, iter};
use std::ffi::CString;
use std::fs::File;
use std::io::Write;
use std::os::unix::prelude::*;
use tempfile::tempfile;
use tempdir::TempDir;
use libc::{_exit, off_t};

#[test]
fn test_fork_and_waitpid() {
    #[allow(unused_variables)]
    let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");

    // Safe: Child only calls `_exit`, which is signal-safe
    match fork() {
        Ok(Child) => unsafe { _exit(0) },
        Ok(Parent { child }) => {
            // assert that child was created and pid > 0
            let child_raw: ::libc::pid_t = child.into();
            assert!(child_raw > 0);
            let wait_status = waitpid(child, None);
            match wait_status {
                // assert that waitpid returned correct status and the pid is the one of the child
                Ok(WaitStatus::Exited(pid_t, _)) =>  assert!(pid_t == child),

                // panic, must never happen
                s @ Ok(_) => panic!("Child exited {:?}, should never happen", s),

                // panic, waitpid should never fail
                Err(s) => panic!("Error: waitpid returned Err({:?}", s)
            }

        },
        // panic, fork should never fail unless there is a serious problem with the OS
        Err(_) => panic!("Error: Fork Failed")
    }
}

#[test]
fn test_wait() {
    // Grab FORK_MTX so wait doesn't reap a different test's child process
    #[allow(unused_variables)]
    let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");

    // Safe: Child only calls `_exit`, which is signal-safe
    let pid = fork();
    match pid {
        Ok(Child) => unsafe { _exit(0) },
        Ok(Parent { child }) => {
            let wait_status = wait();

            // just assert that (any) one child returns with WaitStatus::Exited
            assert_eq!(wait_status, Ok(WaitStatus::Exited(child, 0)));
        },
        // panic, fork should never fail unless there is a serious problem with the OS
        Err(_) => panic!("Error: Fork Failed")
    }
}

#[test]
fn test_mkstemp() {
    let mut path = env::temp_dir();
    path.push("nix_tempfile.XXXXXX");

    let result = mkstemp(&path);
    match result {
        Ok((fd, path)) => {
            close(fd).unwrap();
            unlink(path.as_path()).unwrap();
        },
        Err(e) => panic!("mkstemp failed: {}", e)
    }
}

#[test]
fn test_mkstemp_directory() {
    // mkstemp should fail if a directory is given
    assert!(mkstemp(&env::temp_dir()).is_err());
}

#[test]
fn test_mkfifo() {
    let tempdir = TempDir::new("nix-test_mkfifo").unwrap();
    let mkfifo_fifo = tempdir.path().join("mkfifo_fifo");

    mkfifo(&mkfifo_fifo, stat::S_IRUSR).unwrap();

    let stats = stat::stat(&mkfifo_fifo).unwrap();
    let typ = stat::SFlag::from_bits_truncate(stats.st_mode);
    assert!(typ == stat::S_IFIFO);
}

#[test]
fn test_mkfifo_directory() {
    // mkfifo should fail if a directory is given
    assert!(mkfifo(&env::temp_dir(), stat::S_IRUSR).is_err());
}

#[test]
fn test_getpid() {
    let pid: ::libc::pid_t = getpid().into();
    let ppid: ::libc::pid_t = getppid().into();
    assert!(pid > 0);
    assert!(ppid > 0);
}

#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux_android {
    use nix::unistd::gettid;

    #[test]
    fn test_gettid() {
        let tid: ::libc::pid_t = gettid().into();
        assert!(tid > 0);
    }
}

#[test]
// `getgroups()` and `setgroups()` do not behave as expected on Apple platforms
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
fn test_setgroups() {
    // Skip this test when not run as root as `setgroups()` requires root.
    if !Uid::current().is_root() {
        return
    }

    // Save the existing groups
    let old_groups = getgroups().unwrap();

    // Set some new made up groups
    let groups = [Gid::from_raw(123), Gid::from_raw(456)];
    setgroups(&groups).unwrap();

    let new_groups = getgroups().unwrap();
    assert_eq!(new_groups, groups);

    // Revert back to the old groups
    setgroups(&old_groups).unwrap();
}

macro_rules! execve_test_factory(
    ($test_name:ident, $syscall:ident, $exe: expr) => (
    #[test]
    fn $test_name() {
        #[allow(unused_variables)]
        let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");
        // The `exec`d process will write to `writer`, and we'll read that
        // data from `reader`.
        let (reader, writer) = pipe().unwrap();

        // Safe: Child calls `exit`, `dup`, `close` and the provided `exec*` family function.
        // NOTE: Technically, this makes the macro unsafe to use because you could pass anything.
        //       The tests make sure not to do that, though.
        match fork().unwrap() {
            Child => {
                // Close stdout.
                close(1).unwrap();
                // Make `writer` be the stdout of the new process.
                dup(writer).unwrap();
                // exec!
                $syscall(
                    $exe,
                    &[CString::new(b"".as_ref()).unwrap(),
                      CString::new(b"-c".as_ref()).unwrap(),
                      CString::new(b"echo nix!!! && echo foo=$foo && echo baz=$baz"
                                   .as_ref()).unwrap()],
                    &[CString::new(b"foo=bar".as_ref()).unwrap(),
                      CString::new(b"baz=quux".as_ref()).unwrap()]).unwrap();
            },
            Parent { child } => {
                // Wait for the child to exit.
                waitpid(child, None).unwrap();
                // Read 1024 bytes.
                let mut buf = [0u8; 1024];
                read(reader, &mut buf).unwrap();
                // It should contain the things we printed using `/bin/sh`.
                let string = String::from_utf8_lossy(&buf);
                assert!(string.contains("nix!!!"));
                assert!(string.contains("foo=bar"));
                assert!(string.contains("baz=quux"));
            }
        }
    }
    )
);

cfg_if!{
    if #[cfg(target_os = "android")] {
        execve_test_factory!(test_execve, execve, &CString::new("/system/bin/sh").unwrap());
        execve_test_factory!(test_fexecve, fexecve, File::open("/system/bin/sh").unwrap().into_raw_fd());
    } else if #[cfg(any(target_os = "dragonfly",
                        target_os = "freebsd",
                        target_os = "netbsd",
                        target_os = "openbsd",
                        target_os = "linux", ))] {
        execve_test_factory!(test_execve, execve, &CString::new("/bin/sh").unwrap());
        execve_test_factory!(test_fexecve, fexecve, File::open("/bin/sh").unwrap().into_raw_fd());
    } else if #[cfg(any(target_os = "ios", target_os = "macos", ))] {
        execve_test_factory!(test_execve, execve, &CString::new("/bin/sh").unwrap());
        // No fexecve() on macos/ios.
    }
}

#[test]
fn test_fchdir() {
    // fchdir changes the process's cwd
    #[allow(unused_variables)]
    let m = ::CWD_MTX.lock().expect("Mutex got poisoned by another test");

    let tmpdir = TempDir::new("test_fchdir").unwrap();
    let tmpdir_path = tmpdir.path().canonicalize().unwrap();
    let tmpdir_fd = File::open(&tmpdir_path).unwrap().into_raw_fd();

    assert!(fchdir(tmpdir_fd).is_ok());
    assert_eq!(getcwd().unwrap(), tmpdir_path);

    assert!(close(tmpdir_fd).is_ok());
}

#[test]
fn test_getcwd() {
    // chdir changes the process's cwd
    #[allow(unused_variables)]
    let m = ::CWD_MTX.lock().expect("Mutex got poisoned by another test");

    let tmpdir = TempDir::new("test_getcwd").unwrap();
    let tmpdir_path = tmpdir.path().canonicalize().unwrap();
    assert!(chdir(&tmpdir_path).is_ok());
    assert_eq!(getcwd().unwrap(), tmpdir_path);

    // make path 500 chars longer so that buffer doubling in getcwd
    // kicks in.  Note: One path cannot be longer than 255 bytes
    // (NAME_MAX) whole path cannot be longer than PATH_MAX (usually
    // 4096 on linux, 1024 on macos)
    let mut inner_tmp_dir = tmpdir_path.to_path_buf();
    for _ in 0..5 {
        let newdir = iter::repeat("a").take(100).collect::<String>();
        inner_tmp_dir.push(newdir);
        assert!(mkdir(inner_tmp_dir.as_path(), stat::S_IRWXU).is_ok());
    }
    assert!(chdir(inner_tmp_dir.as_path()).is_ok());
    assert_eq!(getcwd().unwrap(), inner_tmp_dir.as_path());
}

#[test]
fn test_lseek() {
    const CONTENTS: &'static [u8] = b"abcdef123456";
    let mut tmp = tempfile().unwrap();
    tmp.write_all(CONTENTS).unwrap();
    let tmpfd = tmp.into_raw_fd();

    let offset: off_t = 5;
    lseek(tmpfd, offset, Whence::SeekSet).unwrap();

    let mut buf = [0u8; 7];
    ::read_exact(tmpfd, &mut buf);
    assert_eq!(b"f123456", &buf);

    close(tmpfd).unwrap();
}

#[cfg(any(target_os = "linux", target_os = "android"))]
#[test]
fn test_lseek64() {
    const CONTENTS: &'static [u8] = b"abcdef123456";
    let mut tmp = tempfile().unwrap();
    tmp.write(CONTENTS).unwrap();
    let tmpfd = tmp.into_raw_fd();

    lseek64(tmpfd, 5, Whence::SeekSet).unwrap();

    let mut buf = [0u8; 7];
    ::read_exact(tmpfd, &mut buf);
    assert_eq!(b"f123456", &buf);

    close(tmpfd).unwrap();
}

#[test]
fn test_fpathconf_limited() {
    let f = tempfile().unwrap();
    // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test
    let path_max = fpathconf(f.as_raw_fd(), PathconfVar::PATH_MAX);
    assert!(path_max.expect("fpathconf failed").expect("PATH_MAX is unlimited") > 0);
}

#[test]
fn test_pathconf_limited() {
    // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test
    let path_max = pathconf("/", PathconfVar::PATH_MAX);
    assert!(path_max.expect("pathconf failed").expect("PATH_MAX is unlimited") > 0);
}

#[test]
fn test_sysconf_limited() {
    // AFAIK, OPEN_MAX is limited on all platforms, so it makes a good test
    let open_max = sysconf(SysconfVar::OPEN_MAX);
    assert!(open_max.expect("sysconf failed").expect("OPEN_MAX is unlimited") > 0);
}

#[cfg(target_os = "freebsd")]
#[test]
fn test_sysconf_unsupported() {
    // I know of no sysconf variables that are unsupported everywhere, but
    // _XOPEN_CRYPT is unsupported on FreeBSD 11.0, which is one of the platforms
    // we test.
    let open_max = sysconf(SysconfVar::_XOPEN_CRYPT);
    assert!(open_max.expect("sysconf failed").is_none())
}
<|endoftext|>


<commit_before>use std::rand::random;

mod guess {
    pub fn guessed_correctly(guess: uint, machine: uint) -> bool {
        guess == machine
    }
}

fn main() {
    let random_value = random::<uint>() % 10u;
    let mut guess = 0u;
    guess += 1;
    println!("{}", random_value);
    println!("{}", guess::guessed_correctly(guess, random_value));

}
<commit_msg>Add OS checking using cfg<commit_after>use std::io;
use std::rand::random;

mod guess {
    pub fn guessed_correctly(guess: uint, machine: uint) -> bool {
        guess == machine
    }
}

#[cfg(not(target_os = "linux"))]
fn test_os() {
    println!("You are not running Linux!")
}

fn main() {
    test_os();
    let random_value = random::<uint>() % 10u;
    let mut guess = 0u;
    for line in io::stdin().lines() {
        // guess = line.unwrap().to_int();
        println!("{}", line.unwrap());
    }

    println!("{}", random_value);
    println!("{}", guess);
    println!("{}", guess::guessed_correctly(guess, random_value));

}
<|endoftext|>


<commit_before>//
// zhtta.rs
//
// Running on Rust 0.8
//
// Starting code for PS3
//
// Note: it would be very unwise to run this server on a machine that is
// on the Internet and contains any sensitive files!
//
// University of Virginia - cs4414 Fall 2013
// Weilin Xu and David Evans
// Version 0.1

extern mod extra;

use std::rt::io::*;
use std::rt::io::net::ip::{SocketAddr, Ipv4Addr};
use std::io::println;
use std::cell::Cell;
use std::{os, str, io};
use extra::arc;
use std::comm::*;

static PORT:    int = 4414;
static IPV4_LOOPBACK: &'static str = "127.0.0.1";

struct sched_msg {
    stream: Option<std::rt::io::net::tcp::TcpStream>,
    filepath: ~std::path::PosixPath
}

fn main() {
    let req_vec: ~[sched_msg] = ~[];
    let shared_req_vec = arc::RWArc::new(req_vec);
    let add_vec = shared_req_vec.clone();
    let take_vec = shared_req_vec.clone();

    let (port, chan) = stream();
    let chan = SharedChan::new(chan);

    // add file requests into queue.
    do spawn {
        while(true) {
            do add_vec.write |vec| {
                let tf:sched_msg = port.recv();
                (*vec).push(tf);
                println("add to queue");
            }
        }
    }

    // take file requests from queue, and send a response.
    do spawn {
        while(true) {
            do take_vec.write |vec| {
                let mut tf = (*vec).pop();

                match io::read_whole_file(tf.filepath) {
                    Ok(file_data) => {
                        tf.stream.write(file_data);
                    }
                    Err(err) => {
                        println(err);
                    }
                }
            }
        }
    }

    let socket = net::tcp::TcpListener::bind(SocketAddr {ip: Ipv4Addr(127,0,0,1), port: PORT as u16});

    println(fmt!("Listening on tcp port %d ...", PORT));
    let mut acceptor = socket.listen().unwrap();

    let visitor_count_master = arc::RWArc::new(0);

    // we can limit the incoming connection count.
    //for stream in acceptor.incoming().take(10 as uint) {
    for stream in acceptor.incoming() {
        let stream = Cell::new(stream);

        // Start a new task to handle the connection
        let child_chan = chan.clone();
	let visitor_count = visitor_count_master.clone();
        do spawn {
	    do visitor_count.write |count| {
		*count += 1;
	    };

            let mut stream = stream.take();
            let mut buf = [0, ..500];
            stream.read(buf);
            let request_str = str::from_utf8(buf);

            let req_group : ~[&str]= request_str.splitn_iter(' ', 3).collect();
            if req_group.len() > 2 {
                let path = req_group[1];
                println(fmt!("Request for path: \n%?", path));

                let file_path = ~os::getcwd().push(path.replace("/../", ""));
                if !os::path_exists(file_path) || os::path_is_dir(file_path) {
                    println(fmt!("Request received:\n%s", request_str));
                    let response: ~str = fmt!(
                        "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n
                         <doctype !html><title>Hello, Rust!</title>

Greetings, Krusty!

Visitor count: %u

                         \r\n", do visitor_count.read |count| { *count });

                    stream.write(response.as_bytes());
                }
                else {
                    // may do scheduling here
                    let msg: sched_msg = sched_msg{stream: stream, filepath: file_path.clone()};
                    child_chan.send(msg);

                    println(fmt!("get file request: %?", file_path));
                }
            }
            println!("connection terminates")
        }
    }
}
<commit_msg>Gets ip address and checks if it's in charlottesville<commit_after>//
// zhtta.rs
//
// Running on Rust 0.8
//
// Starting code for PS3
//
// Note: it would be very unwise to run this server on a machine that is
// on the Internet and contains any sensitive files!
//
// University of Virginia - cs4414 Fall 2013
// Weilin Xu and David Evans
// Version 0.1

extern mod extra;

use std::rt::io::*;
use std::rt::io::net::ip::{SocketAddr, Ipv4Addr};
use std::io::println;
use std::cell::Cell;
use std::{os, str, io};
use extra::arc;
use std::comm::*;

static PORT:    int = 4414;
static IPV4_LOOPBACK: &'static str = "127.0.0.1";

struct sched_msg {
    stream: Option<std::rt::io::net::tcp::TcpStream>,
    filepath: ~std::path::PosixPath
}

fn main() {
    let req_vec: ~[sched_msg] = ~[];
    let shared_req_vec = arc::RWArc::new(req_vec);
    let add_vec = shared_req_vec.clone();
    let take_vec = shared_req_vec.clone();

    let (port, chan) = stream();
    let chan = SharedChan::new(chan);

    // add file requests into queue.
    do spawn {
        while(true) {
            do add_vec.write |vec| {
                let tf:sched_msg = port.recv();
                (*vec).push(tf);
                println("add to queue");
            }
        }
    }

    // take file requests from queue, and send a response.
    do spawn {
        while(true) {
            do take_vec.write |vec| {
                let mut tf = (*vec).pop();

                match io::read_whole_file(tf.filepath) {
                    Ok(file_data) => {
                        tf.stream.write(file_data);
                    }
                    Err(err) => {
                        println(err);
                    }
                }
            }
        }
    }

    let socket = net::tcp::TcpListener::bind(SocketAddr {ip: Ipv4Addr(127,0,0,1), port: PORT as u16});

    println(fmt!("Listening on tcp port %d ...", PORT));
    let mut acceptor = socket.listen().unwrap();

    let visitor_count_master = arc::RWArc::new(0);

    // we can limit the incoming connection count.
    //for stream in acceptor.incoming().take(10 as uint) {
    for stream in acceptor.incoming() {
        let stream = Cell::new(stream);

        // Start a new task to handle the connection
        let child_chan = chan.clone();
	let visitor_count = visitor_count_master.clone();
        do spawn {
	    do visitor_count.write |count| {
		*count += 1;
	    };

            let mut stream = stream.take().unwrap();

	    let in_charlottesville = match stream.peer_name() {
		    Some(pn) => {
			let s = pn.to_str();
			s.slice_chars(0, 6) == "137.54" || s.slice_chars(0,7)=="128.143"
		    },
		    None => false
	    };

            let mut buf = [0, ..500];
            stream.read(buf);
            let request_str = str::from_utf8(buf);

            let req_group : ~[&str]= request_str.splitn_iter(' ', 3).collect();
            if req_group.len() > 2 {
                let path = req_group[1];
                println(fmt!("Request for path: \n%?", path));
		/*
		let peer = match stream {
		    Some(k) => match k.peername() {
			Some(p) => p.to_str(),
			None => ~""
		    },
		    None => ""
		};
		*/

                let file_path = ~os::getcwd().push(path.replace("/../", ""));
                if !os::path_exists(file_path) || os::path_is_dir(file_path) {
                    println(fmt!("Request received:\n%s", request_str));
                    let response: ~str = fmt!(
                        "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n
                         <doctype !html><title>Hello, Rust!</title>

Greetings, Krusty!

Visitor count: %u

                         \r\n", do visitor_count.read |count| { *count });

                    stream.write(response.as_bytes());
                }
                else {
                    // may do scheduling here
                    let msg: sched_msg = sched_msg{stream: Some(stream), filepath: file_path.clone()};
                    child_chan.send(msg);

                    println(fmt!("get file request: %?", file_path));
                }
            }
            println!("connection terminates")
        }
    }
}
<|endoftext|>


<commit_before>use std::libc::*;

pub struct ColorRGB {
    r:u8,
    g:u8,
    b:u8,
}

pub struct Point {
    x:c_int,
    y:c_int,
}
pub struct LongPoint {
    x:c_long,
    y:c_long,
}
pub struct Vector {
    x:c_int,
    y:c_int,
}

pub struct Size {
    w:c_int,
    h:c_int,
}
pub struct DoubleSize {
    w:c_double,
    h:c_double,
}

pub struct Rect {
    x:c_int,
    y:c_int,
    w:c_int,
    h:c_int,
}
<commit_msg>Fix test.rs compile errors, and extract T{Point,Size,Rect,Vector}s from struct into separate arguments to run normally.<commit_after><|endoftext|>


<commit_before>use super::WinningRootHashSet;
use crate::common::get_attesting_indices_unsorted;
use types::*;

/// Sets the boolean `var` on `self` to be true if it is true on `other`. Otherwise leaves `self`
/// as is.
macro_rules! set_self_if_other_is_true {
    ($self_: ident, $other: ident, $var: ident) => {
        if $other.$var {
            $self_.$var = true;
        }
    };
}

/// The information required to reward some validator for their participation in a "winning"
/// crosslink root.
#[derive(Default, Clone)]
pub struct WinningRootInfo {
    /// The total balance of the crosslink committee.
    pub total_committee_balance: u64,
    /// The total balance of the crosslink committee that attested for the "winning" root.
    pub total_attesting_balance: u64,
}

/// The information required to reward a block producer for including an attestation in a block.
#[derive(Clone, Copy)]
pub struct InclusionInfo {
    /// The earliest slot a validator had an attestation included in the previous epoch.
    pub slot: Slot,
    /// The distance between the attestation slot and the slot that attestation was included in a
    /// block.
    pub distance: u64,
    /// The index of the proposer at the slot where the attestation was included.
    pub proposer_index: usize,
}

impl Default for InclusionInfo {
    /// Defaults to `slot` and `distance` at their maximum values and `proposer_index` at zero.
    fn default() -> Self {
        Self {
            slot: Slot::max_value(),
            distance: u64::max_value(),
            proposer_index: 0,
        }
    }
}

impl InclusionInfo {
    /// Tests if some `other` `InclusionInfo` has a lower inclusion slot than `self`. If so,
    /// replaces `self` with `other`.
    pub fn update(&mut self, other: &Self) {
        if other.slot < self.slot {
            self.slot = other.slot;
            self.distance = other.distance;
            self.proposer_index = other.proposer_index;
        }
    }
}

/// Information required to reward some validator during the current and previous epoch.
#[derive(Default, Clone)]
pub struct ValidatorStatus {
    /// True if the validator has been slashed, ever.
    pub is_slashed: bool,
    /// True if the validator can withdraw in the current epoch.
    pub is_withdrawable_in_current_epoch: bool,
    /// True if the validator was active in the state's _current_ epoch.
    pub is_active_in_current_epoch: bool,
    /// True if the validator was active in the state's _previous_ epoch.
    pub is_active_in_previous_epoch: bool,
    /// The validator's effective balance in the _current_ epoch.
    pub current_epoch_effective_balance: u64,

    /// True if the validator had an attestation included in the _current_ epoch.
    pub is_current_epoch_attester: bool,
    /// True if the validator's beacon block root attestation for the first slot of the _current_
    /// epoch matches the block root known to the state.
    pub is_current_epoch_target_attester: bool,
    /// True if the validator had an attestation included in the _previous_ epoch.
    pub is_previous_epoch_attester: bool,
    /// True if the validator's beacon block root attestation for the first slot of the _previous_
    /// epoch matches the block root known to the state.
    pub is_previous_epoch_target_attester: bool,
    /// True if the validator's beacon block root attestation in the _previous_ epoch at the
    /// attestation's slot (`attestation_data.slot`) matches the block root known to the state.
    pub is_previous_epoch_head_attester: bool,

    /// Information used to reward the block producer of this validators earliest-included
    /// attestation.
    pub inclusion_info: Option<InclusionInfo>,
    /// Information used to reward/penalize the validator if they voted in the super-majority for
    /// some shard block.
    pub winning_root_info: Option<WinningRootInfo>,
}

impl ValidatorStatus {
    /// Accepts some `other` `ValidatorStatus` and updates `self` if required.
    ///
    /// Will never set one of the `bool` fields to `false`, it will only set it to `true` if other
    /// contains a `true` field.
    ///
    /// Note: does not update the winning root info, this is done manually.
    pub fn update(&mut self, other: &Self) {
        // Update all the bool fields, only updating `self` if `other` is true (never setting
        // `self` to false).
        set_self_if_other_is_true!(self, other, is_slashed);
        set_self_if_other_is_true!(self, other, is_withdrawable_in_current_epoch);
        set_self_if_other_is_true!(self, other, is_active_in_current_epoch);
        set_self_if_other_is_true!(self, other, is_active_in_previous_epoch);
        set_self_if_other_is_true!(self, other, is_current_epoch_attester);
        set_self_if_other_is_true!(self, other, is_current_epoch_target_attester);
        set_self_if_other_is_true!(self, other, is_previous_epoch_attester);
        set_self_if_other_is_true!(self, other, is_previous_epoch_target_attester);
        set_self_if_other_is_true!(self, other, is_previous_epoch_head_attester);

        if let Some(other_info) = other.inclusion_info {
            if let Some(self_info) = self.inclusion_info.as_mut() {
                self_info.update(&other_info);
            } else {
                self.inclusion_info = other.inclusion_info;
            }
        }
    }
}

/// The total effective balances for different sets of validators during the previous and current
/// epochs.
#[derive(Default, Clone)]
pub struct TotalBalances {
    /// The total effective balance of all active validators during the _current_ epoch.
    pub current_epoch: u64,
    /// The total effective balance of all active validators during the _previous_ epoch.
    pub previous_epoch: u64,
    /// The total effective balance of all validators who attested during the _current_ epoch.
    pub current_epoch_attesters: u64,
    /// The total effective balance of all validators who attested during the _current_ epoch and
    /// agreed with the state about the beacon block at the first slot of the _current_ epoch.
    pub current_epoch_target_attesters: u64,
    /// The total effective balance of all validators who attested during the _previous_ epoch.
    pub previous_epoch_attesters: u64,
    /// The total effective balance of all validators who attested during the _previous_ epoch and
    /// agreed with the state about the beacon block at the first slot of the _previous_ epoch.
    pub previous_epoch_target_attesters: u64,
    /// The total effective balance of all validators who attested during the _previous_ epoch and
    /// agreed with the state about the beacon block at the time of attestation.
    pub previous_epoch_head_attesters: u64,
}

/// Summarised information about validator participation in the _previous and _current_ epochs of
/// some `BeaconState`.
#[derive(Clone)]
pub struct ValidatorStatuses {
    /// Information about each individual validator from the state's validator registy.
    pub statuses: Vec<ValidatorStatus>,
    /// Summed balances for various sets of validators.
    pub total_balances: TotalBalances,
}

impl ValidatorStatuses {
    /// Initializes a new instance, determining:
    ///
    /// - Active validators
    /// - Total balances for the current and previous epochs.
    ///
    /// Spec v0.6.1
    pub fn new<T: EthSpec>(
        state: &BeaconState<T>,
        spec: &ChainSpec,
    ) -> Result<Self, BeaconStateError> {
        let mut statuses = Vec::with_capacity(state.validator_registry.len());
        let mut total_balances = TotalBalances::default();

        for (i, validator) in state.validator_registry.iter().enumerate() {
            let effective_balance = state.get_effective_balance(i, spec)?;
            let mut status = ValidatorStatus {
                is_slashed: validator.slashed,
                is_withdrawable_in_current_epoch: validator
                    .is_withdrawable_at(state.current_epoch()),
                current_epoch_effective_balance: effective_balance,
                ..ValidatorStatus::default()
            };

            if validator.is_active_at(state.current_epoch()) {
                status.is_active_in_current_epoch = true;
                total_balances.current_epoch += effective_balance;
            }

            if validator.is_active_at(state.previous_epoch()) {
                status.is_active_in_previous_epoch = true;
                total_balances.previous_epoch += effective_balance;
            }

            statuses.push(status);
        }

        Ok(Self {
            statuses,
            total_balances,
        })
    }

    /// Process some attestations from the given `state` updating the `statuses` and
    /// `total_balances` fields.
    ///
    /// Spec v0.6.1
    pub fn process_attestations<T: EthSpec>(
        &mut self,
        state: &BeaconState<T>,
        spec: &ChainSpec,
    ) -> Result<(), BeaconStateError> {
        for a in state
            .previous_epoch_attestations
            .iter()
            .chain(state.current_epoch_attestations.iter())
        {
            let attesting_indices =
                get_attesting_indices_unsorted(state, &a.data, &a.aggregation_bitfield)?;

            let mut status = ValidatorStatus::default();

            // Profile this attestation, updating the total balances and generating an
            // `ValidatorStatus` object that applies to all participants in the attestation.
            if is_from_epoch(a, state.current_epoch()) {
                status.is_current_epoch_attester = true;

                if target_matches_epoch_start_block(a, state, state.current_epoch(), spec)? {
                    status.is_current_epoch_target_attester = true;
                }
            } else if is_from_epoch(a, state.previous_epoch()) {
                status.is_previous_epoch_attester = true;

                // The inclusion slot and distance are only required for previous epoch attesters.
                let attestation_slot = state.get_attestation_slot(&a.data)?;
                let inclusion_slot = attestation_slot + a.inclusion_delay;
                let relative_epoch =
                    RelativeEpoch::from_slot(state.slot, inclusion_slot, spec.slots_per_epoch)?;
                status.inclusion_info = Some(InclusionInfo {
                    slot: inclusion_slot,
                    distance: a.inclusion_delay,
                    proposer_index: state.get_beacon_proposer_index(
                        attestation_slot,
                        relative_epoch,
                        spec,
                    )?,
                });

                if target_matches_epoch_start_block(a, state, state.previous_epoch(), spec)? {
                    status.is_previous_epoch_target_attester = true;
                }

                if has_common_beacon_block_root(a, state)? {
                    status.is_previous_epoch_head_attester = true;
                }
            }

            // Loop through the participating validator indices and update the status vec.
            for validator_index in attesting_indices {
                self.statuses[validator_index].update(&status);
            }
        }

        // Compute the total balances
        for (index, v) in self.statuses.iter().enumerate() {
            // According to the spec, we only count unslashed validators towards the totals.
            if !v.is_slashed {
                let validator_balance = state.get_effective_balance(index, spec)?;

                if v.is_current_epoch_attester {
                    self.total_balances.current_epoch_attesters += validator_balance;
                }
                if v.is_current_epoch_target_attester {
                    self.total_balances.current_epoch_target_attesters += validator_balance;
                }
                if v.is_previous_epoch_attester {
                    self.total_balances.previous_epoch_attesters += validator_balance;
                }
                if v.is_previous_epoch_target_attester {
                    self.total_balances.previous_epoch_target_attesters += validator_balance;
                }
                if v.is_previous_epoch_head_attester {
                    self.total_balances.previous_epoch_head_attesters += validator_balance;
                }
            }
        }

        Ok(())
    }

    /// Update the `statuses` for each validator based upon whether or not they attested to the
    /// "winning" shard block root for the previous epoch.
    ///
    /// Spec v0.6.1
    pub fn process_winning_roots<T: EthSpec>(
        &mut self,
        state: &BeaconState<T>,
        winning_roots: &WinningRootHashSet,
        spec: &ChainSpec,
    ) -> Result<(), BeaconStateError> {
        // Loop through each slot in the previous epoch.
        for slot in state.previous_epoch().slot_iter(spec.slots_per_epoch) {
            let crosslink_committees_at_slot = state.get_crosslink_committees_at_slot(slot)?;

            // Loop through each committee in the slot.
            for c in crosslink_committees_at_slot {
                // If there was some winning crosslink root for the committee's shard.
                if let Some(winning_root) = winning_roots.get(&c.shard) {
                    let total_committee_balance = state.get_total_balance(&c.committee, spec)?;
                    for &validator_index in &winning_root.attesting_validator_indices {
                        // Take note of the balance information for the winning root, it will be
                        // used later to calculate rewards for that validator.
                        self.statuses[validator_index].winning_root_info = Some(WinningRootInfo {
                            total_committee_balance,
                            total_attesting_balance: winning_root.total_attesting_balance,
                        })
                    }
                }
            }
        }

        Ok(())
    }
}

/// Returns `true` if some `PendingAttestation` is from the supplied `epoch`.
///
/// Spec v0.6.1
fn is_from_epoch(a: &PendingAttestation, epoch: Epoch) -> bool {
    a.data.target_epoch == epoch
}

/// Returns `true` if the attestation's FFG target is equal to the hash of the `state`'s first
/// beacon block in the given `epoch`.
///
/// Spec v0.6.1
fn target_matches_epoch_start_block<T: EthSpec>(
    a: &PendingAttestation,
    state: &BeaconState<T>,
    epoch: Epoch,
    spec: &ChainSpec,
) -> Result<bool, BeaconStateError> {
    let slot = epoch.start_slot(spec.slots_per_epoch);
    let state_boundary_root = *state.get_block_root(slot)?;

    Ok(a.data.target_root == state_boundary_root)
}

/// Returns `true` if a `PendingAttestation` and `BeaconState` share the same beacon block hash for
/// the current slot of the `PendingAttestation`.
///
/// Spec v0.6.1
fn has_common_beacon_block_root<T: EthSpec>(
    a: &PendingAttestation,
    state: &BeaconState<T>,
) -> Result<bool, BeaconStateError> {
    let attestation_slot = state.get_attestation_slot(&a.data)?;
    let state_block_root = *state.get_block_root(attestation_slot)?;

    Ok(a.data.beacon_block_root == state_block_root)
}
<commit_msg>Fix bug in epoch_processing<commit_after>use super::WinningRootHashSet;
use crate::common::get_attesting_indices_unsorted;
use types::*;

/// Sets the boolean `var` on `self` to be true if it is true on `other`. Otherwise leaves `self`
/// as is.
macro_rules! set_self_if_other_is_true {
    ($self_: ident, $other: ident, $var: ident) => {
        if $other.$var {
            $self_.$var = true;
        }
    };
}

/// The information required to reward some validator for their participation in a "winning"
/// crosslink root.
#[derive(Default, Clone)]
pub struct WinningRootInfo {
    /// The total balance of the crosslink committee.
    pub total_committee_balance: u64,
    /// The total balance of the crosslink committee that attested for the "winning" root.
    pub total_attesting_balance: u64,
}

/// The information required to reward a block producer for including an attestation in a block.
#[derive(Clone, Copy)]
pub struct InclusionInfo {
    /// The earliest slot a validator had an attestation included in the previous epoch.
    pub slot: Slot,
    /// The distance between the attestation slot and the slot that attestation was included in a
    /// block.
    pub distance: u64,
    /// The index of the proposer at the slot where the attestation was included.
    pub proposer_index: usize,
}

impl Default for InclusionInfo {
    /// Defaults to `slot` and `distance` at their maximum values and `proposer_index` at zero.
    fn default() -> Self {
        Self {
            slot: Slot::max_value(),
            distance: u64::max_value(),
            proposer_index: 0,
        }
    }
}

impl InclusionInfo {
    /// Tests if some `other` `InclusionInfo` has a lower inclusion slot than `self`. If so,
    /// replaces `self` with `other`.
    pub fn update(&mut self, other: &Self) {
        if other.slot < self.slot {
            self.slot = other.slot;
            self.distance = other.distance;
            self.proposer_index = other.proposer_index;
        }
    }
}

/// Information required to reward some validator during the current and previous epoch.
#[derive(Default, Clone)]
pub struct ValidatorStatus {
    /// True if the validator has been slashed, ever.
    pub is_slashed: bool,
    /// True if the validator can withdraw in the current epoch.
    pub is_withdrawable_in_current_epoch: bool,
    /// True if the validator was active in the state's _current_ epoch.
    pub is_active_in_current_epoch: bool,
    /// True if the validator was active in the state's _previous_ epoch.
    pub is_active_in_previous_epoch: bool,
    /// The validator's effective balance in the _current_ epoch.
    pub current_epoch_effective_balance: u64,

    /// True if the validator had an attestation included in the _current_ epoch.
    pub is_current_epoch_attester: bool,
    /// True if the validator's beacon block root attestation for the first slot of the _current_
    /// epoch matches the block root known to the state.
    pub is_current_epoch_target_attester: bool,
    /// True if the validator had an attestation included in the _previous_ epoch.
    pub is_previous_epoch_attester: bool,
    /// True if the validator's beacon block root attestation for the first slot of the _previous_
    /// epoch matches the block root known to the state.
    pub is_previous_epoch_target_attester: bool,
    /// True if the validator's beacon block root attestation in the _previous_ epoch at the
    /// attestation's slot (`attestation_data.slot`) matches the block root known to the state.
    pub is_previous_epoch_head_attester: bool,

    /// Information used to reward the block producer of this validators earliest-included
    /// attestation.
    pub inclusion_info: Option<InclusionInfo>,
    /// Information used to reward/penalize the validator if they voted in the super-majority for
    /// some shard block.
    pub winning_root_info: Option<WinningRootInfo>,
}

impl ValidatorStatus {
    /// Accepts some `other` `ValidatorStatus` and updates `self` if required.
    ///
    /// Will never set one of the `bool` fields to `false`, it will only set it to `true` if other
    /// contains a `true` field.
    ///
    /// Note: does not update the winning root info, this is done manually.
    pub fn update(&mut self, other: &Self) {
        // Update all the bool fields, only updating `self` if `other` is true (never setting
        // `self` to false).
        set_self_if_other_is_true!(self, other, is_slashed);
        set_self_if_other_is_true!(self, other, is_withdrawable_in_current_epoch);
        set_self_if_other_is_true!(self, other, is_active_in_current_epoch);
        set_self_if_other_is_true!(self, other, is_active_in_previous_epoch);
        set_self_if_other_is_true!(self, other, is_current_epoch_attester);
        set_self_if_other_is_true!(self, other, is_current_epoch_target_attester);
        set_self_if_other_is_true!(self, other, is_previous_epoch_attester);
        set_self_if_other_is_true!(self, other, is_previous_epoch_target_attester);
        set_self_if_other_is_true!(self, other, is_previous_epoch_head_attester);

        if let Some(other_info) = other.inclusion_info {
            if let Some(self_info) = self.inclusion_info.as_mut() {
                self_info.update(&other_info);
            } else {
                self.inclusion_info = other.inclusion_info;
            }
        }
    }
}

/// The total effective balances for different sets of validators during the previous and current
/// epochs.
#[derive(Default, Clone)]
pub struct TotalBalances {
    /// The total effective balance of all active validators during the _current_ epoch.
    pub current_epoch: u64,
    /// The total effective balance of all active validators during the _previous_ epoch.
    pub previous_epoch: u64,
    /// The total effective balance of all validators who attested during the _current_ epoch.
    pub current_epoch_attesters: u64,
    /// The total effective balance of all validators who attested during the _current_ epoch and
    /// agreed with the state about the beacon block at the first slot of the _current_ epoch.
    pub current_epoch_target_attesters: u64,
    /// The total effective balance of all validators who attested during the _previous_ epoch.
    pub previous_epoch_attesters: u64,
    /// The total effective balance of all validators who attested during the _previous_ epoch and
    /// agreed with the state about the beacon block at the first slot of the _previous_ epoch.
    pub previous_epoch_target_attesters: u64,
    /// The total effective balance of all validators who attested during the _previous_ epoch and
    /// agreed with the state about the beacon block at the time of attestation.
    pub previous_epoch_head_attesters: u64,
}

/// Summarised information about validator participation in the _previous and _current_ epochs of
/// some `BeaconState`.
#[derive(Clone)]
pub struct ValidatorStatuses {
    /// Information about each individual validator from the state's validator registy.
    pub statuses: Vec<ValidatorStatus>,
    /// Summed balances for various sets of validators.
    pub total_balances: TotalBalances,
}

impl ValidatorStatuses {
    /// Initializes a new instance, determining:
    ///
    /// - Active validators
    /// - Total balances for the current and previous epochs.
    ///
    /// Spec v0.6.1
    pub fn new<T: EthSpec>(
        state: &BeaconState<T>,
        spec: &ChainSpec,
    ) -> Result<Self, BeaconStateError> {
        let mut statuses = Vec::with_capacity(state.validator_registry.len());
        let mut total_balances = TotalBalances::default();

        for (i, validator) in state.validator_registry.iter().enumerate() {
            let effective_balance = state.get_effective_balance(i, spec)?;
            let mut status = ValidatorStatus {
                is_slashed: validator.slashed,
                is_withdrawable_in_current_epoch: validator
                    .is_withdrawable_at(state.current_epoch()),
                current_epoch_effective_balance: effective_balance,
                ..ValidatorStatus::default()
            };

            if validator.is_active_at(state.current_epoch()) {
                status.is_active_in_current_epoch = true;
                total_balances.current_epoch += effective_balance;
            }

            if validator.is_active_at(state.previous_epoch()) {
                status.is_active_in_previous_epoch = true;
                total_balances.previous_epoch += effective_balance;
            }

            statuses.push(status);
        }

        Ok(Self {
            statuses,
            total_balances,
        })
    }

    /// Process some attestations from the given `state` updating the `statuses` and
    /// `total_balances` fields.
    ///
    /// Spec v0.6.1
    pub fn process_attestations<T: EthSpec>(
        &mut self,
        state: &BeaconState<T>,
        spec: &ChainSpec,
    ) -> Result<(), BeaconStateError> {
        for a in state
            .previous_epoch_attestations
            .iter()
            .chain(state.current_epoch_attestations.iter())
        {
            let attesting_indices =
                get_attesting_indices_unsorted(state, &a.data, &a.aggregation_bitfield)?;

            let mut status = ValidatorStatus::default();

            // Profile this attestation, updating the total balances and generating an
            // `ValidatorStatus` object that applies to all participants in the attestation.
            if is_from_epoch(a, state.current_epoch()) {
                status.is_current_epoch_attester = true;

                if target_matches_epoch_start_block(a, state, state.current_epoch(), spec)? {
                    status.is_current_epoch_target_attester = true;
                }
            } else if is_from_epoch(a, state.previous_epoch()) {
                status.is_previous_epoch_attester = true;

                // The inclusion slot and distance are only required for previous epoch attesters.
                let attestation_slot = state.get_attestation_slot(&a.data)?;
                let inclusion_slot = attestation_slot + a.inclusion_delay;
                let relative_epoch =
                    RelativeEpoch::from_slot(state.slot, attestation_slot, spec.slots_per_epoch)?;
                status.inclusion_info = Some(InclusionInfo {
                    slot: inclusion_slot,
                    distance: a.inclusion_delay,
                    proposer_index: state.get_beacon_proposer_index(
                        attestation_slot,
                        relative_epoch,
                        spec,
                    )?,
                });

                if target_matches_epoch_start_block(a, state, state.previous_epoch(), spec)? {
                    status.is_previous_epoch_target_attester = true;
                }

                if has_common_beacon_block_root(a, state)? {
                    status.is_previous_epoch_head_attester = true;
                }
            }

            // Loop through the participating validator indices and update the status vec.
            for validator_index in attesting_indices {
                self.statuses[validator_index].update(&status);
            }
        }

        // Compute the total balances
        for (index, v) in self.statuses.iter().enumerate() {
            // According to the spec, we only count unslashed validators towards the totals.
            if !v.is_slashed {
                let validator_balance = state.get_effective_balance(index, spec)?;

                if v.is_current_epoch_attester {
                    self.total_balances.current_epoch_attesters += validator_balance;
                }
                if v.is_current_epoch_target_attester {
                    self.total_balances.current_epoch_target_attesters += validator_balance;
                }
                if v.is_previous_epoch_attester {
                    self.total_balances.previous_epoch_attesters += validator_balance;
                }
                if v.is_previous_epoch_target_attester {
                    self.total_balances.previous_epoch_target_attesters += validator_balance;
                }
                if v.is_previous_epoch_head_attester {
                    self.total_balances.previous_epoch_head_attesters += validator_balance;
                }
            }
        }

        Ok(())
    }

    /// Update the `statuses` for each validator based upon whether or not they attested to the
    /// "winning" shard block root for the previous epoch.
    ///
    /// Spec v0.6.1
    pub fn process_winning_roots<T: EthSpec>(
        &mut self,
        state: &BeaconState<T>,
        winning_roots: &WinningRootHashSet,
        spec: &ChainSpec,
    ) -> Result<(), BeaconStateError> {
        // Loop through each slot in the previous epoch.
        for slot in state.previous_epoch().slot_iter(spec.slots_per_epoch) {
            let crosslink_committees_at_slot = state.get_crosslink_committees_at_slot(slot)?;

            // Loop through each committee in the slot.
            for c in crosslink_committees_at_slot {
                // If there was some winning crosslink root for the committee's shard.
                if let Some(winning_root) = winning_roots.get(&c.shard) {
                    let total_committee_balance = state.get_total_balance(&c.committee, spec)?;
                    for &validator_index in &winning_root.attesting_validator_indices {
                        // Take note of the balance information for the winning root, it will be
                        // used later to calculate rewards for that validator.
                        self.statuses[validator_index].winning_root_info = Some(WinningRootInfo {
                            total_committee_balance,
                            total_attesting_balance: winning_root.total_attesting_balance,
                        })
                    }
                }
            }
        }

        Ok(())
    }
}

/// Returns `true` if some `PendingAttestation` is from the supplied `epoch`.
///
/// Spec v0.6.1
fn is_from_epoch(a: &PendingAttestation, epoch: Epoch) -> bool {
    a.data.target_epoch == epoch
}

/// Returns `true` if the attestation's FFG target is equal to the hash of the `state`'s first
/// beacon block in the given `epoch`.
///
/// Spec v0.6.1
fn target_matches_epoch_start_block<T: EthSpec>(
    a: &PendingAttestation,
    state: &BeaconState<T>,
    epoch: Epoch,
    spec: &ChainSpec,
) -> Result<bool, BeaconStateError> {
    let slot = epoch.start_slot(spec.slots_per_epoch);
    let state_boundary_root = *state.get_block_root(slot)?;

    Ok(a.data.target_root == state_boundary_root)
}

/// Returns `true` if a `PendingAttestation` and `BeaconState` share the same beacon block hash for
/// the current slot of the `PendingAttestation`.
///
/// Spec v0.6.1
fn has_common_beacon_block_root<T: EthSpec>(
    a: &PendingAttestation,
    state: &BeaconState<T>,
) -> Result<bool, BeaconStateError> {
    let attestation_slot = state.get_attestation_slot(&a.data)?;
    let state_block_root = *state.get_block_root(attestation_slot)?;

    Ok(a.data.beacon_block_root == state_block_root)
}
<|endoftext|>


<commit_before>use std::collections::hash_map::HashMap;
use std::rc::Rc;

use automation::Automation;
use partial::Partial;
use tree::node::{ANode, NodeInputSlot, YNode};
use tree::send::{AASend, AYSend, Send, YYSend};
use tree::tree::Tree;

use render::render_spec::RenderSpec;

use super::partial_renderer::PartialRenderer;

/// Tracks all the partials/automations that have ever entered the node.
/// This information is needed in order to evaluate the output whenever
/// a new input arrives.
struct ANodeState {
    left: Vec<Automation>,
    right: Vec<Automation>,
    aasends: Vec<AASend>,
    aysends: Vec<AYSend>,
}

/// Tracks all the partials/automations that have ever entered the node.
/// This information is needed in order to evaluate the output whenever
/// a new input arrives.
struct YNodeState {
    left: Vec<Partial>,
    right: Vec<Automation>,
    yysends: Vec<YYSend>,
}

struct OutputState {
    node: Rc<YNode>,
    renderer: PartialRenderer,
}

struct TreeRenderer {
    render_spec: RenderSpec,
    anode_states: HashMap<Rc<ANode>, ANodeState>,
    ynode_states: HashMap<Rc<YNode>, YNodeState>,
    outputs: Vec<OutputState>,
    // In order to return a slice from the step() function, we need to allocate
    // some buffer space
    output_buff: Vec<f32>,
}

impl TreeRenderer {
    pub fn new(render_spec: RenderSpec) -> TreeRenderer {
        TreeRenderer{
            render_spec: render_spec,
            anode_states: HashMap::new(),
            ynode_states: HashMap::new(),
            outputs: vec![],
            output_buff: vec![],
        }
    }
    /// Get the ANodeState associated with a node,
    /// and create it if it doesn't already exist.
    fn get_anode_state(&mut self, node: &Rc<ANode>) -> &mut ANodeState {
        self.anode_states.entry(node.clone()).or_insert_with(|| ANodeState::new())
    }
    /// Get the YNodeState associated with a node,
    /// and create it if it doesn't already exist.
    fn get_ynode_state(&mut self, node: &Rc<YNode>) -> &mut YNodeState {
        self.ynode_states.entry(node.clone()).or_insert_with(|| YNodeState::new())
    }
    /// Send a partial to the input of any nodes connected to the output of the
    /// given node.
    fn broadcast_partial(&mut self, from: &Rc<YNode>, partial: Partial) {
        // need to clone the State's sends to avoid mutability problems
        let sends = self.get_ynode_state(from).yysends.clone();
        for ref send in sends.iter() {
            self.ynode_input_left(send.dest(), partial);
        }
    }
    /// Send an Automation to the input of any nodes connected to the output of
    /// the given node.
    fn broadcast_autom(&mut self, from: &Rc<ANode>, autom: Automation) {
        // need to clone the State's sends to avoid mutability problems
        let aasends = self.get_anode_state(from).aasends.clone();
        let aysends = self.get_anode_state(from).aysends.clone();
        // send automation input to the YNodes:
        for ref send in aysends.iter() {
            self.ynode_input_right(send.dest(), autom);
        }
        // send the automation to the other ANodes:
        for ref send in aasends.iter() {
            self.anode_input(send.dest(), send.dest_slot(), autom);
        }
    }
    /// Add a partial to the YNode's left slot
    fn ynode_input_left(&mut self, node: &Rc<YNode>, partial: Partial) {
        let right;
        {
            let mut state = self.get_ynode_state(node);
            state.left.push(partial);
            // need to clone the State's right-hand-side to avoid mut issues
            right = state.right.clone();
        }
        // compute any new outputs & broadcast them.
        for autom in right.iter() {
            self.broadcast_partial(node, autom.apply_to_partial(partial));
        }
    }
    fn ynode_input_right(&mut self, node: &Rc<YNode>, autom: Automation) {
        let left;
        {
            let mut state = self.get_ynode_state(node);
            state.right.push(autom);
            // need to clone the State's left-hand-side to avoid mut issues
            left = state.left.clone();
        }
        // compute any new outputs & broadcast them.
        for partial in left.iter() {
            self.broadcast_partial(node, autom.apply_to_partial(*partial));
        }
    }
    fn anode_input(&mut self, node: &Rc<ANode>, slot: NodeInputSlot,
      autom: Automation) {
        match slot {
            NodeInputSlot::Left => {
                let right;
                {
                    let mut state = self.get_anode_state(node);
                    state.left.push(autom);
                    right = state.right.clone();
                }
                // all the automations in the right bin affect the new autom
                for autom_right in right.iter() {
                    self.broadcast_autom(node, autom_right.apply_to_autom(autom));
                }
            },
            NodeInputSlot::Right => {
                let left;
                {
                    let mut state = self.get_anode_state(node);
                    state.right.push(autom);
                    left = state.left.clone();
                }
                // this new autom affects all automations in the left bin
                for autom_left in left.iter() {
                    self.broadcast_autom(node, autom.apply_to_autom(*autom_left));
                }
            },
        };
    }
}

impl Tree for TreeRenderer {
    /// Connect two nodes in the tree.
    /// If the send is ASrcSend / YSrcSend, this is the same as feeding
    /// external stimuli into the tree.
    fn add_send(&mut self, send: Send) {
        match send {
            Send::AASend(send) => {
                self.get_anode_state(send.src()).add_aasend(send);
            },
            Send::AYSend(send) => {
                self.get_anode_state(send.src()).add_aysend(send);
            },
            Send::YYSend(send) => {
                self.get_ynode_state(send.src()).add_yysend(send);
            },
            Send::ASrcSend(send) => {
                self.broadcast_autom(send.dest(), *send.src());
            },
            Send::YSrcSend(send) => {
                self.broadcast_partial(send.dest(), *send.src());
            },
        }
    }

    /// set the nodes for which we are interested in the output PCM signals.
    /// Future calls to `step()` will return an array of samples corresponding
    /// to these nodes.
    fn watch_nodes(&mut self, outputs: &[Rc<YNode>]) {
        //self.output_nodes = outputs.to_vec();
        self.outputs = outputs.iter().map(|node|
            OutputState::new(self.render_spec.clone(), node.clone())
        ).collect();
    }
    /// Return the next buffer of samples related to the watched nodes.
    fn step(&mut self) -> &[f32] {
        unimplemented!();
        &self.output_buff
    }
}

impl ANodeState {
    fn new() -> ANodeState {
        ANodeState{ left:vec![], right: vec![], aasends: vec![], aysends:vec![] }
    }
    fn add_aasend(&mut self, send: AASend) {
        self.aasends.push(send);
    }
    fn add_aysend(&mut self, send: AYSend) {
        self.aysends.push(send);
    }
}

impl YNodeState {
    fn new() -> YNodeState {
        YNodeState{ left:vec![], right: vec![], yysends: vec![] }
    }
    fn add_yysend(&mut self, send: YYSend) {
        self.yysends.push(send);
    }
}

impl OutputState {
    fn new(spec: RenderSpec, node: Rc<YNode>) -> OutputState {
        OutputState{ node: node, renderer: PartialRenderer::new(spec) }
    }
    fn node(&self) -> &Rc<YNode> {
        &self.node
    }
}

<commit_msg>Implement TreeRenderer::step()<commit_after>use std::collections::hash_map::HashMap;
use std::rc::Rc;

use automation::Automation;
use partial::Partial;
use tree::node::{ANode, NodeInputSlot, YNode};
use tree::send::{AASend, AYSend, Send, YYSend};
use tree::tree::Tree;

use render::render_spec::RenderSpec;

use super::partial_renderer::PartialRenderer;

/// Tracks all the partials/automations that have ever entered the node.
/// This information is needed in order to evaluate the output whenever
/// a new input arrives.
struct ANodeState {
    left: Vec<Automation>,
    right: Vec<Automation>,
    aasends: Vec<AASend>,
    aysends: Vec<AYSend>,
}

/// Tracks all the partials/automations that have ever entered the node.
/// This information is needed in order to evaluate the output whenever
/// a new input arrives.
struct YNodeState {
    left: Vec<Partial>,
    right: Vec<Automation>,
    yysends: Vec<YYSend>,
}

struct OutputState {
    node: Rc<YNode>,
    renderer: PartialRenderer,
}

struct TreeRenderer {
    render_spec: RenderSpec,
    anode_states: HashMap<Rc<ANode>, ANodeState>,
    ynode_states: HashMap<Rc<YNode>, YNodeState>,
    outputs: Vec<OutputState>,
    // In order to return a slice from the step() function, we need to allocate
    // some buffer space
    output_buff: Vec<f32>,
}

impl TreeRenderer {
    pub fn new(render_spec: RenderSpec) -> TreeRenderer {
        TreeRenderer{
            render_spec: render_spec,
            anode_states: HashMap::new(),
            ynode_states: HashMap::new(),
            outputs: vec![],
            output_buff: vec![],
        }
    }
    /// Get the ANodeState associated with a node,
    /// and create it if it doesn't already exist.
    fn get_anode_state(&mut self, node: &Rc<ANode>) -> &mut ANodeState {
        self.anode_states.entry(node.clone()).or_insert_with(|| ANodeState::new())
    }
    /// Get the YNodeState associated with a node,
    /// and create it if it doesn't already exist.
    fn get_ynode_state(&mut self, node: &Rc<YNode>) -> &mut YNodeState {
        self.ynode_states.entry(node.clone()).or_insert_with(|| YNodeState::new())
    }
    /// Send a partial to the input of any nodes connected to the output of the
    /// given node.
    fn broadcast_partial(&mut self, from: &Rc<YNode>, partial: Partial) {
        // need to clone the State's sends to avoid mutability problems
        let sends = self.get_ynode_state(from).yysends.clone();
        for ref send in sends.iter() {
            self.ynode_input_left(send.dest(), partial);
        }
    }
    /// Send an Automation to the input of any nodes connected to the output of
    /// the given node.
    fn broadcast_autom(&mut self, from: &Rc<ANode>, autom: Automation) {
        // need to clone the State's sends to avoid mutability problems
        let aasends = self.get_anode_state(from).aasends.clone();
        let aysends = self.get_anode_state(from).aysends.clone();
        // send automation input to the YNodes:
        for ref send in aysends.iter() {
            self.ynode_input_right(send.dest(), autom);
        }
        // send the automation to the other ANodes:
        for ref send in aasends.iter() {
            self.anode_input(send.dest(), send.dest_slot(), autom);
        }
    }
    /// Add a partial to the YNode's left slot
    fn ynode_input_left(&mut self, node: &Rc<YNode>, partial: Partial) {
        let right;
        {
            let mut state = self.get_ynode_state(node);
            state.left.push(partial);
            // need to clone the State's right-hand-side to avoid mut issues
            right = state.right.clone();
        }
        // compute any new outputs & broadcast them.
        for autom in right.iter() {
            self.broadcast_partial(node, autom.apply_to_partial(partial));
        }
    }
    fn ynode_input_right(&mut self, node: &Rc<YNode>, autom: Automation) {
        let left;
        {
            let mut state = self.get_ynode_state(node);
            state.right.push(autom);
            // need to clone the State's left-hand-side to avoid mut issues
            left = state.left.clone();
        }
        // compute any new outputs & broadcast them.
        for partial in left.iter() {
            self.broadcast_partial(node, autom.apply_to_partial(*partial));
        }
    }
    fn anode_input(&mut self, node: &Rc<ANode>, slot: NodeInputSlot,
      autom: Automation) {
        match slot {
            NodeInputSlot::Left => {
                let right;
                {
                    let mut state = self.get_anode_state(node);
                    state.left.push(autom);
                    right = state.right.clone();
                }
                // all the automations in the right bin affect the new autom
                for autom_right in right.iter() {
                    self.broadcast_autom(node, autom_right.apply_to_autom(autom));
                }
            },
            NodeInputSlot::Right => {
                let left;
                {
                    let mut state = self.get_anode_state(node);
                    state.right.push(autom);
                    left = state.left.clone();
                }
                // this new autom affects all automations in the left bin
                for autom_left in left.iter() {
                    self.broadcast_autom(node, autom.apply_to_autom(*autom_left));
                }
            },
        };
    }
}

impl Tree for TreeRenderer {
    /// Connect two nodes in the tree.
    /// If the send is ASrcSend / YSrcSend, this is the same as feeding
    /// external stimuli into the tree.
    fn add_send(&mut self, send: Send) {
        match send {
            Send::AASend(send) => {
                self.get_anode_state(send.src()).add_aasend(send);
            },
            Send::AYSend(send) => {
                self.get_anode_state(send.src()).add_aysend(send);
            },
            Send::YYSend(send) => {
                self.get_ynode_state(send.src()).add_yysend(send);
            },
            Send::ASrcSend(send) => {
                self.broadcast_autom(send.dest(), *send.src());
            },
            Send::YSrcSend(send) => {
                self.broadcast_partial(send.dest(), *send.src());
            },
        }
    }

    /// set the nodes for which we are interested in the output PCM signals.
    /// Future calls to `step()` will return an array of samples corresponding
    /// to these nodes.
    fn watch_nodes(&mut self, outputs: &[Rc<YNode>]) {
        self.outputs = outputs.iter().map(|node|
            OutputState::new(self.render_spec.clone(), node.clone())
        ).collect();
    }
    /// Return the next buffer of samples related to the watched nodes.
    fn step(&mut self) -> &[f32] {
        // Todo: Make use of `Vec::resize once stabilized (Projected for Rust 1.5)
        self.output_buff = self.outputs.iter_mut().map(
            |output| output.step()
        ).collect();
        &self.output_buff
    }
}

impl ANodeState {
    fn new() -> ANodeState {
        ANodeState{ left:vec![], right: vec![], aasends: vec![], aysends:vec![] }
    }
    fn add_aasend(&mut self, send: AASend) {
        self.aasends.push(send);
    }
    fn add_aysend(&mut self, send: AYSend) {
        self.aysends.push(send);
    }
}

impl YNodeState {
    fn new() -> YNodeState {
        YNodeState{ left:vec![], right: vec![], yysends: vec![] }
    }
    fn add_yysend(&mut self, send: YYSend) {
        self.yysends.push(send);
    }
}

impl OutputState {
    fn new(spec: RenderSpec, node: Rc<YNode>) -> OutputState {
        OutputState{ node: node, renderer: PartialRenderer::new(spec) }
    }
    fn node(&self) -> &Rc<YNode> {
        &self.node
    }
    fn step(&mut self) -> f32 {
        self.renderer.step()
    }
}

<|endoftext|>


<commit_before><commit_msg>Auto merge of #45007 - undecidabot:optimize-iter, r=bluss<commit_after><|endoftext|>


<commit_before>#![no_main]
extern crate libfuzzer_sys;
extern crate capnp;

pub mod test_capnp {
  include!(concat!(env!("OUT_DIR"), "/test_capnp.rs"));
}

use capnp::{serialize, message};
use test_capnp::test_all_types;

fn traverse(v: test_all_types::Reader) -> ::capnp::Result<()> {
    v.get_int64_field();
    v.get_float32_field();
    v.get_float64_field();
    v.get_text_field()?;
    v.get_data_field()?;
    v.get_struct_field()?;
    v.get_enum_field()?;

    let structs = v.get_struct_list()?;
    for s in structs.iter() {
        s.get_text_field()?;
        s.get_data_field()?;
    }

    let bools = v.get_bool_list()?;
    for idx in 0 .. bools.len() {
        bools.get(idx);
    }

    let enums = v.get_enum_list()?;
    for idx in 0 .. enums.len() {
        enums.get(idx)?;
    }

    let int8s = v.get_int8_list()?;
    for idx in 0 .. int8s.len() {
        int8s.get(idx);
    }

    Ok(())
}

fn try_go(mut data: &[u8]) -> ::capnp::Result<()> {
    let orig_data = data;
    let message_reader = serialize::read_message(
        &mut data,
        *message::ReaderOptions::new().traversal_limit_in_words(4 * 1024))?;
    assert!(orig_data.len() > data.len());

    let root: test_all_types::Reader = message_reader.get_root()?;
    root.total_size()?;
    traverse(root)?;

    let mut message = message::Builder::new_default();
    message.set_root(root)?;
    {
        let mut root_builder = message.get_root::<test_all_types::Builder>()?;
        root_builder.total_size()?;

        root_builder.set_struct_field(root)?;
        {
            let list = root_builder.reborrow().init_struct_list(2);
            list.set_with_caveats(0,  root)?;
            list.set_with_caveats(1,  root)?;
        }

        traverse(root_builder.into_reader())?;
    }

    // init_root() will zero the previous value
    let mut new_root = message.init_root::<test_all_types::Builder>();
    new_root.set_struct_field(root)?;

    Ok(())
}

#[export_name="rust_fuzzer_test_input"]
pub extern fn go(data: &[u8]) {
    let _ = try_go(data);
}
<commit_msg>update fuzz test to work with 0.14<commit_after>#![no_main]
extern crate libfuzzer_sys;
extern crate capnp;

pub mod test_capnp {
  include!(concat!(env!("OUT_DIR"), "/test_capnp.rs"));
}

use capnp::{serialize, message};
use test_capnp::test_all_types;

fn traverse(v: test_all_types::Reader) -> ::capnp::Result<()> {
    v.get_int64_field();
    v.get_float32_field();
    v.get_float64_field();
    v.get_text_field()?;
    v.get_data_field()?;
    v.get_struct_field()?;
    v.get_enum_field()?;

    let structs = v.get_struct_list()?;
    for s in structs.iter() {
        s.get_text_field()?;
        s.get_data_field()?;
    }

    let bools = v.get_bool_list()?;
    for idx in 0 .. bools.len() {
        bools.get(idx);
    }

    let enums = v.get_enum_list()?;
    for idx in 0 .. enums.len() {
        enums.get(idx)?;
    }

    let int8s = v.get_int8_list()?;
    for idx in 0 .. int8s.len() {
        int8s.get(idx);
    }

    Ok(())
}

fn try_go(mut data: &[u8]) -> ::capnp::Result<()> {
    let orig_data = data;
    let message_reader = serialize::read_message(
        &mut data,
        *message::ReaderOptions::new().traversal_limit_in_words(Some(4 * 1024)))?;
    assert!(orig_data.len() > data.len());

    let root: test_all_types::Reader = message_reader.get_root()?;
    root.total_size()?;
    traverse(root)?;

    let mut message = message::Builder::new_default();
    message.set_root(root)?;
    {
        let mut root_builder = message.get_root::<test_all_types::Builder>()?;
        root_builder.total_size()?;

        root_builder.set_struct_field(root)?;
        {
            let list = root_builder.reborrow().init_struct_list(2);
            list.set_with_caveats(0,  root)?;
            list.set_with_caveats(1,  root)?;
        }

        traverse(root_builder.into_reader())?;
    }

    // init_root() will zero the previous value
    let mut new_root = message.init_root::<test_all_types::Builder>();
    new_root.set_struct_field(root)?;

    Ok(())
}

#[export_name="rust_fuzzer_test_input"]
pub extern fn go(data: &[u8]) {
    let _ = try_go(data);
}
<|endoftext|>


<commit_before>use gl;
use yaglw::gl_context::GLContext;
use yaglw::shader::Shader;

pub struct T<'a> {
  #[allow(missing_docs)]
  pub shader: Shader<'a>,
}

pub fn new<'a, 'b:'a>(gl: &'a GLContext) -> T<'b> {
  let components = vec!(
    (gl::VERTEX_SHADER, "
      #version 330 core

      void main() {
        if (gl_VertexID == 0) {
          gl_Position = vec4(1, -1, 0, 1);
        } else if (gl_VertexID == 1) {
          gl_Position = vec4(1, 1, 0, 1);
        } else if (gl_VertexID == 2) {
          gl_Position = vec4(-1, -1, 0, 1);
        } else if (gl_VertexID == 3) {
          gl_Position = vec4(-1, 1, 0, 1);
        }
      }".to_owned()),
    (gl::FRAGMENT_SHADER,
      format!(r#"
        #version 330 core

        uniform vec2 window_size;

        uniform struct Sun {{
          vec3 direction;
          vec3 intensity;
        }} sun;

        const float sun_angular_radius = 3.14/32;

        uniform mat4 projection_matrix;
        uniform vec3 eye_position;

        uniform float time_ms;

        out vec4 frag_color;

        // include depth fog
        {}

        // include cnoise
        {}

        vec3 pixel_direction(vec2 pixel) {{
          // Scale to [0, 1]
          pixel /= window_size;
          // Scale to [-1, 1]
          pixel = 2*pixel - 1;
          vec4 p = inverse(projection_matrix) * vec4(pixel, -1, 1);
          return normalize(vec3(p / p.w) - eye_position);
        }}

        float cloud_noise(vec3 seed) {{
          float f = cnoise(seed + vec3(0, time_ms / 8000, 0));
          return f;
        }}

        float cloud_density(vec3 seed) {{
          float d = (2.0*cloud_noise(seed / 2) + cloud_noise(seed) + 0.5*cloud_noise(2.0 * seed) + 0.25*cloud_noise(4.0*seed)) / 3.75;
          d = (d + 1) / 2;
          float min_cloud = 0.4;
          float max_cloud = 0.8;
          d = (d - min_cloud) / (max_cloud - min_cloud);
          d = min(max(d, 0), 1);
          return d;
        }}

        void main() {{
          vec3 direction = pixel_direction(gl_FragCoord.xy);

          const int HEIGHTS = 2;
          float heights[HEIGHTS] = float[](150, 1000);
          vec3 offsets[HEIGHTS] = vec3[](vec3(12,553,239), vec3(-10, 103, 10004));

          vec3 c = vec3(0);
          float alpha = 1;
          for (int i = 0; i < HEIGHTS; ++i) {{
            float cloud_height = heights[i];
            float dist = (cloud_height - eye_position.y) / direction.y;
            if (dist <= 0 || dist > 1000000) {{
              continue;
            }} else {{
              vec3 seed = (eye_position + dist * direction + offsets[i]) / 1000 * vec3(1, 4, 1);

              float depth_alpha = fog_density(dist / 64);
              float density = cloud_density(seed);
              float cloud_alpha = density * (1 - depth_alpha);
              c += alpha * cloud_alpha * vec3(mix(0.4, 1, (exp(1 - density) - 1) / (exp(1) - 1)));
              alpha *= (1 - cloud_alpha);
            }}
          }}

          float sunniness = exp(64 * (dot(sun.direction, direction) - cos(sun_angular_radius)));
          vec3 infinity_color = mix(sun.intensity, vec3(1), sunniness);
          c += alpha * infinity_color;

          frag_color = min(vec4(c, 1), vec4(1));
        }}"#,
        ::shaders::depth_fog::to_string(),
        ::shaders::noise::cnoise(),
      )
    ),
  );
  T {
    shader: Shader::new(gl, components.into_iter()),
  }
}
<commit_msg>attempt to light clouds based on directional density<commit_after>use gl;
use yaglw::gl_context::GLContext;
use yaglw::shader::Shader;

pub struct T<'a> {
  #[allow(missing_docs)]
  pub shader: Shader<'a>,
}

pub fn new<'a, 'b:'a>(gl: &'a GLContext) -> T<'b> {
  let components = vec!(
    (gl::VERTEX_SHADER, "
      #version 330 core

      void main() {
        if (gl_VertexID == 0) {
          gl_Position = vec4(1, -1, 0, 1);
        } else if (gl_VertexID == 1) {
          gl_Position = vec4(1, 1, 0, 1);
        } else if (gl_VertexID == 2) {
          gl_Position = vec4(-1, -1, 0, 1);
        } else if (gl_VertexID == 3) {
          gl_Position = vec4(-1, 1, 0, 1);
        }
      }".to_owned()),
    (gl::FRAGMENT_SHADER,
      format!(r#"
        #version 330 core

        uniform vec2 window_size;

        uniform struct Sun {{
          vec3 direction;
          vec3 intensity;
        }} sun;

        const float sun_angular_radius = 3.14/32;

        uniform mat4 projection_matrix;
        uniform vec3 eye_position;

        uniform float time_ms;

        out vec4 frag_color;

        // include depth fog
        {}

        // include cnoise
        {}

        vec3 pixel_direction(vec2 pixel) {{
          // Scale to [0, 1]
          pixel /= window_size;
          // Scale to [-1, 1]
          pixel = 2*pixel - 1;
          vec4 p = inverse(projection_matrix) * vec4(pixel, -1, 1);
          return normalize(vec3(p / p.w) - eye_position);
        }}

        float cloud_noise(vec3 seed) {{
          float f = cnoise(seed + vec3(0, time_ms / 8000, 0));
          return f;
        }}

        float cloud_density(vec3 seed) {{
          float d = (2.0*cloud_noise(seed / 2) + cloud_noise(seed) + 0.5*cloud_noise(2.0 * seed) + 0.25*cloud_noise(4.0*seed)) / 3.75;
          d = (d + 1) / 2;
          return d;
        }}

        void main() {{
          vec3 direction = pixel_direction(gl_FragCoord.xy);

          const int HEIGHTS = 2;
          float heights[HEIGHTS] = float[](150, 1000);
          vec3 offsets[HEIGHTS] = vec3[](vec3(12,553,239), vec3(-10, 103, 10004));

          vec3 c = vec3(0);
          float alpha = 1;
          for (int i = 0; i < HEIGHTS; ++i) {{
            float cloud_height = heights[i];
            float dist = (cloud_height - eye_position.y) / direction.y;
            if (dist <= 0 || dist > 1000000) {{
              continue;
            }} else {{
              vec3 seed = (eye_position + dist * direction + offsets[i]) / 1000 * vec3(1, 4, 1);

              float depth_alpha = fog_density(dist / 16);

              float density = cloud_density(seed);

              float cloud_alpha = density;
              float min_cloud = 0.4;
              float max_cloud = 0.8;
              cloud_alpha = (cloud_alpha - min_cloud) / (max_cloud - min_cloud);
              cloud_alpha = min(max(cloud_alpha, 0), 1);
              cloud_alpha *= (1 - depth_alpha);

              float lightness = pow(max(density - cloud_density(seed + 10 * sun.direction), 0), 1.0) * (1 - density);
              vec3 cloud_color = vec3(mix(0.4, 1, lightness));
              c += alpha * cloud_alpha * cloud_color;
              alpha *= (1 - cloud_alpha);
            }}
          }}

          float sunniness = exp(64 * (dot(sun.direction, direction) - cos(sun_angular_radius)));
          vec3 infinity_color = mix(sun.intensity, vec3(1), sunniness);
          c += alpha * infinity_color;

          frag_color = min(vec4(c, 1), vec4(1));
        }}"#,
        ::shaders::depth_fog::to_string(),
        ::shaders::noise::cnoise(),
      )
    ),
  );
  T {
    shader: Shader::new(gl, components.into_iter()),
  }
}
<|endoftext|>


<commit_before>use rustc::lint::*;
use rustc::hir::*;
use syntax::ast;
use utils::{is_adjusted, match_path, match_trait_method, match_type, remove_blocks, paths, snippet,
            span_help_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, iter_input_pats};

/// **What it does:** Checks for mapping `clone()` over an iterator.
///
/// **Why is this bad?** It makes the code less readable than using the
/// `.cloned()` adapter.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// x.map(|e| e.clone());
/// ```
declare_lint! {
    pub MAP_CLONE,
    Warn,
    "using `.map(|x| x.clone())` to clone an iterator or option's contents"
}

#[derive(Copy, Clone)]
pub struct Pass;

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
    fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
        // call to .map()
        if let ExprMethodCall(name, _, ref args) = expr.node {
            if &*name.node.as_str() == "map" && args.len() == 2 {
                match args[1].node {
                    ExprClosure(_, ref decl, closure_eid, _) => {
                        let body = cx.tcx.map.body(closure_eid);
                        let closure_expr = remove_blocks(&body.value);
                        if_let_chain! {[
                            // nothing special in the argument, besides reference bindings
                            // (e.g. .map(|&x| x) )
                            let Some(first_arg) = iter_input_pats(decl, body).next(),
                            let Some(arg_ident) = get_arg_name(&first_arg.pat),
                            // the method is being called on a known type (option or iterator)
                            let Some(type_name) = get_type_name(cx, expr, &args[0])
                        ], {
                            // look for derefs, for .map(|x| *x)
                            if only_derefs(cx, &*closure_expr, arg_ident) &&
                                // .cloned() only removes one level of indirection, don't lint on more
                                walk_ptrs_ty_depth(cx.tables.pat_ty(&first_arg.pat)).1 == 1
                            {
                                span_help_and_lint(cx, MAP_CLONE, expr.span, &format!(
                                    "you seem to be using .map() to clone the contents of an {}, consider \
                                    using `.cloned()`", type_name),
                                    &format!("try\n{}.cloned()", snippet(cx, args[0].span, "..")));
                            }
                            // explicit clone() calls ( .map(|x| x.clone()) )
                            else if let ExprMethodCall(clone_call, _, ref clone_args) = closure_expr.node {
                                if &*clone_call.node.as_str() == "clone" &&
                                    clone_args.len() == 1 &&
                                    match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) &&
                                    expr_eq_name(&clone_args[0], arg_ident)
                                {
                                    span_help_and_lint(cx, MAP_CLONE, expr.span, &format!(
                                        "you seem to be using .map() to clone the contents of an {}, consider \
                                        using `.cloned()`", type_name),
                                        &format!("try\n{}.cloned()", snippet(cx, args[0].span, "..")));
                                }
                            }
                        }}
                    },
                    ExprPath(ref path) => {
                        if match_path(path, &paths::CLONE) {
                            let type_name = get_type_name(cx, expr, &args[0]).unwrap_or("_");
                            span_help_and_lint(cx,
                                               MAP_CLONE,
                                               expr.span,
                                               &format!("you seem to be using .map() to clone the contents of an \
                                                         {}, consider using `.cloned()`",
                                                        type_name),
                                               &format!("try\n{}.cloned()", snippet(cx, args[0].span, "..")));
                        }
                    },
                    _ => (),
                }
            }
        }
    }
}

fn expr_eq_name(expr: &Expr, id: ast::Name) -> bool {
    match expr.node {
        ExprPath(QPath::Resolved(None, ref path)) => {
            let arg_segment = [PathSegment {
                                   name: id,
                                   parameters: PathParameters::none(),
                               }];
            !path.is_global() && path.segments[..] == arg_segment
        },
        _ => false,
    }
}

fn get_type_name(cx: &LateContext, expr: &Expr, arg: &Expr) -> Option<&'static str> {
    if match_trait_method(cx, expr, &paths::ITERATOR) {
        Some("iterator")
    } else if match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(arg)), &paths::OPTION) {
        Some("Option")
    } else {
        None
    }
}

fn get_arg_name(pat: &Pat) -> Option<ast::Name> {
    match pat.node {
        PatKind::Binding(_, _, name, None) => Some(name.node),
        PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
        _ => None,
    }
}

fn only_derefs(cx: &LateContext, expr: &Expr, id: ast::Name) -> bool {
    match expr.node {
        ExprUnary(UnDeref, ref subexpr) if !is_adjusted(cx, subexpr) => only_derefs(cx, subexpr, id),
        _ => expr_eq_name(expr, id),
    }
}

impl LintPass for Pass {
    fn get_lints(&self) -> LintArray {
        lint_array!(MAP_CLONE)
    }
}
<commit_msg>Rustfmtup to 0.7.1<commit_after>use rustc::lint::*;
use rustc::hir::*;
use syntax::ast;
use utils::{is_adjusted, match_path, match_trait_method, match_type, remove_blocks, paths, snippet, span_help_and_lint,
            walk_ptrs_ty, walk_ptrs_ty_depth, iter_input_pats};

/// **What it does:** Checks for mapping `clone()` over an iterator.
///
/// **Why is this bad?** It makes the code less readable than using the
/// `.cloned()` adapter.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// x.map(|e| e.clone());
/// ```
declare_lint! {
    pub MAP_CLONE,
    Warn,
    "using `.map(|x| x.clone())` to clone an iterator or option's contents"
}

#[derive(Copy, Clone)]
pub struct Pass;

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
    fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
        // call to .map()
        if let ExprMethodCall(name, _, ref args) = expr.node {
            if &*name.node.as_str() == "map" && args.len() == 2 {
                match args[1].node {
                    ExprClosure(_, ref decl, closure_eid, _) => {
                        let body = cx.tcx.map.body(closure_eid);
                        let closure_expr = remove_blocks(&body.value);
                        if_let_chain! {[
                            // nothing special in the argument, besides reference bindings
                            // (e.g. .map(|&x| x) )
                            let Some(first_arg) = iter_input_pats(decl, body).next(),
                            let Some(arg_ident) = get_arg_name(&first_arg.pat),
                            // the method is being called on a known type (option or iterator)
                            let Some(type_name) = get_type_name(cx, expr, &args[0])
                        ], {
                            // look for derefs, for .map(|x| *x)
                            if only_derefs(cx, &*closure_expr, arg_ident) &&
                                // .cloned() only removes one level of indirection, don't lint on more
                                walk_ptrs_ty_depth(cx.tables.pat_ty(&first_arg.pat)).1 == 1
                            {
                                span_help_and_lint(cx, MAP_CLONE, expr.span, &format!(
                                    "you seem to be using .map() to clone the contents of an {}, consider \
                                    using `.cloned()`", type_name),
                                    &format!("try\n{}.cloned()", snippet(cx, args[0].span, "..")));
                            }
                            // explicit clone() calls ( .map(|x| x.clone()) )
                            else if let ExprMethodCall(clone_call, _, ref clone_args) = closure_expr.node {
                                if &*clone_call.node.as_str() == "clone" &&
                                    clone_args.len() == 1 &&
                                    match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) &&
                                    expr_eq_name(&clone_args[0], arg_ident)
                                {
                                    span_help_and_lint(cx, MAP_CLONE, expr.span, &format!(
                                        "you seem to be using .map() to clone the contents of an {}, consider \
                                        using `.cloned()`", type_name),
                                        &format!("try\n{}.cloned()", snippet(cx, args[0].span, "..")));
                                }
                            }
                        }}
                    },
                    ExprPath(ref path) => {
                        if match_path(path, &paths::CLONE) {
                            let type_name = get_type_name(cx, expr, &args[0]).unwrap_or("_");
                            span_help_and_lint(cx,
                                               MAP_CLONE,
                                               expr.span,
                                               &format!("you seem to be using .map() to clone the contents of an \
                                                         {}, consider using `.cloned()`",
                                                        type_name),
                                               &format!("try\n{}.cloned()", snippet(cx, args[0].span, "..")));
                        }
                    },
                    _ => (),
                }
            }
        }
    }
}

fn expr_eq_name(expr: &Expr, id: ast::Name) -> bool {
    match expr.node {
        ExprPath(QPath::Resolved(None, ref path)) => {
            let arg_segment = [PathSegment {
                                   name: id,
                                   parameters: PathParameters::none(),
                               }];
            !path.is_global() && path.segments[..] == arg_segment
        },
        _ => false,
    }
}

fn get_type_name(cx: &LateContext, expr: &Expr, arg: &Expr) -> Option<&'static str> {
    if match_trait_method(cx, expr, &paths::ITERATOR) {
        Some("iterator")
    } else if match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(arg)), &paths::OPTION) {
        Some("Option")
    } else {
        None
    }
}

fn get_arg_name(pat: &Pat) -> Option<ast::Name> {
    match pat.node {
        PatKind::Binding(_, _, name, None) => Some(name.node),
        PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
        _ => None,
    }
}

fn only_derefs(cx: &LateContext, expr: &Expr, id: ast::Name) -> bool {
    match expr.node {
        ExprUnary(UnDeref, ref subexpr) if !is_adjusted(cx, subexpr) => only_derefs(cx, subexpr, id),
        _ => expr_eq_name(expr, id),
    }
}

impl LintPass for Pass {
    fn get_lints(&self) -> LintArray {
        lint_array!(MAP_CLONE)
    }
}
<|endoftext|>