<commit_before>//
// Sysinfo
//
// Copyright (c) 2017 Guillaume Gomez
//

#![crate_type = "bin"]
#![allow(unused_must_use, non_upper_case_globals)]

extern crate sysinfo;

use std::io::{self, BufRead, Write};
use std::str::FromStr;
use sysinfo::Signal::*;
use sysinfo::{NetworkExt, NetworksExt, Pid, ProcessExt, ProcessorExt, Signal, System, SystemExt};

const signals: [Signal; 31] = [
    Hangup,
    Interrupt,
    Quit,
    Illegal,
    Trap,
    Abort,
    Bus,
    FloatingPointException,
    Kill,
    User1,
    Segv,
    User2,
    Pipe,
    Alarm,
    Term,
    Stklft,
    Child,
    Continue,
    Stop,
    TSTP,
    TTIN,
    TTOU,
    Urgent,
    XCPU,
    XFSZ,
    VirtualAlarm,
    Profiling,
    Winch,
    IO,
    Power,
    Sys,
];

fn print_help() {
    writeln!(&mut io::stdout(), "== Help menu ==");
    writeln!(&mut io::stdout(), "help               : show this menu");
    writeln!(
        &mut io::stdout(),
        "signals            : show the available signals"
    );
    writeln!(
        &mut io::stdout(),
        "refresh            : reloads all processes' information"
    );
    writeln!(
        &mut io::stdout(),
        "refresh [pid]      : reloads corresponding process' information"
    );
    writeln!(
        &mut io::stdout(),
        "refresh_disks      : reloads only disks' information"
    );
    writeln!(
        &mut io::stdout(),
        "show [pid | name]  : show information of the given process \
                                 corresponding to [pid | name]"
    );
    writeln!(
        &mut io::stdout(),
        "kill [pid] [signal]: send [signal] to the process with this \
                                 [pid]. 0 < [signal] < 32"
    );
    writeln!(
        &mut io::stdout(),
        "procd              : Displays processors state"
    );
    writeln!(
        &mut io::stdout(),
        "memory             : Displays memory state"
    );
    writeln!(
        &mut io::stdout(),
        "temperature        : Displays components' temperature"
    );
    writeln!(
        &mut io::stdout(),
        "disks              : Displays disks' information"
    );
    writeln!(
        &mut io::stdout(),
        "network            : Displays network' information"
    );
    writeln!(
        &mut io::stdout(),
        "all                : Displays all process name and pid"
    );
    writeln!(
        &mut io::stdout(),
        "uptime             : Displays system uptime"
    );
    writeln!(
        &mut io::stdout(),
        "vendor_id          : Displays processor vendor id"
    );
    writeln!(
        &mut io::stdout(),
        "brand              : Displays processor brand"
    );
    writeln!(
        &mut io::stdout(),
        "load_avg           : Displays system load average"
    );
    writeln!(
        &mut io::stdout(),
        "frequency          : Displays processor frequency"
    );
    writeln!(&mut io::stdout(), "quit               : exit the program");
}

fn interpret_input(input: &str, sys: &mut System) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            sys.refresh_disks_list();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in &signals {
                writeln!(&mut io::stdout(), "{:2}:{:?}", nb, sig);
                nb += 1;
            }
        }
        "procs" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            let procs = sys.get_processors();

            writeln!(
                &mut io::stdout(),
                "total process usage: {}%",
                procs[0].get_cpu_usage()
            );
            for proc_ in procs.iter().skip(1) {
                writeln!(&mut io::stdout(), "{:?}", proc_);
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory: {} KiB",
                sys.get_total_memory()
            );
            writeln!(
                &mut io::stdout(),
                "used memory : {} KiB",
                sys.get_used_memory()
            );
            writeln!(
                &mut io::stdout(),
                "total swap  : {} KiB",
                sys.get_total_swap()
            );
            writeln!(
                &mut io::stdout(),
                "used swap   : {} KiB",
                sys.get_used_swap()
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.get_process_list() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            writeln!(
                &mut io::stdout(),
                "{} MHz",
                sys.get_processors()[0].get_frequency()
            );
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.get_processors()[0].get_vendor_id()
            );
        }
        "brand" => {
            writeln!(
                &mut io::stdout(),
                "brand: {}",
                sys.get_processors()[0].get_brand()
            );
        }
        "load_avg" => {
            let load_avg = sys.get_load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.get_process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{:?}\" not found", pid),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.get_process_by_name(proc_name) {
                    writeln!(&mut io::stdout(), "==== {} ====", proc_.name());
                    writeln!(&mut io::stdout(), "{:?}", proc_);
                }
            }
        }
        "temperature" => {
            for component in sys.get_components() {
                writeln!(&mut io::stdout(), "{:?}", component);
            }
        }
        "network" => {
            for (interface_name, data) in sys.get_networks().iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.get_income(),
                    data.get_total_income(),
                    data.get_outcome(),
                    data.get_total_outcome(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter !"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                              signals command"
                    );
                } else {
                    match sys.get_process(pid) {
                        Some(p) => {
                            writeln!(
                                &mut io::stdout(),
                                "kill: {}",
                                p.kill(*signals.get(signal as usize - 1).unwrap())
                            );
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in sys.get_disks() {
                writeln!(&mut io::stdout(), "{:?}", disk);
            }
        }
        "uptime" => {
            let mut uptime = sys.get_uptime();
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{} days {} hours {} minutes",
                days,
                hours,
                minutes
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_process(pid) {
                        writeln!(&mut io::stdout(), "Process `{}` updated successfully", pid);
                    } else {
                        writeln!(
                            &mut io::stdout(),
                            "Process `{}` couldn't be updated...",
                            pid
                        );
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \
                      list.",
                    x
                );
            }
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \
                      list.",
                e
            );
        }
    }
    false
}

fn main() {
    println!("Getting processes' information...");
    let mut t = System::new_all();
    println!("Done.");
    let t_stin = io::stdin();
    let mut stin = t_stin.lock();
    let mut done = false;

    println!("To get the commands' list, enter 'help'.");
    while !done {
        let mut input = String::new();
        write!(&mut io::stdout(), "> ");
        io::stdout().flush();

        stin.read_line(&mut input);
        if input.is_empty() {
            // The string is empty, meaning there is no '\n', meaning
            // that the user used CTRL+D so we can just quit!
            println!("\nLeaving, bye!");
            break;
        }
        if (&input as &str).ends_with('\n') {
            input.pop();
        }
        done = interpret_input(input.as_ref(), &mut t);
    }
}
<commit_msg>Update example<commit_after>//
// Sysinfo
//
// Copyright (c) 2017 Guillaume Gomez
//

#![crate_type = "bin"]
#![allow(unused_must_use, non_upper_case_globals)]

extern crate sysinfo;

use std::io::{self, BufRead, Write};
use std::str::FromStr;
use sysinfo::Signal::*;
use sysinfo::{NetworkExt, NetworksExt, Pid, ProcessExt, ProcessorExt, Signal, System, SystemExt};

const signals: [Signal; 31] = [
    Hangup,
    Interrupt,
    Quit,
    Illegal,
    Trap,
    Abort,
    Bus,
    FloatingPointException,
    Kill,
    User1,
    Segv,
    User2,
    Pipe,
    Alarm,
    Term,
    Stklft,
    Child,
    Continue,
    Stop,
    TSTP,
    TTIN,
    TTOU,
    Urgent,
    XCPU,
    XFSZ,
    VirtualAlarm,
    Profiling,
    Winch,
    IO,
    Power,
    Sys,
];

fn print_help() {
    writeln!(&mut io::stdout(), "== Help menu ==");
    writeln!(&mut io::stdout(), "help               : show this menu");
    writeln!(
        &mut io::stdout(),
        "signals            : show the available signals"
    );
    writeln!(
        &mut io::stdout(),
        "refresh            : reloads all processes' information"
    );
    writeln!(
        &mut io::stdout(),
        "refresh [pid]      : reloads corresponding process' information"
    );
    writeln!(
        &mut io::stdout(),
        "refresh_disks      : reloads only disks' information"
    );
    writeln!(
        &mut io::stdout(),
        "show [pid | name]  : show information of the given process \
                                 corresponding to [pid | name]"
    );
    writeln!(
        &mut io::stdout(),
        "kill [pid] [signal]: send [signal] to the process with this \
                                 [pid]. 0 < [signal] < 32"
    );
    writeln!(
        &mut io::stdout(),
        "processors         : Displays processors state"
    );
    writeln!(
        &mut io::stdout(),
        "memory             : Displays memory state"
    );
    writeln!(
        &mut io::stdout(),
        "temperature        : Displays components' temperature"
    );
    writeln!(
        &mut io::stdout(),
        "disks              : Displays disks' information"
    );
    writeln!(
        &mut io::stdout(),
        "network            : Displays network' information"
    );
    writeln!(
        &mut io::stdout(),
        "all                : Displays all process name and pid"
    );
    writeln!(
        &mut io::stdout(),
        "uptime             : Displays system uptime"
    );
    writeln!(
        &mut io::stdout(),
        "vendor_id          : Displays processor vendor id"
    );
    writeln!(
        &mut io::stdout(),
        "brand              : Displays processor brand"
    );
    writeln!(
        &mut io::stdout(),
        "load_avg           : Displays system load average"
    );
    writeln!(
        &mut io::stdout(),
        "frequency          : Displays processor frequency"
    );
    writeln!(&mut io::stdout(), "quit               : exit the program");
}

fn interpret_input(input: &str, sys: &mut System) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            sys.refresh_disks_list();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in &signals {
                writeln!(&mut io::stdout(), "{:2}:{:?}", nb, sig);
                nb += 1;
            }
        }
        "processors" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "total process usage: {}%",
                sys.get_global_processor_info().get_cpu_usage()
            );
            for proc_ in sys.get_processors() {
                writeln!(&mut io::stdout(), "{:?}", proc_);
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory: {} KiB",
                sys.get_total_memory()
            );
            writeln!(
                &mut io::stdout(),
                "used memory : {} KiB",
                sys.get_used_memory()
            );
            writeln!(
                &mut io::stdout(),
                "total swap  : {} KiB",
                sys.get_total_swap()
            );
            writeln!(
                &mut io::stdout(),
                "used swap   : {} KiB",
                sys.get_used_swap()
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.get_process_list() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            writeln!(
                &mut io::stdout(),
                "{} MHz",
                sys.get_processors()[0].get_frequency()
            );
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.get_processors()[0].get_vendor_id()
            );
        }
        "brand" => {
            writeln!(
                &mut io::stdout(),
                "brand: {}",
                sys.get_processors()[0].get_brand()
            );
        }
        "load_avg" => {
            let load_avg = sys.get_load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.get_process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{:?}\" not found", pid),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.get_process_by_name(proc_name) {
                    writeln!(&mut io::stdout(), "==== {} ====", proc_.name());
                    writeln!(&mut io::stdout(), "{:?}", proc_);
                }
            }
        }
        "temperature" => {
            for component in sys.get_components() {
                writeln!(&mut io::stdout(), "{:?}", component);
            }
        }
        "network" => {
            for (interface_name, data) in sys.get_networks().iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.get_income(),
                    data.get_total_income(),
                    data.get_outcome(),
                    data.get_total_outcome(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter !"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                              signals command"
                    );
                } else {
                    match sys.get_process(pid) {
                        Some(p) => {
                            writeln!(
                                &mut io::stdout(),
                                "kill: {}",
                                p.kill(*signals.get(signal as usize - 1).unwrap())
                            );
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in sys.get_disks() {
                writeln!(&mut io::stdout(), "{:?}", disk);
            }
        }
        "uptime" => {
            let mut uptime = sys.get_uptime();
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{} days {} hours {} minutes",
                days,
                hours,
                minutes
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_process(pid) {
                        writeln!(&mut io::stdout(), "Process `{}` updated successfully", pid);
                    } else {
                        writeln!(
                            &mut io::stdout(),
                            "Process `{}` couldn't be updated...",
                            pid
                        );
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \
                      list.",
                    x
                );
            }
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \
                      list.",
                e
            );
        }
    }
    false
}

fn main() {
    println!("Getting processes' information...");
    let mut t = System::new_all();
    println!("Done.");
    let t_stin = io::stdin();
    let mut stin = t_stin.lock();
    let mut done = false;

    println!("To get the commands' list, enter 'help'.");
    while !done {
        let mut input = String::new();
        write!(&mut io::stdout(), "> ");
        io::stdout().flush();

        stin.read_line(&mut input);
        if input.is_empty() {
            // The string is empty, meaning there is no '\n', meaning
            // that the user used CTRL+D so we can just quit!
            println!("\nLeaving, bye!");
            break;
        }
        if (&input as &str).ends_with('\n') {
            input.pop();
        }
        done = interpret_input(input.as_ref(), &mut t);
    }
}
<|endoftext|>


<commit_before>extern crate nalgebra as na;
extern crate ncollide3d;
extern crate nphysics3d;
extern crate nphysics_testbed3d;
extern crate rand;

use na::{Point3, Vector3};
use ncollide3d::shape::{Cuboid, ShapeHandle, TriMesh};
use nphysics3d::object::{ColliderDesc, RigidBodyDesc};
use nphysics3d::world::World;
use nphysics_testbed3d::Testbed;

use rand::distributions::{Standard, Distribution};
use rand::{SeedableRng, XorShiftRng};

fn main() {
    /*
     * World
     */
    let mut world = World::new();
    world.set_gravity(Vector3::new(0.0, -9.81, 0.0));

    /*
     * Setup a random ground.
     */
    let quad = ncollide3d::procedural::quad(10.0, 10.0, 10, 10);
    let indices = quad
        .flat_indices()
        .chunks(3)
        .map(|is| Point3::new(is[0] as usize, is[2] as usize, is[1] as usize))
        .collect();

    let mut rng = XorShiftRng::seed_from_u64(42);
    let distribution = Standard;

    let mut vertices = quad.coords;

    // ncollide generatse a quad with `z` as the normal.
    // so we switch z and y here and set a random altitude at each point.
    for p in &mut vertices {
        p.z = p.y;
        let y: f32 = distribution.sample(&mut rng);
        p.y = y * 1.5;
    }

    let trimesh: TriMesh<f32> = TriMesh::new(vertices, indices, None);
    ColliderDesc::new(ShapeHandle::new(trimesh))
        .build(&mut world);

    /*
     * Create some boxes and spheres.
     */
    let num = 7;
    let rad = 0.1;
    let shift = rad * 2.0 + 0.5;
    let centerx = shift * (num as f32) / 2.0;
    let centery = shift / 2.0;
    let centerz = shift * (num as f32) / 2.0;
    let height = 1.0;

    let cuboid = ShapeHandle::new(Cuboid::new(Vector3::repeat(rad)));
    let collider_desc = ColliderDesc::new(cuboid)
        .density(1.0);

    let mut rb_desc = RigidBodyDesc::new()
        .collider(&collider_desc);

    for i in 0usize..num {
        for j in 0usize..num {
            for k in 0usize..num {
                let x = i as f32 * shift - centerx;
                let y = j as f32 * shift + centery + height;
                let z = k as f32 * shift - centerz;

                // Build the rigid body and its collider.
                rb_desc
                    .set_translation(Vector3::new(x, y, z))
                    .build(&mut world);
            }
        }
    }

    /*
     * Set up the testbed.
     */
    let testbed = Testbed::new(world);
    testbed.run();
}
<commit_msg>Improve height map in trimesh3 example<commit_after>extern crate nalgebra as na;
extern crate ncollide3d;
extern crate nphysics3d;
extern crate nphysics_testbed3d;
extern crate rand;

use na::{Point3, Vector3};
use ncollide3d::shape::{Cuboid, ShapeHandle, TriMesh};
use nphysics3d::object::{ColliderDesc, RigidBodyDesc};
use nphysics3d::world::World;
use nphysics_testbed3d::Testbed;

use rand::distributions::{Normal, Distribution};
use rand::thread_rng;

fn main() {
    /*
     * World
     */
    let mut world = World::new();
    world.set_gravity(Vector3::new(0.0, -9.81, 0.0));

    /*
     * Use a fourier series to model ground height. This isn't an ideal terrain
     * model, but is a lot better than using uncorrelated random points.
     */
    let distribution = Normal::new(0.0, 0.5);

    let make_fourier = || {
        let mut rng = thread_rng();
        let a0 = distribution.sample(&mut rng) as f32;
        let a1 = distribution.sample(&mut rng) as f32;
        let b1 = distribution.sample(&mut rng) as f32;
        let a2 = distribution.sample(&mut rng) as f32;
        let b2 = distribution.sample(&mut rng) as f32;
        let a3 = distribution.sample(&mut rng) as f32;
        let b3 = distribution.sample(&mut rng) as f32;
        let tau: f32 = 6.283185307179586 / 50f32;
        move |t: f32| {
            0.5*a0 + a1 * (tau * t).cos() + b1 * (tau * t).sin()
                + a2 * (2.0 * tau * t).cos() + b2 * (2.0 * tau * t).sin()
                + a3 * (3.0 * tau * t).cos() + b3 * (3.0 * tau * t).sin()
        }
    };
    let fourier_x = make_fourier();
    let fourier_y = make_fourier();

    /*
     * Setup a random ground.
     */
    let quad = ncollide3d::procedural::quad(20.0, 20.0, 100, 100);
    let indices = quad
        .flat_indices()
        .chunks(3)
        .map(|is| Point3::new(is[0] as usize, is[2] as usize, is[1] as usize))
        .collect();

    let mut vertices = quad.coords;

    // ncollide generatse a quad with `z` as the normal.
    // so we switch z and y here and set a random altitude at each point.
    for p in &mut vertices {
        p.z = p.y;
        p.y = fourier_x(p.x) + fourier_y(p.z);
    }

    let trimesh: TriMesh<f32> = TriMesh::new(vertices, indices, None);
    ColliderDesc::new(ShapeHandle::new(trimesh))
        .build(&mut world);

    /*
     * Create some boxes and spheres.
     */
    let num = 7;
    let rad = 0.1;
    let shift = rad * 2.0 + 0.5;
    let centerx = shift * (num as f32) / 2.0;
    let centery = shift / 2.0;
    let centerz = shift * (num as f32) / 2.0;
    let height = 1.0;

    let cuboid = ShapeHandle::new(Cuboid::new(Vector3::repeat(rad)));
    let collider_desc = ColliderDesc::new(cuboid)
        .density(1.0);

    let mut rb_desc = RigidBodyDesc::new()
        .collider(&collider_desc);

    for i in 0usize..num {
        for j in 0usize..num {
            for k in 0usize..num {
                let x = i as f32 * shift - centerx;
                let y = j as f32 * shift + centery + height;
                let z = k as f32 * shift - centerz;

                // Build the rigid body and its collider.
                rb_desc
                    .set_translation(Vector3::new(x, y, z))
                    .build(&mut world);
            }
        }
    }

    /*
     * Set up the testbed.
     */
    let testbed = Testbed::new(world);
    testbed.run();
}
<|endoftext|>


<commit_before>use error::Result;
use postgres::Connection;
use std::collections::BTreeMap;
use std::time::Duration;

#[derive(Debug, PartialEq)]
pub(crate) struct Limits {
    memory: usize,
    targets: usize,
    timeout: Duration,
    networking: bool,
    max_log_size: usize,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            memory: 3 * 1024 * 1024 * 1024,  // 3 GB
            timeout: Duration::from_secs(15 * 60),  // 15 minutes
            targets: 10,
            networking: false,
            max_log_size: 100 * 1024, // 100 KB
        }
    }
}

impl Limits {
    pub(crate) fn for_crate(conn: &Connection, name: &str) -> Result<Self> {
        let mut limits = Self::default();

        let res = conn.query(
            "SELECT * FROM sandbox_overrides WHERE crate_name = $1;",
            &[&name],
        )?;
        if !res.is_empty() {
            let row = res.get(0);
            if let Some(memory) = row.get::<_, Option<i64>>("max_memory_bytes") {
                limits.memory = memory as usize;
            }
            if let Some(timeout) = row.get::<_, Option<i32>>("timeout_seconds") {
                limits.timeout = Duration::from_secs(timeout as u64);
            }
            if let Some(targets) = row.get::<_, Option<i32>>("max_targets") {
                limits.targets = targets as usize;
            }
        }

        Ok(limits)
    }

    pub(crate) fn memory(&self) -> usize {
        self.memory
    }

    pub(crate) fn timeout(&self) -> Duration {
        self.timeout
    }

    pub(crate) fn networking(&self) -> bool {
        self.networking
    }

    pub(crate) fn max_log_size(&self) -> usize {
        self.max_log_size
    }

    pub(crate) fn targets(&self) -> usize {
        self.targets
    }

    pub(crate) fn for_website(&self) -> BTreeMap<String, String> {
        let time_scale = |v| scale(v, 60, &["seconds", "minutes", "hours"]);
        let size_scale = |v| scale(v, 1024, &["bytes", "KB", "MB", "GB"]);

        let mut res = BTreeMap::new();
        res.insert("Available RAM".into(), size_scale(self.memory));
        res.insert(
            "Maximum rustdoc execution time".into(),
            time_scale(self.timeout.as_secs() as usize),
        );
        res.insert("Maximum size of a build log".into(), size_scale(self.max_log_size));
        if self.networking {
            res.insert("Network access".into(), "allowed".into());
        } else {
            res.insert("Network access".into(), "blocked".into());
        }
        res.insert("Maximum number of build targets".into(), self.targets.to_string());
        res
    }
}

fn scale(mut value: usize, interval: usize, labels: &[&str]) -> String {
    let mut chosen_label = &labels[0];
    for label in &labels[1..] {
        if (value as f64) / (interval as f64) >= 1.0 {
            chosen_label = label;
            value = value / interval;
        } else {
            break;
        }
    }
    format!("{} {}", value, chosen_label)
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::test::*;
    #[test]
    fn retrieve_limits() {
        wrapper(|env| {
            let db = env.db();

            let krate = "hexponent";
            // limits work if no crate has limits set
            let hexponent = Limits::for_crate(&db.conn(), krate)?;
            assert_eq!(hexponent, Limits::default());

            db.conn().query("INSERT INTO sandbox_overrides (crate_name, max_targets) VALUES ($1, 15)", &[&krate])?;
            // limits work if crate has limits set
            let hexponent = Limits::for_crate(&db.conn(), krate)?;
            assert_eq!(hexponent, Limits { targets: 15, ..Limits::default() });

            // all limits work
            let krate = "regex";
            let limits = Limits {
                memory: 100_000,
                timeout: Duration::from_secs(300),
                targets: 1,
                ..Limits::default()
            };
            db.conn().query("INSERT INTO sandbox_overrides (crate_name, max_memory_bytes, timeout_seconds, max_targets)
                                    VALUES ($1, $2, $3, $4)",
                                    &[&krate, &(limits.memory as i64), &(limits.timeout.as_secs() as i32), &(limits.targets as i32)])?;
            assert_eq!(limits, Limits::for_crate(&db.conn(), krate)?);
            Ok(())
        });
    }
    #[test]
    fn display_limits() {
        let limits = Limits {
            memory: 102400,
            timeout: Duration::from_secs(300),
            targets: 1,
            ..Limits::default()
        };
        let display = limits.for_website();
        assert_eq!(display.get("Network access".into()), Some(&"blocked".into()));
        assert_eq!(display.get("Maximum size of a build log".into()), Some(&"100 KB".into()));
        assert_eq!(display.get("Maximum number of build targets".into()), Some(&limits.targets.to_string()));
        assert_eq!(display.get("Maximum rustdoc execution time".into()), Some(&"5 minutes".into()));
        assert_eq!(display.get("Available RAM".into()), Some(&"100 KB".into()));
    }
}
<commit_msg>Add test for `scale`<commit_after>use error::Result;
use postgres::Connection;
use std::collections::BTreeMap;
use std::time::Duration;

#[derive(Debug, PartialEq)]
pub(crate) struct Limits {
    memory: usize,
    targets: usize,
    timeout: Duration,
    networking: bool,
    max_log_size: usize,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            memory: 3 * 1024 * 1024 * 1024,  // 3 GB
            timeout: Duration::from_secs(15 * 60),  // 15 minutes
            targets: 10,
            networking: false,
            max_log_size: 100 * 1024, // 100 KB
        }
    }
}

impl Limits {
    pub(crate) fn for_crate(conn: &Connection, name: &str) -> Result<Self> {
        let mut limits = Self::default();

        let res = conn.query(
            "SELECT * FROM sandbox_overrides WHERE crate_name = $1;",
            &[&name],
        )?;
        if !res.is_empty() {
            let row = res.get(0);
            if let Some(memory) = row.get::<_, Option<i64>>("max_memory_bytes") {
                limits.memory = memory as usize;
            }
            if let Some(timeout) = row.get::<_, Option<i32>>("timeout_seconds") {
                limits.timeout = Duration::from_secs(timeout as u64);
            }
            if let Some(targets) = row.get::<_, Option<i32>>("max_targets") {
                limits.targets = targets as usize;
            }
        }

        Ok(limits)
    }

    pub(crate) fn memory(&self) -> usize {
        self.memory
    }

    pub(crate) fn timeout(&self) -> Duration {
        self.timeout
    }

    pub(crate) fn networking(&self) -> bool {
        self.networking
    }

    pub(crate) fn max_log_size(&self) -> usize {
        self.max_log_size
    }

    pub(crate) fn targets(&self) -> usize {
        self.targets
    }

    pub(crate) fn for_website(&self) -> BTreeMap<String, String> {

        let mut res = BTreeMap::new();
        res.insert("Available RAM".into(), SIZE_SCALE(self.memory));
        res.insert(
            "Maximum rustdoc execution time".into(),
            TIME_SCALE(self.timeout.as_secs() as usize),
        );
        res.insert("Maximum size of a build log".into(), SIZE_SCALE(self.max_log_size));
        if self.networking {
            res.insert("Network access".into(), "allowed".into());
        } else {
            res.insert("Network access".into(), "blocked".into());
        }
        res.insert("Maximum number of build targets".into(), self.targets.to_string());
        res
    }
}

const TIME_SCALE: fn(usize) -> String = |v| scale(v, 60, &["seconds", "minutes", "hours"]);
const SIZE_SCALE: fn(usize) -> String = |v| scale(v, 1024, &["bytes", "KB", "MB", "GB"]);

fn scale(value: usize, interval: usize, labels: &[&str]) -> String {
    let (mut value, interval) = (value as f64, interval as f64);
    let mut chosen_label = &labels[0];
    for label in &labels[1..] {
        if value / interval >= 1.0 {
            chosen_label = label;
            value = value / interval;
        } else {
            break;
        }
    }
    format!("{} {}", value.round() as usize, chosen_label)
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::test::*;
    #[test]
    fn retrieve_limits() {
        wrapper(|env| {
            let db = env.db();

            let krate = "hexponent";
            // limits work if no crate has limits set
            let hexponent = Limits::for_crate(&db.conn(), krate)?;
            assert_eq!(hexponent, Limits::default());

            db.conn().query("INSERT INTO sandbox_overrides (crate_name, max_targets) VALUES ($1, 15)", &[&krate])?;
            // limits work if crate has limits set
            let hexponent = Limits::for_crate(&db.conn(), krate)?;
            assert_eq!(hexponent, Limits { targets: 15, ..Limits::default() });

            // all limits work
            let krate = "regex";
            let limits = Limits {
                memory: 100_000,
                timeout: Duration::from_secs(300),
                targets: 1,
                ..Limits::default()
            };
            db.conn().query("INSERT INTO sandbox_overrides (crate_name, max_memory_bytes, timeout_seconds, max_targets)
                                    VALUES ($1, $2, $3, $4)",
                                    &[&krate, &(limits.memory as i64), &(limits.timeout.as_secs() as i32), &(limits.targets as i32)])?;
            assert_eq!(limits, Limits::for_crate(&db.conn(), krate)?);
            Ok(())
        });
    }
    #[test]
    fn display_limits() {
        let limits = Limits {
            memory: 102400,
            timeout: Duration::from_secs(300),
            targets: 1,
            ..Limits::default()
        };
        let display = limits.for_website();
        assert_eq!(display.get("Network access".into()), Some(&"blocked".into()));
        assert_eq!(display.get("Maximum size of a build log".into()), Some(&"100 KB".into()));
        assert_eq!(display.get("Maximum number of build targets".into()), Some(&limits.targets.to_string()));
        assert_eq!(display.get("Maximum rustdoc execution time".into()), Some(&"5 minutes".into()));
        assert_eq!(display.get("Available RAM".into()), Some(&"100 KB".into()));
    }
    #[test]
    fn scale_limits() {
        // time
        assert_eq!(TIME_SCALE(300), "5 minutes");
        assert_eq!(TIME_SCALE(1), "1 seconds");
        assert_eq!(TIME_SCALE(7200), "2 hours");

        // size
        assert_eq!(SIZE_SCALE(1), "1 bytes");
        assert_eq!(SIZE_SCALE(100), "100 bytes");
        assert_eq!(SIZE_SCALE(1024), "1 KB");
        assert_eq!(SIZE_SCALE(10240), "10 KB");
        assert_eq!(SIZE_SCALE(1048576), "1 MB");
        assert_eq!(SIZE_SCALE(10485760), "10 MB");
        assert_eq!(SIZE_SCALE(1073741824), "1 GB");
        assert_eq!(SIZE_SCALE(10737418240), "10 GB");
        assert_eq!(SIZE_SCALE(std::u32::MAX as usize), "4 GB");
    }
}
<|endoftext|>


<commit_before>use buf::{Buf, MutBuf};
use std::os::unix::io::{Fd, AsRawFd};

// Re-export the io::Result / Error types for convenience
pub use std::io::{Read, Write, Result, Error};

/// A value that may be registered with an `EventLoop`
pub trait Evented : AsRawFd {
}

/// Create a value with a FD
pub trait FromFd {
    fn from_fd(fd: Fd) -> Self;
}

pub trait TryRead {
    fn read<B: MutBuf>(&mut self, buf: &mut B) -> Result<Option<usize>> {
        // Reads the length of the slice supplied by buf.mut_bytes into the buffer
        // This is not guaranteed to consume an entire datagram or segment.
        // If your protocol is msg based (instead of continuous stream) you should
        // ensure that your buffer is large enough to hold an entire segment (1532 bytes if not jumbo
        // frames)
        let res = self.read_slice(buf.mut_bytes());

        if let Ok(Some(cnt)) = res {
            buf.advance(cnt);
        }

        res
    }

    fn read_slice(&mut self, buf: &mut [u8]) -> Result<Option<usize>>;
}

pub trait TryWrite {
    fn write<B: Buf>(&mut self, buf: &mut B) -> Result<Option<usize>> {
        let res = self.write_slice(buf.bytes());

        if let Ok(Some(cnt)) = res {
            buf.advance(cnt);
        }

        res
    }

    fn write_slice(&mut self, buf: &[u8]) -> Result<Option<usize>>;
}

/*
 *
 * ===== Basic IO type =====
 *
 */

#[derive(Debug)]
pub struct Io {
    fd: Fd,
}

impl Io {
    pub fn new(fd: Fd) -> Io {
        Io { fd: fd }
    }
}

impl AsRawFd for Io {
    fn as_raw_fd(&self) -> Fd {
        self.fd
    }
}

impl Evented for Io {
}

impl TryRead for Io {
    fn read_slice(&mut self, dst: &mut [u8]) -> Result<Option<usize>> {
        use nix::unistd::read;

        read(self.as_raw_fd(), dst)
            .map(|cnt| Some(cnt))
            .map_err(from_nix_error)
            .or_else(to_non_block)
    }
}

impl TryWrite for Io {
    fn write_slice(&mut self, src: &[u8]) -> Result<Option<usize>> {
        use nix::unistd::write;

        write(self.as_raw_fd(), src)
            .map_err(from_nix_error)
            .map(|cnt| Some(cnt))
            .or_else(to_non_block)
    }
}

impl Drop for Io {
    fn drop(&mut self) {
        use nix::unistd::close;
        let _ = close(self.as_raw_fd());
    }
}

/*
 *
 * ===== Pipe =====
 *
 */

pub fn pipe() -> Result<(PipeReader, PipeWriter)> {
    use nix::fcntl::{O_NONBLOCK, O_CLOEXEC};
    use nix::unistd::pipe2;

    let (rd, wr) = try!(pipe2(O_NONBLOCK | O_CLOEXEC)
        .map_err(from_nix_error));

    let rd = FromFd::from_fd(rd);
    let wr = FromFd::from_fd(wr);

    Ok((rd, wr))
}

pub struct PipeReader {
    io: Io,
}

impl FromFd for PipeReader {
    fn from_fd(fd: Fd) -> PipeReader {
        PipeReader { io: Io::new(fd) }
    }
}

impl AsRawFd for PipeReader {
    fn as_raw_fd(&self) -> Fd {
        self.io.as_raw_fd()
    }
}

impl Evented for PipeReader {
}

impl TryRead for PipeReader {
    fn read_slice(&mut self, buf: &mut [u8]) -> Result<Option<usize>> {
        self.io.read_slice(buf)
    }
}
pub struct PipeWriter {
    io: Io,
}

impl FromFd for PipeWriter {
    fn from_fd(fd: Fd) -> PipeWriter {
        PipeWriter { io: Io::new(fd) }
    }
}

impl AsRawFd for PipeWriter {
    fn as_raw_fd(&self) -> Fd {
        self.io.fd
    }
}

impl Evented for PipeWriter {
}

impl TryWrite for PipeWriter {
    fn write_slice(&mut self, buf: &[u8]) -> Result<Option<usize>> {
        self.io.write_slice(buf)
    }
}

/*
 *
 * ===== Helpers =====
 *
 */

pub fn from_nix_error(err: ::nix::NixError) -> Error {
    use nix::{errno, NixError};

    match err {
        NixError::Sys(errno) => Error::from_os_error(errno as i32),
        _ => Error::from_os_error(errno::EINVAL as i32)
    }
}

pub fn to_non_block<T>(err: Error) -> Result<Option<T>> {
    use std::io::ErrorKind::ResourceUnavailable;

    if let ResourceUnavailable = err.kind() {
        return Ok(None);
    }

    Err(err)
}
<commit_msg>Track std::io.. ResourceUnavailable -> WouldBlock .<commit_after>use buf::{Buf, MutBuf};
use std::os::unix::io::{Fd, AsRawFd};

// Re-export the io::Result / Error types for convenience
pub use std::io::{Read, Write, Result, Error};

/// A value that may be registered with an `EventLoop`
pub trait Evented : AsRawFd {
}

/// Create a value with a FD
pub trait FromFd {
    fn from_fd(fd: Fd) -> Self;
}

pub trait TryRead {
    fn read<B: MutBuf>(&mut self, buf: &mut B) -> Result<Option<usize>> {
        // Reads the length of the slice supplied by buf.mut_bytes into the buffer
        // This is not guaranteed to consume an entire datagram or segment.
        // If your protocol is msg based (instead of continuous stream) you should
        // ensure that your buffer is large enough to hold an entire segment (1532 bytes if not jumbo
        // frames)
        let res = self.read_slice(buf.mut_bytes());

        if let Ok(Some(cnt)) = res {
            buf.advance(cnt);
        }

        res
    }

    fn read_slice(&mut self, buf: &mut [u8]) -> Result<Option<usize>>;
}

pub trait TryWrite {
    fn write<B: Buf>(&mut self, buf: &mut B) -> Result<Option<usize>> {
        let res = self.write_slice(buf.bytes());

        if let Ok(Some(cnt)) = res {
            buf.advance(cnt);
        }

        res
    }

    fn write_slice(&mut self, buf: &[u8]) -> Result<Option<usize>>;
}

/*
 *
 * ===== Basic IO type =====
 *
 */

#[derive(Debug)]
pub struct Io {
    fd: Fd,
}

impl Io {
    pub fn new(fd: Fd) -> Io {
        Io { fd: fd }
    }
}

impl AsRawFd for Io {
    fn as_raw_fd(&self) -> Fd {
        self.fd
    }
}

impl Evented for Io {
}

impl TryRead for Io {
    fn read_slice(&mut self, dst: &mut [u8]) -> Result<Option<usize>> {
        use nix::unistd::read;

        read(self.as_raw_fd(), dst)
            .map(|cnt| Some(cnt))
            .map_err(from_nix_error)
            .or_else(to_non_block)
    }
}

impl TryWrite for Io {
    fn write_slice(&mut self, src: &[u8]) -> Result<Option<usize>> {
        use nix::unistd::write;

        write(self.as_raw_fd(), src)
            .map_err(from_nix_error)
            .map(|cnt| Some(cnt))
            .or_else(to_non_block)
    }
}

impl Drop for Io {
    fn drop(&mut self) {
        use nix::unistd::close;
        let _ = close(self.as_raw_fd());
    }
}

/*
 *
 * ===== Pipe =====
 *
 */

pub fn pipe() -> Result<(PipeReader, PipeWriter)> {
    use nix::fcntl::{O_NONBLOCK, O_CLOEXEC};
    use nix::unistd::pipe2;

    let (rd, wr) = try!(pipe2(O_NONBLOCK | O_CLOEXEC)
        .map_err(from_nix_error));

    let rd = FromFd::from_fd(rd);
    let wr = FromFd::from_fd(wr);

    Ok((rd, wr))
}

pub struct PipeReader {
    io: Io,
}

impl FromFd for PipeReader {
    fn from_fd(fd: Fd) -> PipeReader {
        PipeReader { io: Io::new(fd) }
    }
}

impl AsRawFd for PipeReader {
    fn as_raw_fd(&self) -> Fd {
        self.io.as_raw_fd()
    }
}

impl Evented for PipeReader {
}

impl TryRead for PipeReader {
    fn read_slice(&mut self, buf: &mut [u8]) -> Result<Option<usize>> {
        self.io.read_slice(buf)
    }
}
pub struct PipeWriter {
    io: Io,
}

impl FromFd for PipeWriter {
    fn from_fd(fd: Fd) -> PipeWriter {
        PipeWriter { io: Io::new(fd) }
    }
}

impl AsRawFd for PipeWriter {
    fn as_raw_fd(&self) -> Fd {
        self.io.fd
    }
}

impl Evented for PipeWriter {
}

impl TryWrite for PipeWriter {
    fn write_slice(&mut self, buf: &[u8]) -> Result<Option<usize>> {
        self.io.write_slice(buf)
    }
}

/*
 *
 * ===== Helpers =====
 *
 */

pub fn from_nix_error(err: ::nix::NixError) -> Error {
    use nix::{errno, NixError};

    match err {
        NixError::Sys(errno) => Error::from_os_error(errno as i32),
        _ => Error::from_os_error(errno::EINVAL as i32)
    }
}

pub fn to_non_block<T>(err: Error) -> Result<Option<T>> {
    use std::io::ErrorKind::WouldBlock;

    if let WouldBlock = err.kind() {
        return Ok(None);
    }

    Err(err)
}
<|endoftext|>


<commit_before>use std::{io, path};
use std::rand;
use std::rand::Rng;

fn load(filename: ~str) -> ~[~str] {
	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(filename));

	if read.is_ok() {
	let file = read.unwrap();
	return file.read_lines();
	}

	println(fmt!("Error in reading the file: %?", read.unwrap_err()));
	return ~[];
}

fn main() {
        let mut rng = rand::task_rng();
	let dictionary: ~[~str] = load(~"words.txt");
	let max_size: uint = dictionary.len();
        let n: uint = rng.gen_integer_range(0u, max_size);
	let word: ~str = dictionary[n];
	let word_len: uint = word.char_len();

	let mut i = 0;
	while (i < word_len) {
        	print("_ ");
		i += 1;
        }
        println("");

	let mut j = 0;
        let max_guess : uint = 8;
	while (j < max_guess){

		let line = io::stdin().read_line();
		let guess_char: char = line.char_at(0);
		println(fmt!("%? guessed: ", guess_char));
		let has_char: bool = word.contains_char(guess_char);

		if (has_char){
       			let mut i = 0;
			while (i < word_len) {
				if(word.char_at(i) != guess_char){
        	 			print("_ ");
                		}else{
		 			print(fmt!("%c", guess_char));
		 			print(" ");
				}
				i += 1;
       			 }
			println("");
		}
		else{
			println("nope.");
			j += 1;
		}
	}

}
<commit_msg>Char array<commit_after>use std::{io, path};
use std::rand;
use std::rand::Rng;

fn load(filename: ~str) -> ~[~str] {
	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(filename));

	if read.is_ok() {
	let file = read.unwrap();
	return file.read_lines();
	}

	println(fmt!("Error in reading the file: %?", read.unwrap_err()));
	return ~[];
}

fn isDuplicate(guess: char) -> bool{
	for uint::range(0,guesses.length()) |b|{
		let ch = copy(guesses[b]);
		match ch {
			guess => {return true;}
			_ => {}
		}
	}
	return false;
}

//fn searchChar(guess: char) -> bool{

//}

fn main() {
        let mut rng = rand::task_rng();
	let dictionary: ~[~str] = load(~"words.txt");
	let max_size: uint = dictionary.len();
        let n: uint = rng.gen_integer_range(0u, max_size);
	let word: ~str = dictionary[n];
	let word_len: uint = word.char_len();

	//Stores the guessed word
	let mut i = 0;
	//let mut guessedWord: ~[~str] = ~[~""];
	let mut guessedWord: ~[char] = ~[];
	while (i < word_len) {
        	guessedWord = guessedWord + ~['_'];
		i += 1;
        }
        println(guessedWord.to_str());
	println(word);

	let mut guesses: ~[char] = ~[];

	let mut j = 0;
        let max_guess : uint = 8;
	while (j < max_guess){

		let line = io::stdin().read_line();
		let guess_char: char = line.char_at(0);
		println(fmt!("%? guessed: ", guess_char));
		guesses = guesses + ~['a', 'b'];
		println(isDuplicate(guess_char).to_str());
		let has_char: bool = word.contains_char(guess_char);

		if (has_char){
       			let mut i = 0;
			while (i < word_len) {
				if(word.char_at(i) != guess_char){
        	 			print("_ ");
                		}else{
		 			print(fmt!("%c", guess_char));
		 			print(" ");
				}
				i += 1;
       			 }
			println("");
		}
		else{
			println("nope.");
			j += 1;
		}
	}

}
<|endoftext|>


<commit_before>#![feature(const_generics)]
#![allow(incomplete_features)]
struct Arr<const N: usize>
where Assert::<{N < usize::max_value() / 2}>: IsTrue, //~ ERROR constant expression depends on a generic parameter
{
}

enum Assert<const CHECK: bool> {}

trait IsTrue {}

impl IsTrue for Assert<true> {}

fn main() {
    let x: Arr<{usize::max_value()}> = Arr {};
}
<commit_msg>fixup! Add regression test for const generic ICE in #72819<commit_after>#![feature(const_generics)]
#![allow(incomplete_features)]
struct Arr<const N: usize>
where Assert::<{N < usize::max_value() / 2}>: IsTrue,
//~^ ERROR constant expression depends on a generic parameter
{
}

enum Assert<const CHECK: bool> {}

trait IsTrue {}

impl IsTrue for Assert<true> {}

fn main() {
    let x: Arr<{usize::max_value()}> = Arr {};
}
<|endoftext|>


<commit_before>// This file is part of rss.
//
// Copyright © 2015-2017 The rust-syndication Developers
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the MIT License and/or Apache 2.0 License.

use std::collections::HashSet;
use std::error::Error as StdError;
use std::fmt;
use std::num::ParseIntError;

use chrono::DateTime;
use chrono::ParseError as DateParseError;
use mime::Mime;
use mime::FromStrError as MimeParseError;
use url::ParseError as UrlParseError;
use url::Url;

use {Category, Channel, Cloud, Enclosure, Image, Item, Source, TextInput};

#[derive(Debug)]
/// Errors that occur during validation.
pub enum ValidationError {
    /// An error while parsing a string to a date.
    DateParsing(DateParseError),
    /// An error while parsing a string to an integer.
    IntParsing(ParseIntError),
    /// An error while parsing a string to a URL.
    UrlParsing(UrlParseError),
    /// An error while parsing a string to a MIME type.
    MimeParsing(MimeParseError),
    /// A different validation error.
    Validation(String),
}

impl StdError for ValidationError {
    fn description(&self) -> &str {
        match *self {
            ValidationError::DateParsing(ref err) => err.description(),
            ValidationError::IntParsing(ref err) => err.description(),
            ValidationError::UrlParsing(ref err) => err.description(),
            ValidationError::MimeParsing(_) => "Unable to parse MIME type",
            ValidationError::Validation(ref s) => s.as_str(),
        }
    }

    fn cause(&self) -> Option<&StdError> {
        match *self {
            ValidationError::DateParsing(ref err) => Some(err),
            ValidationError::IntParsing(ref err) => Some(err),
            ValidationError::UrlParsing(ref err) => Some(err),
            _ => None,
        }
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ValidationError::DateParsing(ref err) => err.fmt(f),
            ValidationError::IntParsing(ref err) => err.fmt(f),
            ValidationError::UrlParsing(ref err) => err.fmt(f),
            ValidationError::MimeParsing(_) => write!(f, "Unable to parse MIME type"),
            ValidationError::Validation(ref s) => write!(f, "{}", s),
        }
    }
}

impl From<DateParseError> for ValidationError {
    fn from(err: DateParseError) -> Self {
        ValidationError::DateParsing(err)
    }
}

impl From<ParseIntError> for ValidationError {
    fn from(err: ParseIntError) -> Self {
        ValidationError::IntParsing(err)
    }
}

impl From<UrlParseError> for ValidationError {
    fn from(err: UrlParseError) -> Self {
        ValidationError::UrlParsing(err)
    }
}

impl From<MimeParseError> for ValidationError {
    fn from(err: MimeParseError) -> Self {
        ValidationError::MimeParsing(err)
    }
}

/// A trait to support data validation.
pub trait Validate {
    /// Validate the data against the RSS specification.
    fn validate(&self) -> Result<(), ValidationError>;
}

macro_rules! validate {
    ($e:expr, $msg:expr) => ({
        if !($e) {
            return Err(ValidationError::Validation(String::from($msg)));
        }
    })
}

impl Validate for Channel {
    fn validate(&self) -> Result<(), ValidationError> {
        Url::parse(self.link())?;

        for category in self.categories() {
            category.validate()?;
        }

        if let Some(cloud) = self.cloud() {
            cloud.validate()?;
        }

        if let Some(docs) = self.docs() {
            Url::parse(docs)?;
        }

        if let Some(image) = self.image() {
            image.validate()?;
        }

        for item in self.items() {
            item.validate()?;
        }

        if let Some(last_build_date) = self.last_build_date() {
            DateTime::parse_from_rfc2822(last_build_date)?;
        }

        if let Some(pub_date) = self.pub_date() {
            DateTime::parse_from_rfc2822(pub_date)?;
        }

        for hour in self.skip_hours() {
            let hour = hour.parse::<i64>()?;
            validate!(
                hour >= 0 && hour <= 23,
                "Channel skip hour is not between 0 and 23"
            );
        }

        let valid_days = {
            let mut set = HashSet::with_capacity(7);
            set.insert("Monday");
            set.insert("Tuesday");
            set.insert("Wednesday");
            set.insert("Thursday");
            set.insert("Friday");
            set.insert("Saturday");
            set.insert("Sunday");
            set
        };

        for day in self.skip_days() {
            validate!(
                valid_days.contains(day.as_str()),
                format!("Unknown skip day: {}", day)
            );
        }

        if let Some(text_input) = self.text_input() {
            text_input.validate()?;
        }

        if let Some(ttl) = self.ttl() {
            let ttl = ttl.parse::<i64>()?;
            validate!(ttl > 0, "Channel TTL is not greather than 0");
        }

        Ok(())
    }
}

impl Validate for Category {
    fn validate(&self) -> Result<(), ValidationError> {
        if let Some(domain) = self.domain() {
            Url::parse(domain)?;
        }
        Ok(())
    }
}

impl Validate for Cloud {
    fn validate(&self) -> Result<(), ValidationError> {
        let port = self.port().parse::<i64>()?;
        validate!(port > 0, "Cloud port must be greather than 0");
        Url::parse(self.domain())?;
        validate!(
            vec!["xml-rpc", "soap", "http-post"].contains(self.protocol()),
            format!("Unknown cloud protocol: {}", self.protocol())
        );
        Ok(())
    }
}

impl Validate for Enclosure {
    fn validate(&self) -> Result<(), ValidationError> {
        Url::parse(self.url())?;
        self.mime_type().parse::<Mime>()?;
        let length = self.length().parse::<i64>()?;
        validate!(length > 0, "Enclosure length is not greather than 0");
        Ok(())
    }
}

impl Validate for TextInput {
    fn validate(&self) -> Result<(), ValidationError> {
        Url::parse(self.link())?;
        Ok(())
    }
}

impl Validate for Image {
    fn validate(&self) -> Result<(), ValidationError> {
        Url::parse(self.link())?;
        Url::parse(self.url())?;

        if let Some(width) = self.width() {
            let width = width.parse::<i64>()?;
            validate!(
                width >= 0 && width <= 144,
                "Image width is not between 0 and 144"
            );
        }

        if let Some(height) = self.height() {
            let height = height.parse::<i64>()?;
            validate!(
                height >= 0 && height <= 144,
                "Image height is not between 0 and 144"
            );
        }

        Ok(())
    }
}

impl Validate for Item {
    fn validate(&self) -> Result<(), ValidationError> {
        if let Some(link) = self.link() {
            Url::parse(link)?;
        }

        if let Some(comments) = self.comments() {
            Url::parse(comments)?;
        }

        if let Some(enclosure) = self.enclosure() {
            enclosure.validate()?;
        }

        if let Some(pub_date) = self.pub_date() {
            DateTime::parse_from_rfc2822(pub_date)?;
        }

        if let Some(source) = self.source() {
            source.validate()?;
        }

        Ok(())
    }
}

impl Validate for Source {
    fn validate(&self) -> Result<(), ValidationError> {
        Url::parse(self.url())?;
        Ok(())
    }
}
<commit_msg>Fix a failing test.<commit_after>// This file is part of rss.
//
// Copyright © 2015-2017 The rust-syndication Developers
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the MIT License and/or Apache 2.0 License.

use std::collections::HashSet;
use std::error::Error as StdError;
use std::fmt;
use std::num::ParseIntError;

use chrono::DateTime;
use chrono::ParseError as DateParseError;
use mime::Mime;
use mime::FromStrError as MimeParseError;
use url::ParseError as UrlParseError;
use url::Url;

use {Category, Channel, Cloud, Enclosure, Image, Item, Source, TextInput};

#[derive(Debug)]
/// Errors that occur during validation.
pub enum ValidationError {
    /// An error while parsing a string to a date.
    DateParsing(DateParseError),
    /// An error while parsing a string to an integer.
    IntParsing(ParseIntError),
    /// An error while parsing a string to a URL.
    UrlParsing(UrlParseError),
    /// An error while parsing a string to a MIME type.
    MimeParsing(MimeParseError),
    /// A different validation error.
    Validation(String),
}

impl StdError for ValidationError {
    fn description(&self) -> &str {
        match *self {
            ValidationError::DateParsing(ref err) => err.description(),
            ValidationError::IntParsing(ref err) => err.description(),
            ValidationError::UrlParsing(ref err) => err.description(),
            ValidationError::MimeParsing(_) => "Unable to parse MIME type",
            ValidationError::Validation(ref s) => s.as_str(),
        }
    }

    fn cause(&self) -> Option<&StdError> {
        match *self {
            ValidationError::DateParsing(ref err) => Some(err),
            ValidationError::IntParsing(ref err) => Some(err),
            ValidationError::UrlParsing(ref err) => Some(err),
            _ => None,
        }
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ValidationError::DateParsing(ref err) => err.fmt(f),
            ValidationError::IntParsing(ref err) => err.fmt(f),
            ValidationError::UrlParsing(ref err) => err.fmt(f),
            ValidationError::MimeParsing(_) => write!(f, "Unable to parse MIME type"),
            ValidationError::Validation(ref s) => write!(f, "{}", s),
        }
    }
}

impl From<DateParseError> for ValidationError {
    fn from(err: DateParseError) -> Self {
        ValidationError::DateParsing(err)
    }
}

impl From<ParseIntError> for ValidationError {
    fn from(err: ParseIntError) -> Self {
        ValidationError::IntParsing(err)
    }
}

impl From<UrlParseError> for ValidationError {
    fn from(err: UrlParseError) -> Self {
        ValidationError::UrlParsing(err)
    }
}

impl From<MimeParseError> for ValidationError {
    fn from(err: MimeParseError) -> Self {
        ValidationError::MimeParsing(err)
    }
}

/// A trait to support data validation.
pub trait Validate {
    /// Validate the data against the RSS specification.
    fn validate(&self) -> Result<(), ValidationError>;
}

macro_rules! validate {
    ($e:expr, $msg:expr) => ({
        if !($e) {
            return Err(ValidationError::Validation(String::from($msg)));
        }
    })
}

impl Validate for Channel {
    fn validate(&self) -> Result<(), ValidationError> {
        Url::parse(self.link())?;

        for category in self.categories() {
            category.validate()?;
        }

        if let Some(cloud) = self.cloud() {
            cloud.validate()?;
        }

        if let Some(docs) = self.docs() {
            Url::parse(docs)?;
        }

        if let Some(image) = self.image() {
            image.validate()?;
        }

        for item in self.items() {
            item.validate()?;
        }

        if let Some(last_build_date) = self.last_build_date() {
            DateTime::parse_from_rfc2822(last_build_date)?;
        }

        if let Some(pub_date) = self.pub_date() {
            DateTime::parse_from_rfc2822(pub_date)?;
        }

        for hour in self.skip_hours() {
            let hour = hour.parse::<i64>()?;
            validate!(
                hour >= 0 && hour <= 23,
                "Channel skip hour is not between 0 and 23"
            );
        }

        let valid_days = {
            let mut set = HashSet::with_capacity(7);
            set.insert("Monday");
            set.insert("Tuesday");
            set.insert("Wednesday");
            set.insert("Thursday");
            set.insert("Friday");
            set.insert("Saturday");
            set.insert("Sunday");
            set
        };

        for day in self.skip_days() {
            validate!(
                valid_days.contains(day.as_str()),
                format!("Unknown skip day: {}", day)
            );
        }

        if let Some(text_input) = self.text_input() {
            text_input.validate()?;
        }

        if let Some(ttl) = self.ttl() {
            let ttl = ttl.parse::<i64>()?;
            validate!(ttl > 0, "Channel TTL is not greather than 0");
        }

        Ok(())
    }
}

impl Validate for Category {
    fn validate(&self) -> Result<(), ValidationError> {
        if let Some(domain) = self.domain() {
            Url::parse(domain)?;
        }
        Ok(())
    }
}

impl Validate for Cloud {
    fn validate(&self) -> Result<(), ValidationError> {
        let port = self.port().parse::<i64>()?;
        validate!(port > 0, "Cloud port must be greather than 0");
        Url::parse(self.domain())?;
        validate!(
            vec!["xml-rpc", "soap", "http-post"].contains(&self.protocol()),
            format!("Unknown cloud protocol: {}", self.protocol())
        );
        Ok(())
    }
}

impl Validate for Enclosure {
    fn validate(&self) -> Result<(), ValidationError> {
        Url::parse(self.url())?;
        self.mime_type().parse::<Mime>()?;
        let length = self.length().parse::<i64>()?;
        validate!(length > 0, "Enclosure length is not greather than 0");
        Ok(())
    }
}

impl Validate for TextInput {
    fn validate(&self) -> Result<(), ValidationError> {
        Url::parse(self.link())?;
        Ok(())
    }
}

impl Validate for Image {
    fn validate(&self) -> Result<(), ValidationError> {
        Url::parse(self.link())?;
        Url::parse(self.url())?;

        if let Some(width) = self.width() {
            let width = width.parse::<i64>()?;
            validate!(
                width >= 0 && width <= 144,
                "Image width is not between 0 and 144"
            );
        }

        if let Some(height) = self.height() {
            let height = height.parse::<i64>()?;
            validate!(
                height >= 0 && height <= 144,
                "Image height is not between 0 and 144"
            );
        }

        Ok(())
    }
}

impl Validate for Item {
    fn validate(&self) -> Result<(), ValidationError> {
        if let Some(link) = self.link() {
            Url::parse(link)?;
        }

        if let Some(comments) = self.comments() {
            Url::parse(comments)?;
        }

        if let Some(enclosure) = self.enclosure() {
            enclosure.validate()?;
        }

        if let Some(pub_date) = self.pub_date() {
            DateTime::parse_from_rfc2822(pub_date)?;
        }

        if let Some(source) = self.source() {
            source.validate()?;
        }

        Ok(())
    }
}

impl Validate for Source {
    fn validate(&self) -> Result<(), ValidationError> {
        Url::parse(self.url())?;
        Ok(())
    }
}
<|endoftext|>


<commit_before>use std::io::File;
use std::io::{Reader, Writer, Seek, SeekSet, SeekEnd};
use std::io::{IoResult, IoError, InvalidInput};
use std::iter;
use std::iter::range_inclusive;
use std::path::BytesContainer;
use error;
use error::ZipError;
use maybe_utf8::MaybeUTF8;
use flate;
use crc32;
use format;
use fileinfo;
use fileinfo::{CompressionMethod, FileInfo};

pub struct ZipReader<R> {
    reader: R,
    end_record: format::EndOfCentralDirectoryRecord,
}

pub struct Files<'a, R:'a> {
    zip_reader: &'a mut ZipReader<R>,
    current_entry: u16,
    current_offset: u64,
}

impl<'a, R:Reader+Seek> Iterator<Result<FileInfo, ZipError>> for Files<'a, R> {
    fn next(&mut self) -> Option<Result<FileInfo, ZipError>> {
        if self.current_entry < self.zip_reader.end_record.total_entry_count {
            match self.zip_reader.reader.seek(self.current_offset as i64, SeekSet) {
                Ok(()) => {}
                Err(err) => { return Some(Err(error::SomeIoError(err))); }
            }
            let h = match format::CentralDirectoryHeader::read(&mut self.zip_reader.reader) {
                Ok(h) => h,
                Err(err) => { return Some(Err(err)); }
            };
            let info = FileInfo::from_cdh(&h);
            self.current_entry += 1;
            self.current_offset += h.total_size() as u64;
            Some(Ok(info))
        } else {
            None
        }
    }
}

impl ZipReader<File> {
    pub fn open(path: &Path) -> Result<ZipReader<File>, ZipError> {
        ZipReader::new(try_io!(File::open(path)))
    }
}

impl<R:Reader+Seek> ZipReader<R> {
    pub fn new(reader: R) -> Result<ZipReader<R>, ZipError> {
        // find the End of Central Directory record, looking backwards from the end of the file
        let mut r = reader;
        try_io!(r.seek(0, SeekEnd));
        let file_size = try_io!(r.tell());
        let mut end_record_offset : Option<u64> = None;
        for i in range_inclusive(4, file_size) {
            let offset = file_size - i;
            try_io!(r.seek(offset as i64, SeekSet));

            let sig = try_io!(r.read_le_u32());

            // TODO: check for false positives here
            if sig == format::EOCDR_SIGNATURE {
                end_record_offset = Some(offset);
                break;
            }

        }

        match end_record_offset {
            Some(offset) => {
                try_io!(r.seek(offset as i64, SeekSet));
                let e = try!(format::EndOfCentralDirectoryRecord::read(&mut r));
                Ok(ZipReader {reader: r, end_record: e})
            },
            None => Err(error::NotAZipFile)
        }
    }

    pub fn files_raw<'a>(&'a mut self) -> Files<'a, R> {
        let cdr_offset = self.end_record.central_directory_offset;
        Files {
            zip_reader: self,
            current_entry: 0,
            current_offset: cdr_offset as u64
        }
    }

    pub fn files<'a>(&'a mut self) -> iter::Map<Result<FileInfo, ZipError>, FileInfo,
                                                Files<'a, R>> {
        self.files_raw().map(|fileinfo_or_err| fileinfo_or_err.unwrap())
    }

    pub fn file_names<'a>(&'a mut self) -> iter::Map<Result<FileInfo, ZipError>, MaybeUTF8,
                                                     Files<'a, R>> {
        self.files_raw().map(|fileinfo_or_err| fileinfo_or_err.unwrap().name)
    }

    pub fn info<T:BytesContainer>(&mut self, name: T) -> Result<FileInfo, ZipError> {
        for i in self.files() {
            if i.name.equiv(&name) {
                return Ok(i);
            }
        }
        Err(error::FileNotFoundInArchive)
    }

    // TODO: Create a Reader for the cases when you don't want to decompress the whole file
    pub fn read(&mut self, f: &FileInfo) -> Result<Vec<u8>, ZipError> {
        try_io!(self.reader.seek(f.local_file_header_offset as i64, SeekSet));
        let h = try!(format::LocalFileHeader::read(&mut self.reader));
        let file_offset = f.local_file_header_offset as i64 + h.total_size() as i64;

        let result =
            match CompressionMethod::from_u16(h.compression_method) {
                fileinfo::Store => self.read_stored_file(file_offset, h.uncompressed_size),
                fileinfo::Deflate => self.read_deflated_file(file_offset, h.compressed_size, h.uncompressed_size),
                _ => fail!()
            };
        let result = try_io!(result);

        // Check the CRC32 of the result against the one stored in the header
        let crc = crc32::crc32(result.as_slice());

        if crc == h.crc32 { Ok(result) }
        else { Err(error::CrcError) }
    }

    fn read_stored_file(&mut self, pos: i64, uncompressed_size: u32) -> IoResult<Vec<u8>> {
        try!(self.reader.seek(pos, SeekSet));
        self.reader.read_exact(uncompressed_size as uint)
    }

    fn read_deflated_file(&mut self, pos: i64, compressed_size: u32, uncompressed_size: u32) -> IoResult<Vec<u8>> {
        try!(self.reader.seek(pos, SeekSet));
        let compressed_bytes = try!(self.reader.read_exact(compressed_size as uint));
        let uncompressed_bytes = match flate::inflate_bytes(compressed_bytes.as_slice()) {
            Some(bytes) => bytes,
            None => return Err(IoError { kind: InvalidInput, desc: "decompression failure", detail: None })
        };
        assert!(uncompressed_bytes.len() as u32 == uncompressed_size);
        // FIXME try not to copy the buffer, or switch to the incremental fashion
        Ok(Vec::from_slice(uncompressed_bytes.as_slice()))
    }

    // when we make read return a Reader, we will be able to loop here and copy
    // blocks of a fixed size from Reader to Writer
    pub fn extract<T:Writer>(&mut self, f: &FileInfo, writer: &mut T) -> Result<(), ZipError> {
        match self.read(f) {
            Ok(bytes) => { try_io!(writer.write(bytes.as_slice())); Ok(()) },
            Err(x) => Err(x)
        }
    }

}

<commit_msg>language changes: Vec::from_silce -> .to_vec<commit_after>use std::io::File;
use std::io::{Reader, Writer, Seek, SeekSet, SeekEnd};
use std::io::{IoResult, IoError, InvalidInput};
use std::iter;
use std::iter::range_inclusive;
use std::path::BytesContainer;
use error;
use error::ZipError;
use maybe_utf8::MaybeUTF8;
use flate;
use crc32;
use format;
use fileinfo;
use fileinfo::{CompressionMethod, FileInfo};

pub struct ZipReader<R> {
    reader: R,
    end_record: format::EndOfCentralDirectoryRecord,
}

pub struct Files<'a, R:'a> {
    zip_reader: &'a mut ZipReader<R>,
    current_entry: u16,
    current_offset: u64,
}

impl<'a, R:Reader+Seek> Iterator<Result<FileInfo, ZipError>> for Files<'a, R> {
    fn next(&mut self) -> Option<Result<FileInfo, ZipError>> {
        if self.current_entry < self.zip_reader.end_record.total_entry_count {
            match self.zip_reader.reader.seek(self.current_offset as i64, SeekSet) {
                Ok(()) => {}
                Err(err) => { return Some(Err(error::SomeIoError(err))); }
            }
            let h = match format::CentralDirectoryHeader::read(&mut self.zip_reader.reader) {
                Ok(h) => h,
                Err(err) => { return Some(Err(err)); }
            };
            let info = FileInfo::from_cdh(&h);
            self.current_entry += 1;
            self.current_offset += h.total_size() as u64;
            Some(Ok(info))
        } else {
            None
        }
    }
}

impl ZipReader<File> {
    pub fn open(path: &Path) -> Result<ZipReader<File>, ZipError> {
        ZipReader::new(try_io!(File::open(path)))
    }
}

impl<R:Reader+Seek> ZipReader<R> {
    pub fn new(reader: R) -> Result<ZipReader<R>, ZipError> {
        // find the End of Central Directory record, looking backwards from the end of the file
        let mut r = reader;
        try_io!(r.seek(0, SeekEnd));
        let file_size = try_io!(r.tell());
        let mut end_record_offset : Option<u64> = None;
        for i in range_inclusive(4, file_size) {
            let offset = file_size - i;
            try_io!(r.seek(offset as i64, SeekSet));

            let sig = try_io!(r.read_le_u32());

            // TODO: check for false positives here
            if sig == format::EOCDR_SIGNATURE {
                end_record_offset = Some(offset);
                break;
            }

        }

        match end_record_offset {
            Some(offset) => {
                try_io!(r.seek(offset as i64, SeekSet));
                let e = try!(format::EndOfCentralDirectoryRecord::read(&mut r));
                Ok(ZipReader {reader: r, end_record: e})
            },
            None => Err(error::NotAZipFile)
        }
    }

    pub fn files_raw<'a>(&'a mut self) -> Files<'a, R> {
        let cdr_offset = self.end_record.central_directory_offset;
        Files {
            zip_reader: self,
            current_entry: 0,
            current_offset: cdr_offset as u64
        }
    }

    pub fn files<'a>(&'a mut self) -> iter::Map<Result<FileInfo, ZipError>, FileInfo,
                                                Files<'a, R>> {
        self.files_raw().map(|fileinfo_or_err| fileinfo_or_err.unwrap())
    }

    pub fn file_names<'a>(&'a mut self) -> iter::Map<Result<FileInfo, ZipError>, MaybeUTF8,
                                                     Files<'a, R>> {
        self.files_raw().map(|fileinfo_or_err| fileinfo_or_err.unwrap().name)
    }

    pub fn info<T:BytesContainer>(&mut self, name: T) -> Result<FileInfo, ZipError> {
        for i in self.files() {
            if i.name.equiv(&name) {
                return Ok(i);
            }
        }
        Err(error::FileNotFoundInArchive)
    }

    // TODO: Create a Reader for the cases when you don't want to decompress the whole file
    pub fn read(&mut self, f: &FileInfo) -> Result<Vec<u8>, ZipError> {
        try_io!(self.reader.seek(f.local_file_header_offset as i64, SeekSet));
        let h = try!(format::LocalFileHeader::read(&mut self.reader));
        let file_offset = f.local_file_header_offset as i64 + h.total_size() as i64;

        let result =
            match CompressionMethod::from_u16(h.compression_method) {
                fileinfo::Store => self.read_stored_file(file_offset, h.uncompressed_size),
                fileinfo::Deflate => self.read_deflated_file(file_offset, h.compressed_size, h.uncompressed_size),
                _ => fail!()
            };
        let result = try_io!(result);

        // Check the CRC32 of the result against the one stored in the header
        let crc = crc32::crc32(result.as_slice());

        if crc == h.crc32 { Ok(result) }
        else { Err(error::CrcError) }
    }

    fn read_stored_file(&mut self, pos: i64, uncompressed_size: u32) -> IoResult<Vec<u8>> {
        try!(self.reader.seek(pos, SeekSet));
        self.reader.read_exact(uncompressed_size as uint)
    }

    fn read_deflated_file(&mut self, pos: i64, compressed_size: u32, uncompressed_size: u32) -> IoResult<Vec<u8>> {
        try!(self.reader.seek(pos, SeekSet));
        let compressed_bytes = try!(self.reader.read_exact(compressed_size as uint));
        let uncompressed_bytes = match flate::inflate_bytes(compressed_bytes.as_slice()) {
            Some(bytes) => bytes,
            None => return Err(IoError { kind: InvalidInput, desc: "decompression failure", detail: None })
        };
        assert!(uncompressed_bytes.len() as u32 == uncompressed_size);
        // FIXME try not to copy the buffer, or switch to the incremental fashion
        Ok(uncompressed_bytes.as_slice().to_vec())
    }

    // when we make read return a Reader, we will be able to loop here and copy
    // blocks of a fixed size from Reader to Writer
    pub fn extract<T:Writer>(&mut self, f: &FileInfo, writer: &mut T) -> Result<(), ZipError> {
        match self.read(f) {
            Ok(bytes) => { try_io!(writer.write(bytes.as_slice())); Ok(()) },
            Err(x) => Err(x)
        }
    }

}

<|endoftext|>


<commit_before>//! Pixel iterators for `SharedImageSurface`.
use crate::rect::IRect;
use crate::util::clamp;

use super::shared_surface::SharedImageSurface;
use super::{EdgeMode, Pixel};

/// Iterator over pixels of a `SharedImageSurface`.
#[derive(Debug, Clone, Copy)]
pub struct Pixels<'a> {
    surface: &'a SharedImageSurface,
    bounds: IRect,
    x: u32,
    y: u32,
    offset: isize,
}

/// Iterator over a (potentially out of bounds) rectangle of pixels of a `SharedImageSurface`.
#[derive(Debug, Clone, Copy)]
pub struct PixelRectangle<'a> {
    surface: &'a SharedImageSurface,
    bounds: IRect,
    rectangle: IRect,
    edge_mode: EdgeMode,
    x: i32,
    y: i32,
}

impl<'a> Pixels<'a> {
    /// Creates an iterator over the image surface pixels, constrained within the given bounds.
    #[inline]
    pub fn new(surface: &'a SharedImageSurface, bounds: IRect) -> Self {
        // Sanity checks.
        assert!(bounds.x0 >= 0);
        assert!(bounds.x0 <= surface.width());
        assert!(bounds.x1 >= bounds.x0);
        assert!(bounds.x1 <= surface.width());
        assert!(bounds.y0 >= 0);
        assert!(bounds.y0 <= surface.height());
        assert!(bounds.y1 >= bounds.y0);
        assert!(bounds.y1 <= surface.height());

        Self {
            surface,
            bounds,
            x: bounds.x0 as u32,
            y: bounds.y0 as u32,
            offset: bounds.y0 as isize * surface.stride() as isize + bounds.x0 as isize * 4,
        }
    }
}

impl<'a> PixelRectangle<'a> {
    /// Creates an iterator over the image surface pixels, constrained within the given bounds.
    #[inline]
    pub fn new(
        surface: &'a SharedImageSurface,
        bounds: IRect,
        rectangle: IRect,
        edge_mode: EdgeMode,
    ) -> Self {
        // Sanity checks.
        assert!(bounds.x0 >= 0);
        assert!(bounds.x0 <= surface.width());
        assert!(bounds.x1 >= bounds.x0);
        assert!(bounds.x1 <= surface.width());
        assert!(bounds.y0 >= 0);
        assert!(bounds.y0 <= surface.height());
        assert!(bounds.y1 >= bounds.y0);
        assert!(bounds.y1 <= surface.height());

        // Non-None EdgeMode values need at least one pixel available.
        if edge_mode != EdgeMode::None {
            assert!(bounds.x1 > bounds.x0);
            assert!(bounds.y1 > bounds.y0);
        }

        assert!(rectangle.x1 >= rectangle.x0);
        assert!(rectangle.y1 >= rectangle.y0);

        Self {
            surface,
            bounds,
            rectangle,
            edge_mode,
            x: rectangle.x0,
            y: rectangle.y0,
        }
    }
}

impl<'a> Iterator for Pixels<'a> {
    type Item = (u32, u32, Pixel);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        // This means we hit the end on the last iteration.
        if self.x == self.bounds.x1 as u32 || self.y == self.bounds.y1 as u32 {
            return None;
        }

        let rv = Some((
            self.x,
            self.y,
            self.surface.get_pixel_by_offset(self.offset),
        ));

        if self.x + 1 == self.bounds.x1 as u32 {
            self.x = self.bounds.x0 as u32;
            self.y += 1;
            self.offset +=
                self.surface.stride() - (self.bounds.x1 - self.bounds.x0 - 1) as isize * 4;
        } else {
            self.x += 1;
            self.offset += 4;
        }

        rv
    }
}

impl<'a> Iterator for PixelRectangle<'a> {
    type Item = (i32, i32, Pixel);

    #[inline(always)]
    fn next(&mut self) -> Option<Self::Item> {
        // This means we hit the end on the last iteration.
        if self.x == self.rectangle.x1 || self.y == self.rectangle.y1 {
            return None;
        }

        let rv = {
            let get_pixel = |x, y| {
                if x < self.bounds.x0
                    || y < self.bounds.y0
                    || x >= self.bounds.x1
                    || y >= self.bounds.y1
                {
                    match self.edge_mode {
                        EdgeMode::None => Pixel {
                            r: 0,
                            g: 0,
                            b: 0,
                            a: 0,
                        },
                        EdgeMode::Duplicate => {
                            let x = clamp(x, self.bounds.x0, self.bounds.x1 - 1);
                            let y = clamp(y, self.bounds.y0, self.bounds.y1 - 1);
                            self.surface.get_pixel(x as u32, y as u32)
                        }
                        EdgeMode::Wrap => {
                            let wrap = |mut x, v| {
                                while x < 0 {
                                    x += v;
                                }
                                x % v
                            };

                            let x = self.bounds.x0
                                + wrap(x - self.bounds.x0, self.bounds.x1 - self.bounds.x0);
                            let y = self.bounds.y0
                                + wrap(y - self.bounds.y0, self.bounds.y1 - self.bounds.y0);
                            self.surface.get_pixel(x as u32, y as u32)
                        }
                    }
                } else {
                    self.surface.get_pixel(x as u32, y as u32)
                }
            };

            Some((self.x, self.y, get_pixel(self.x, self.y)))
        };

        if self.x + 1 == self.rectangle.x1 {
            self.x = self.rectangle.x0;
            self.y += 1;
        } else {
            self.x += 1;
        }

        rv
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::surface_utils::shared_surface::SurfaceType;
    use cairo::{self, ImageSurface};

    #[test]
    fn pixels_count() {
        const WIDTH: i32 = 32;
        const HEIGHT: i32 = 64;

        let surface = SharedImageSurface::new(
            ImageSurface::create(cairo::Format::ARgb32, WIDTH, HEIGHT).unwrap(),
            SurfaceType::SRgb,
        )
        .unwrap();

        // Full image.
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: WIDTH,
            y1: HEIGHT,
        };
        assert_eq!(
            Pixels::new(&surface, bounds).count(),
            (WIDTH * HEIGHT) as usize
        );

        // 1-wide column.
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: 1,
            y1: HEIGHT,
        };
        assert_eq!(Pixels::new(&surface, bounds).count(), HEIGHT as usize);

        // 1-tall row.
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: WIDTH,
            y1: 1,
        };
        assert_eq!(Pixels::new(&surface, bounds).count(), WIDTH as usize);

        // 1×1.
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: 1,
            y1: 1,
        };
        assert_eq!(Pixels::new(&surface, bounds).count(), 1);

        // Nothing (x0 == x1).
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: 0,
            y1: HEIGHT,
        };
        assert_eq!(Pixels::new(&surface, bounds).count(), 0);

        // Nothing (y0 == y1).
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: WIDTH,
            y1: 0,
        };
        assert_eq!(Pixels::new(&surface, bounds).count(), 0);

        // Nothing (x0 == x1, y0 == y1).
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: 0,
            y1: 0,
        };
        assert_eq!(Pixels::new(&surface, bounds).count(), 0);
    }

    #[test]
    fn pixel_rectangle() {
        const WIDTH: i32 = 32;
        const HEIGHT: i32 = 64;

        let surface = SharedImageSurface::new(
            ImageSurface::create(cairo::Format::ARgb32, WIDTH, HEIGHT).unwrap(),
            SurfaceType::SRgb,
        )
        .unwrap();

        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: WIDTH,
            y1: HEIGHT,
        };

        let rect_bounds = IRect {
            x0: -8,
            y0: -8,
            x1: 8,
            y1: 8,
        };
        assert_eq!(
            PixelRectangle::new(&surface, bounds, rect_bounds, EdgeMode::None).count(),
            (16 * 16) as usize
        );
    }
}
<commit_msg>surface_utils: use IRect::contains<commit_after>//! Pixel iterators for `SharedImageSurface`.
use crate::rect::IRect;
use crate::util::clamp;

use super::shared_surface::SharedImageSurface;
use super::{EdgeMode, Pixel};

/// Iterator over pixels of a `SharedImageSurface`.
#[derive(Debug, Clone, Copy)]
pub struct Pixels<'a> {
    surface: &'a SharedImageSurface,
    bounds: IRect,
    x: u32,
    y: u32,
    offset: isize,
}

/// Iterator over a (potentially out of bounds) rectangle of pixels of a `SharedImageSurface`.
#[derive(Debug, Clone, Copy)]
pub struct PixelRectangle<'a> {
    surface: &'a SharedImageSurface,
    bounds: IRect,
    rectangle: IRect,
    edge_mode: EdgeMode,
    x: i32,
    y: i32,
}

impl<'a> Pixels<'a> {
    /// Creates an iterator over the image surface pixels, constrained within the given bounds.
    #[inline]
    pub fn new(surface: &'a SharedImageSurface, bounds: IRect) -> Self {
        // Sanity checks.
        assert!(bounds.x0 >= 0);
        assert!(bounds.x0 <= surface.width());
        assert!(bounds.x1 >= bounds.x0);
        assert!(bounds.x1 <= surface.width());
        assert!(bounds.y0 >= 0);
        assert!(bounds.y0 <= surface.height());
        assert!(bounds.y1 >= bounds.y0);
        assert!(bounds.y1 <= surface.height());

        Self {
            surface,
            bounds,
            x: bounds.x0 as u32,
            y: bounds.y0 as u32,
            offset: bounds.y0 as isize * surface.stride() as isize + bounds.x0 as isize * 4,
        }
    }
}

impl<'a> PixelRectangle<'a> {
    /// Creates an iterator over the image surface pixels, constrained within the given bounds.
    #[inline]
    pub fn new(
        surface: &'a SharedImageSurface,
        bounds: IRect,
        rectangle: IRect,
        edge_mode: EdgeMode,
    ) -> Self {
        // Sanity checks.
        assert!(bounds.x0 >= 0);
        assert!(bounds.x0 <= surface.width());
        assert!(bounds.x1 >= bounds.x0);
        assert!(bounds.x1 <= surface.width());
        assert!(bounds.y0 >= 0);
        assert!(bounds.y0 <= surface.height());
        assert!(bounds.y1 >= bounds.y0);
        assert!(bounds.y1 <= surface.height());

        // Non-None EdgeMode values need at least one pixel available.
        if edge_mode != EdgeMode::None {
            assert!(bounds.x1 > bounds.x0);
            assert!(bounds.y1 > bounds.y0);
        }

        assert!(rectangle.x1 >= rectangle.x0);
        assert!(rectangle.y1 >= rectangle.y0);

        Self {
            surface,
            bounds,
            rectangle,
            edge_mode,
            x: rectangle.x0,
            y: rectangle.y0,
        }
    }
}

impl<'a> Iterator for Pixels<'a> {
    type Item = (u32, u32, Pixel);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        // This means we hit the end on the last iteration.
        if self.x == self.bounds.x1 as u32 || self.y == self.bounds.y1 as u32 {
            return None;
        }

        let rv = Some((
            self.x,
            self.y,
            self.surface.get_pixel_by_offset(self.offset),
        ));

        if self.x + 1 == self.bounds.x1 as u32 {
            self.x = self.bounds.x0 as u32;
            self.y += 1;
            self.offset +=
                self.surface.stride() - (self.bounds.x1 - self.bounds.x0 - 1) as isize * 4;
        } else {
            self.x += 1;
            self.offset += 4;
        }

        rv
    }
}

impl<'a> Iterator for PixelRectangle<'a> {
    type Item = (i32, i32, Pixel);

    #[inline(always)]
    fn next(&mut self) -> Option<Self::Item> {
        // This means we hit the end on the last iteration.
        if self.x == self.rectangle.x1 || self.y == self.rectangle.y1 {
            return None;
        }

        let rv = {
            let get_pixel = |x, y| {
                if !self.bounds.contains(x, y) {
                    match self.edge_mode {
                        EdgeMode::None => Pixel {
                            r: 0,
                            g: 0,
                            b: 0,
                            a: 0,
                        },
                        EdgeMode::Duplicate => {
                            let x = clamp(x, self.bounds.x0, self.bounds.x1 - 1);
                            let y = clamp(y, self.bounds.y0, self.bounds.y1 - 1);
                            self.surface.get_pixel(x as u32, y as u32)
                        }
                        EdgeMode::Wrap => {
                            let wrap = |mut x, v| {
                                while x < 0 {
                                    x += v;
                                }
                                x % v
                            };

                            let x = self.bounds.x0
                                + wrap(x - self.bounds.x0, self.bounds.x1 - self.bounds.x0);
                            let y = self.bounds.y0
                                + wrap(y - self.bounds.y0, self.bounds.y1 - self.bounds.y0);
                            self.surface.get_pixel(x as u32, y as u32)
                        }
                    }
                } else {
                    self.surface.get_pixel(x as u32, y as u32)
                }
            };

            Some((self.x, self.y, get_pixel(self.x, self.y)))
        };

        if self.x + 1 == self.rectangle.x1 {
            self.x = self.rectangle.x0;
            self.y += 1;
        } else {
            self.x += 1;
        }

        rv
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::surface_utils::shared_surface::SurfaceType;
    use cairo::{self, ImageSurface};

    #[test]
    fn pixels_count() {
        const WIDTH: i32 = 32;
        const HEIGHT: i32 = 64;

        let surface = SharedImageSurface::new(
            ImageSurface::create(cairo::Format::ARgb32, WIDTH, HEIGHT).unwrap(),
            SurfaceType::SRgb,
        )
        .unwrap();

        // Full image.
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: WIDTH,
            y1: HEIGHT,
        };
        assert_eq!(
            Pixels::new(&surface, bounds).count(),
            (WIDTH * HEIGHT) as usize
        );

        // 1-wide column.
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: 1,
            y1: HEIGHT,
        };
        assert_eq!(Pixels::new(&surface, bounds).count(), HEIGHT as usize);

        // 1-tall row.
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: WIDTH,
            y1: 1,
        };
        assert_eq!(Pixels::new(&surface, bounds).count(), WIDTH as usize);

        // 1×1.
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: 1,
            y1: 1,
        };
        assert_eq!(Pixels::new(&surface, bounds).count(), 1);

        // Nothing (x0 == x1).
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: 0,
            y1: HEIGHT,
        };
        assert_eq!(Pixels::new(&surface, bounds).count(), 0);

        // Nothing (y0 == y1).
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: WIDTH,
            y1: 0,
        };
        assert_eq!(Pixels::new(&surface, bounds).count(), 0);

        // Nothing (x0 == x1, y0 == y1).
        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: 0,
            y1: 0,
        };
        assert_eq!(Pixels::new(&surface, bounds).count(), 0);
    }

    #[test]
    fn pixel_rectangle() {
        const WIDTH: i32 = 32;
        const HEIGHT: i32 = 64;

        let surface = SharedImageSurface::new(
            ImageSurface::create(cairo::Format::ARgb32, WIDTH, HEIGHT).unwrap(),
            SurfaceType::SRgb,
        )
        .unwrap();

        let bounds = IRect {
            x0: 0,
            y0: 0,
            x1: WIDTH,
            y1: HEIGHT,
        };

        let rect_bounds = IRect {
            x0: -8,
            y0: -8,
            x1: 8,
            y1: 8,
        };
        assert_eq!(
            PixelRectangle::new(&surface, bounds, rect_bounds, EdgeMode::None).count(),
            (16 * 16) as usize
        );
    }
}
<|endoftext|>


<commit_before>/* PKCS#7 padding
 *
 * Dmitry Vasiliev <dima@hlabs.org>
 */

fn pkcs7(data: &[u8], size: u8) -> Vec<u8> {
    let len = data.len();
    if len > size as uint {
        fail!("Invalid block size: {}", size);
    } else if len == size as uint {
        data.to_vec()
    } else {
        let pad = size - len as u8;
        data.to_vec() + Vec::from_elem(pad as uint, pad)
    }
}

/*
 * Main entry point
 */
#[cfg(not(test))]
fn main() {
    let input = "YELLOW SUBMARINE".as_bytes();
    println!("Input     => {}", input);
    println!("PKCS#7    => {}", pkcs7(input, 20));
}

/*
 * Tests
 */
#[cfg(test)]
mod test {
    use super::pkcs7;

    #[test]
    fn test_pkcs7() {
        let input = "YELLOW SUBMARINE".as_bytes();
        assert_eq!("YELLOW SUBMARINE\x04\x04\x04\x04".as_bytes().to_vec(),
                   pkcs7(input, 20));
    }
}
<commit_msg>Small optimization<commit_after>/* PKCS#7 padding
 *
 * Dmitry Vasiliev <dima@hlabs.org>
 */

fn pkcs7(data: &[u8], size: u8) -> Vec<u8> {
    let len = data.len();
    if len > size as uint {
        fail!("Invalid block size: {}", size);
    } else if len == size as uint {
        data.into_vec()
    } else {
        let pad = size - len as u8;
        data.into_vec() + Vec::from_elem(pad as uint, pad)
    }
}

/*
 * Main entry point
 */
#[cfg(not(test))]
fn main() {
    let input = "YELLOW SUBMARINE".as_bytes();
    println!("Input     => {}", input);
    println!("PKCS#7    => {}", pkcs7(input, 20));
}

/*
 * Tests
 */
#[cfg(test)]
mod test {
    use super::pkcs7;

    #[test]
    fn test_pkcs7() {
        let input = "YELLOW SUBMARINE".as_bytes();
        assert_eq!("YELLOW SUBMARINE\x04\x04\x04\x04".as_bytes().to_vec(),
                   pkcs7(input, 20));
    }
}
<|endoftext|>