<commit_before>use graphics::*;

// Local crate.
use Vector2d = vector2d::Vector2d;

static EPSILON: f64 = 0.0000000001;

pub fn area(contour: &[Vector2d]) -> f64 {
    let n = contour.len();
    let mut A = 0.0_f64;

    for i in range(0, n) {
        let q = i;
        let p = (i + n - 1) % n;
        A += contour.get(p).unwrap().get_x() * contour.get(q).unwrap().get_y()
            - contour.get(q).unwrap().get_x() * contour.get(p).unwrap().get_y();
    }

    A * 0.5_f64
}

/// InsideTriangle decides if a point P is Inside of the triangle
/// defined by A, B, C.
pub fn inside_triangle(
    Ax: f64, Ay: f64,
    Bx: f64, By: f64,
    Cx: f64, Cy: f64,
    Px: f64, Py: f64
) -> bool {

    let ax = Cx - Bx;
    let ay = Cy - By;
    let bx = Ax - Cx;
    let by = Ay - Cy;
    let cx = Bx - Ax;
    let cy = By - Ay;
    let apx = Px - Ax;
    let apy = Py - Ay;
    let bpx = Px - Bx;
    let bpy = Py - By;
    let cpx = Px - Cx;
    let cpy = Py - Cy;

    let aCROSSbp = ax*bpy - ay*bpx;
    let cCROSSap = cx*apy - cy*apx;
    let bCROSScp = bx*cpy - by*cpx;

    (
        (aCROSSbp >= 0.0_f64)
        && (bCROSScp >= 0.0_f64)
        && (cCROSSap >= 0.0_f64)
    )
}

pub fn snip(
    contour: &[Vector2d],
    triangle: [uint, ..3],
    n: uint,
    V: &mut Vec<uint>
) -> bool {
    let u = triangle[0];
    let v = triangle[1];
    let w = triangle[2];

    let Ax = contour.get(*V.get(u)).unwrap().get_x();
    let Ay = contour.get(*V.get(u)).unwrap().get_y();

    let Bx = contour.get(*V.get(v)).unwrap().get_x();
    let By = contour.get(*V.get(v)).unwrap().get_y();

    let Cx = contour.get(*V.get(w)).unwrap().get_x();
    let Cy = contour.get(*V.get(w)).unwrap().get_y();

    if EPSILON > (((Bx-Ax)*(Cy-Ay)) - ((By-Ay)*(Cx-Ax))) {
        return false;
    }

    for p in range(0, n) {
        if (p == u) || (p == v) || (p == w) { continue; }

        let Px = contour.get(*V.get(p)).unwrap().get_x();
        let Py = contour.get(*V.get(p)).unwrap().get_y();

        if inside_triangle(Ax,Ay,Bx,By,Cx,Cy,Px,Py) { return false; }
    }

    return true;
}

pub fn process(
    contour: &[Vector2d]
) -> Option<Vec<Vector2d>> {
    /* allocate and initialize list of Vertices in polygon */

    let n = contour.len();
    if n < 3 { return None; }

    let mut result: Vec<Vector2d> = Vec::new();
    let mut vertex_indices: Vec<uint> = Vec::with_capacity(n);

    /* we want a counter-clockwise polygon in V */

    // Computes the area which has opposite signs
    // whether the polygon is clock-wise or counter-clockwise.
    if 0.0_f64 < area(contour) {
        for v in range(0, n) { vertex_indices.push(v); }
    } else {
        // Add indices in reverse order.
        for v in range(0, n) { vertex_indices.push((n-1)-v); }
    }

    // Stores the number of vertices.
    // Used instead of `vertex_indices.len()` to emulate removing of vertices.
    let mut number_of_vertices = n;

    /*  remove nv-2 Vertices, creating 1 triangle every time */

    // Used for error detection.
    let mut count = 2 * number_of_vertices;

    let mut v = number_of_vertices - 1;
    while number_of_vertices > 2 {
        /* if we loop, it is probably a non-simple polygon */
        if count <= 0 {
            //** Triangulate: ERROR - probable bad polygon!
            return None;
        }

        count -= 1;

        /* three consecutive vertices in current polygon, <u,v,w> */
        let triangle = [
            v,
            vecmath::modular_offset_index(number_of_vertices, v, 1),
            vecmath::modular_offset_index(number_of_vertices, v, 2)
        ];
        v = triangle[1];

        if snip(contour, triangle, number_of_vertices, &mut vertex_indices) {
            for &i in triangle.iter() {
                result.push(*contour.get(*vertex_indices.get(i)).unwrap());
            }

            /* remove v from remaining polygon */
            for i in range(0, number_of_vertices - 3) {
                let s = v + i;
                let t = v + i + 1;

                *vertex_indices.get_mut(s) = *vertex_indices.get(t);
            }

            // "Removed" a vertex.
            number_of_vertices -= 1;

            /* resest error detection counter */
            count = 2 * number_of_vertices;
        }
    }

    Some(result)
}

<commit_msg>Replaced `V` with `vertex_indices`<commit_after>use graphics::*;

// Local crate.
use Vector2d = vector2d::Vector2d;

static EPSILON: f64 = 0.0000000001;

pub fn area(contour: &[Vector2d]) -> f64 {
    let n = contour.len();
    let mut A = 0.0_f64;

    for i in range(0, n) {
        let q = i;
        let p = (i + n - 1) % n;
        A += contour.get(p).unwrap().get_x() * contour.get(q).unwrap().get_y()
            - contour.get(q).unwrap().get_x() * contour.get(p).unwrap().get_y();
    }

    A * 0.5_f64
}

/// InsideTriangle decides if a point P is Inside of the triangle
/// defined by A, B, C.
pub fn inside_triangle(
    Ax: f64, Ay: f64,
    Bx: f64, By: f64,
    Cx: f64, Cy: f64,
    Px: f64, Py: f64
) -> bool {

    let ax = Cx - Bx;
    let ay = Cy - By;
    let bx = Ax - Cx;
    let by = Ay - Cy;
    let cx = Bx - Ax;
    let cy = By - Ay;
    let apx = Px - Ax;
    let apy = Py - Ay;
    let bpx = Px - Bx;
    let bpy = Py - By;
    let cpx = Px - Cx;
    let cpy = Py - Cy;

    let aCROSSbp = ax*bpy - ay*bpx;
    let cCROSSap = cx*apy - cy*apx;
    let bCROSScp = bx*cpy - by*cpx;

    (
        (aCROSSbp >= 0.0_f64)
        && (bCROSScp >= 0.0_f64)
        && (cCROSSap >= 0.0_f64)
    )
}

pub fn snip(
    contour: &[Vector2d],
    triangle: [uint, ..3],
    n: uint,
    vertex_indices: &Vec<uint>
) -> bool {
    let u = triangle[0];
    let v = triangle[1];
    let w = triangle[2];

    let Ax = contour.get(*vertex_indices.get(u)).unwrap().get_x();
    let Ay = contour.get(*vertex_indices.get(u)).unwrap().get_y();

    let Bx = contour.get(*vertex_indices.get(v)).unwrap().get_x();
    let By = contour.get(*vertex_indices.get(v)).unwrap().get_y();

    let Cx = contour.get(*vertex_indices.get(w)).unwrap().get_x();
    let Cy = contour.get(*vertex_indices.get(w)).unwrap().get_y();

    if EPSILON > (((Bx-Ax)*(Cy-Ay)) - ((By-Ay)*(Cx-Ax))) {
        return false;
    }

    for p in range(0, n) {
        if (p == u) || (p == v) || (p == w) { continue; }

        let Px = contour.get(*vertex_indices.get(p)).unwrap().get_x();
        let Py = contour.get(*vertex_indices.get(p)).unwrap().get_y();

        if inside_triangle(Ax,Ay,Bx,By,Cx,Cy,Px,Py) { return false; }
    }

    return true;
}

pub fn process(
    contour: &[Vector2d]
) -> Option<Vec<Vector2d>> {
    /* allocate and initialize list of Vertices in polygon */

    let n = contour.len();
    if n < 3 { return None; }

    let mut result: Vec<Vector2d> = Vec::new();
    let mut vertex_indices: Vec<uint> = Vec::with_capacity(n);

    /* we want a counter-clockwise polygon in V */

    // Computes the area which has opposite signs
    // whether the polygon is clock-wise or counter-clockwise.
    if 0.0_f64 < area(contour) {
        for v in range(0, n) { vertex_indices.push(v); }
    } else {
        // Add indices in reverse order.
        for v in range(0, n) { vertex_indices.push((n-1)-v); }
    }

    // Stores the number of vertices.
    // Used instead of `vertex_indices.len()` to emulate removing of vertices.
    let mut number_of_vertices = n;

    /*  remove nv-2 Vertices, creating 1 triangle every time */

    // Used for error detection.
    let mut count = 2 * number_of_vertices;

    let mut v = number_of_vertices - 1;
    while number_of_vertices > 2 {
        /* if we loop, it is probably a non-simple polygon */
        if count <= 0 {
            //** Triangulate: ERROR - probable bad polygon!
            return None;
        }

        count -= 1;

        /* three consecutive vertices in current polygon, <u,v,w> */
        let triangle = [
            v,
            vecmath::modular_offset_index(number_of_vertices, v, 1),
            vecmath::modular_offset_index(number_of_vertices, v, 2)
        ];
        v = triangle[1];

        if snip(contour, triangle, number_of_vertices, &mut vertex_indices) {
            for &i in triangle.iter() {
                result.push(*contour.get(*vertex_indices.get(i)).unwrap());
            }

            /* remove v from remaining polygon */
            for i in range(0, number_of_vertices - 3) {
                let s = v + i;
                let t = v + i + 1;

                *vertex_indices.get_mut(s) = *vertex_indices.get(t);
            }

            // "Removed" a vertex.
            number_of_vertices -= 1;

            /* resest error detection counter */
            count = 2 * number_of_vertices;
        }
    }

    Some(result)
}

<|endoftext|>


<commit_before>#![deny(warnings)]

extern crate ctest;

use std::env;

fn main() {
    let target = env::var("TARGET").unwrap();
    let x86_64 = target.contains("x86_64");
    let windows = target.contains("windows");
    let mingw = target.contains("windows-gnu");
    let linux = target.contains("unknown-linux");
    let android = target.contains("android");
    let apple = target.contains("apple");
    let musl = target.contains("musl");
    let freebsd = target.contains("freebsd");
    let dragonfly = target.contains("dragonfly");
    let mips = target.contains("mips");
    let netbsd = target.contains("netbsd");
    let openbsd = target.contains("openbsd");
    let rumprun = target.contains("rumprun");
    let bsdlike = freebsd || apple || netbsd || openbsd || dragonfly;
    let mut cfg = ctest::TestGenerator::new();

    // Pull in extra goodies on linux/mingw
    if linux || android {
        cfg.define("_GNU_SOURCE", None);
    } else if windows {
        cfg.define("_WIN32_WINNT", Some("0x8000"));
    }

    // Android doesn't actually have in_port_t but it's much easier if we
    // provide one for us to test against
    if android {
        cfg.define("in_port_t", Some("uint16_t"));
    }

    cfg.header("errno.h")
       .header("fcntl.h")
       .header("limits.h")
       .header("stddef.h")
       .header("stdint.h")
       .header("stdio.h")
       .header("stdlib.h")
       .header("sys/stat.h")
       .header("sys/types.h")
       .header("time.h")
       .header("wchar.h");

    if windows {
        cfg.header("winsock2.h"); // must be before windows.h

        cfg.header("direct.h");
        cfg.header("io.h");
        cfg.header("sys/utime.h");
        cfg.header("windows.h");
        cfg.header("process.h");
        cfg.header("ws2ipdef.h");

        if target.contains("gnu") {
            cfg.header("ws2tcpip.h");
        }
    } else {
        cfg.header("ctype.h");
        cfg.header("dirent.h");
        if openbsd {
            cfg.header("sys/socket.h");
        }
        cfg.header("net/if.h");
        cfg.header("netdb.h");
        cfg.header("netinet/in.h");
        cfg.header("netinet/ip.h");
        cfg.header("netinet/tcp.h");
        cfg.header("pthread.h");
        cfg.header("dlfcn.h");
        cfg.header("signal.h");
        cfg.header("string.h");
        cfg.header("sys/file.h");
        cfg.header("sys/ioctl.h");
        cfg.header("sys/mman.h");
        cfg.header("sys/resource.h");
        cfg.header("sys/socket.h");
        cfg.header("sys/time.h");
        cfg.header("sys/un.h");
        cfg.header("sys/wait.h");
        cfg.header("unistd.h");
        cfg.header("utime.h");
        cfg.header("pwd.h");
        cfg.header("grp.h");
        cfg.header("sys/utsname.h");
        cfg.header("sys/ptrace.h");
        cfg.header("sys/mount.h");
        cfg.header("sys/uio.h");
        cfg.header("sched.h");
        cfg.header("termios.h");
        cfg.header("poll.h");
    }

    if android {
        cfg.header("arpa/inet.h");
        cfg.header("time64.h");
    } else if !windows {
        cfg.header("glob.h");
        cfg.header("ifaddrs.h");
        cfg.header("sys/statvfs.h");

        if !openbsd && !freebsd && !dragonfly {
            cfg.header("sys/quota.h");
        }

        if !musl {
            cfg.header("sys/sysctl.h");

            if !netbsd && !openbsd {
                cfg.header("execinfo.h");
            }
        }
    }

    if apple {
        cfg.header("mach-o/dyld.h");
        cfg.header("mach/mach_time.h");
        cfg.header("malloc/malloc.h");
        cfg.header("util.h");
        if target.starts_with("x86") {
            cfg.header("crt_externs.h");
        }
    }

    if bsdlike {
        cfg.header("sys/event.h");
    }

    if linux {
        cfg.header("mqueue.h");
        cfg.header("ucontext.h");
        cfg.header("sys/signalfd.h");
        cfg.header("sys/xattr.h");
        cfg.header("sys/ipc.h");
        cfg.header("sys/shm.h");
    }

    if linux || android {
        cfg.header("malloc.h");
        cfg.header("net/ethernet.h");
        cfg.header("netpacket/packet.h");
        cfg.header("sched.h");
        cfg.header("sys/epoll.h");
        cfg.header("sys/eventfd.h");
        cfg.header("sys/prctl.h");
        cfg.header("sys/sendfile.h");
        cfg.header("sys/vfs.h");
        cfg.header("sys/syscall.h");
        if !musl {
            cfg.header("linux/netlink.h");
            cfg.header("linux/magic.h");

            if !mips {
                cfg.header("linux/quota.h");
            }
        }
    }

    if freebsd {
        cfg.header("pthread_np.h");
        cfg.header("sched.h");
        cfg.header("ufs/ufs/quota.h");
    }

    if netbsd {
        cfg.header("ufs/ufs/quota.h");
        cfg.header("ufs/ufs/quota1.h");
        cfg.header("sys/ioctl_compat.h");
    }

    if openbsd {
        cfg.header("ufs/ufs/quota.h");
        cfg.header("rpcsvc/rex.h");
        cfg.header("pthread_np.h");
        cfg.header("sys/syscall.h");
    }

    if dragonfly {
        cfg.header("ufs/ufs/quota.h");
        cfg.header("pthread_np.h");
        cfg.header("sys/ioctl_compat.h");
    }

    cfg.type_name(move |ty, is_struct| {
        match ty {
            // Just pass all these through, no need for a "struct" prefix
            "FILE" |
            "fd_set" |
            "Dl_info" |
            "DIR" => ty.to_string(),

            // Fixup a few types on windows that don't actually exist.
            "time64_t" if windows => "__time64_t".to_string(),
            "ssize_t" if windows => "SSIZE_T".to_string(),

            // OSX calls this something else
            "sighandler_t" if bsdlike => "sig_t".to_string(),

            t if t.ends_with("_t") => t.to_string(),

            // Windows uppercase structs don't have `struct` in front, there's a
            // few special cases for windows, and then otherwise put `struct` in
            // front of everything.
            t if is_struct => {
                if windows && ty.chars().next().unwrap().is_uppercase() {
                    t.to_string()
                } else if windows && t == "stat" {
                    "struct __stat64".to_string()
                } else if windows && t == "utimbuf" {
                    "struct __utimbuf64".to_string()
                } else {
                    format!("struct {}", t)
                }
            }

            t => t.to_string(),
        }
    });

    let target2 = target.clone();
    cfg.field_name(move |struct_, field| {
        match field {
            "st_birthtime"      if openbsd && struct_ == "stat" => "__st_birthtime".to_string(),
            "st_birthtime_nsec" if openbsd && struct_ == "stat" => "__st_birthtimensec".to_string(),
            // Our stat *_nsec fields normally don't actually exist but are part
            // of a timeval struct
            s if s.ends_with("_nsec") && struct_.starts_with("stat") => {
                if target2.contains("apple") {
                    s.replace("_nsec", "spec.tv_nsec")
                } else if target2.contains("android") {
                    s.to_string()
                } else {
                    s.replace("e_nsec", ".tv_nsec")
                }
            }
            "u64" if struct_ == "epoll_event" => "data.u64".to_string(),
            s => s.to_string(),
        }
    });

    cfg.skip_type(move |ty| {
        match ty {
            // sighandler_t is crazy across platforms
            "sighandler_t" => true,

            _ => false
        }
    });

    cfg.skip_struct(move |ty| {
        match ty {
            "sockaddr_nl" => musl,

            // The alignment of this is 4 on 64-bit OSX...
            "kevent" if apple && x86_64 => true,

            _ => false
        }
    });

    cfg.skip_signededness(move |c| {
        match c {
            "LARGE_INTEGER" |
            "mach_timebase_info_data_t" |
            "float" |
            "double" => true,
            // uuid_t is a struct, not an integer.
            "uuid_t" if dragonfly => true,
            n if n.starts_with("pthread") => true,

            // windows-isms
            n if n.starts_with("P") => true,
            n if n.starts_with("H") => true,
            n if n.starts_with("LP") => true,
            _ => false,
        }
    });

    cfg.skip_const(move |name| {
        match name {
            // Apparently these don't exist in mingw headers?
            "MEM_RESET_UNDO" |
            "FILE_ATTRIBUTE_NO_SCRUB_DATA" |
            "FILE_ATTRIBUTE_INTEGRITY_STREAM" |
            "ERROR_NOTHING_TO_TERMINATE" if mingw => true,

            "SIG_IGN" => true, // sighandler_t weirdness

            // types on musl are defined a little differently
            n if musl && n.contains("__SIZEOF_PTHREAD") => true,

            // Skip constants not defined in MUSL but just passed down to the
            // kernel regardless
            "RLIMIT_NLIMITS" |
            "TCP_COOKIE_TRANSACTIONS" |
            "RLIMIT_RTTIME" if musl => true,
            // work around super old mips toolchain
            "SCHED_IDLE" | "SHM_NORESERVE" => mips,

            // weird signed extension or something like that?
            "MS_NOUSER" => true,

            // These OSX constants are flagged as deprecated
            "NOTE_EXIT_REPARENTED" |
            "NOTE_REAP" if apple => true,

            // The linux/quota.h header file which defines these can't be
            // included with sys/quota.h currently on MIPS, so we don't include
            // it and just ignore these constants
            "QFMT_VFS_OLD" |
            "QFMT_VFS_V0" if mips && linux => true,

            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        // skip those that are manually verified
        match name {
            "execv" |       // crazy stuff with const/mut
            "execve" |
            "execvp" |
            "execvpe" => true,

            "getrlimit" | "getrlimit64" |    // non-int in 1st arg
            "setrlimit" | "setrlimit64" |    // non-int in 1st arg
            "strerror_r" if linux => true,   // actually xpg-something-or-other

            // typed 2nd arg on linux and android
            "gettimeofday" if linux || android || freebsd || openbsd || dragonfly => true,

            // not declared in newer android toolchains
            "getdtablesize" if android => true,

            "dlerror" if android => true, // const-ness is added
            "dladdr" if musl => true, // const-ness only added recently

            // OSX has 'struct tm *const' which we can't actually represent in
            // Rust, but is close enough to *mut
            "timegm" if apple => true,

            // OSX's daemon is deprecated in 10.5 so we'll get a warning (which
            // we turn into an error) so just ignore it.
            "daemon" if apple => true,

            // These functions presumably exist on netbsd but don't look like
            // they're implemented on rumprun yet, just let them slide for now.
            // Some of them look like they have headers but then don't have
            // corresponding actual definitions either...
            "shm_open" |
            "shm_unlink" |
            "syscall" |
            "ptrace" |
            "sigaltstack" if rumprun => true,

            // There seems to be a small error in EGLIBC's eventfd.h header. The
            // [underlying system call][1] always takes its first `count`
            // argument as an `unsigned int`, but [EGLIBC's <sys/eventfd.h>
            // header][2] declares it to take an `int`. [GLIBC's header][3]
            // matches the kernel.
            //
            // EGLIBC is no longer actively developed, and Debian, the largest
            // distribution that had been using it, switched back to GLIBC in
            // April 2015. So effectively all Linux <sys/eventfd.h> headers will
            // be using `unsigned int` soon.
            //
            // [1]: https://git.kernel.org/cgit/linux/kernel/git/stable/linux-stable.git/tree/fs/eventfd.c?id=refs/tags/v3.12.51#n397
            // [2]: http://bazaar.launchpad.net/~ubuntu-branches/ubuntu/trusty/eglibc/trusty/view/head:/sysdeps/unix/sysv/linux/sys/eventfd.h
            // [3]: https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/sys/eventfd.h;h=6295f32e937e779e74318eb9d3bdbe76aef8a8f3;hb=4e42b5b8f89f0e288e68be7ad70f9525aebc2cff#l34
            "eventfd" if linux => true,

            // The `uname` funcion in freebsd is now an inline wrapper that
            // delegates to another, but the symbol still exists, so don't check
            // the symbol.
            "uname" if freebsd => true,

            _ => false,
        }
    });

    cfg.skip_fn_ptrcheck(move |name| {
        match name {
            // This used to be called bsd_signal in rev 18 of the android
            // platform and is now just called signal, the old `bsd_signal`
            // symbol, however, still remains, just gives a different function
            // pointer.
            "signal" if android => true,

            // dllimport weirdness?
            _ if windows => true,

            _ => false,
        }
    });

    cfg.skip_field_type(move |struct_, field| {
        // This is a weird union, don't check the type.
        (struct_ == "ifaddrs" && field == "ifa_ifu") ||
        // sighandler_t type is super weird
        (struct_ == "sigaction" && field == "sa_sigaction")
    });

    cfg.skip_field(move |struct_, field| {
        // this is actually a union on linux, so we can't represent it well and
        // just insert some padding.
        (struct_ == "siginfo_t" && field == "_pad") ||
        // musl names this __dummy1 but it's still there
        (musl && struct_ == "glob_t" && field == "gl_flags") ||
        // musl seems to define this as an *anonymous* bitfield
        (musl && struct_ == "statvfs" && field == "__f_unused")
    });

    cfg.fn_cname(move |name, cname| {
        if windows {
            cname.unwrap_or(name).to_string()
        } else {
            name.to_string()
        }
    });

    if env::var("SKIP_COMPILE").is_ok() {
        cfg.generate_files("../src/lib.rs", "all.rs");
    } else {
        cfg.generate("../src/lib.rs", "all.rs");
    }
}
<commit_msg>Do not skip "signal" when building libc tests.<commit_after>#![deny(warnings)]

extern crate ctest;

use std::env;

fn main() {
    let target = env::var("TARGET").unwrap();
    let x86_64 = target.contains("x86_64");
    let windows = target.contains("windows");
    let mingw = target.contains("windows-gnu");
    let linux = target.contains("unknown-linux");
    let android = target.contains("android");
    let apple = target.contains("apple");
    let musl = target.contains("musl");
    let freebsd = target.contains("freebsd");
    let dragonfly = target.contains("dragonfly");
    let mips = target.contains("mips");
    let netbsd = target.contains("netbsd");
    let openbsd = target.contains("openbsd");
    let rumprun = target.contains("rumprun");
    let bsdlike = freebsd || apple || netbsd || openbsd || dragonfly;
    let mut cfg = ctest::TestGenerator::new();

    // Pull in extra goodies on linux/mingw
    if linux || android {
        cfg.define("_GNU_SOURCE", None);
    } else if windows {
        cfg.define("_WIN32_WINNT", Some("0x8000"));
    }

    // Android doesn't actually have in_port_t but it's much easier if we
    // provide one for us to test against
    if android {
        cfg.define("in_port_t", Some("uint16_t"));
    }

    cfg.header("errno.h")
       .header("fcntl.h")
       .header("limits.h")
       .header("stddef.h")
       .header("stdint.h")
       .header("stdio.h")
       .header("stdlib.h")
       .header("sys/stat.h")
       .header("sys/types.h")
       .header("time.h")
       .header("wchar.h");

    if windows {
        cfg.header("winsock2.h"); // must be before windows.h

        cfg.header("direct.h");
        cfg.header("io.h");
        cfg.header("sys/utime.h");
        cfg.header("windows.h");
        cfg.header("process.h");
        cfg.header("ws2ipdef.h");

        if target.contains("gnu") {
            cfg.header("ws2tcpip.h");
        }
    } else {
        cfg.header("ctype.h");
        cfg.header("dirent.h");
        if openbsd {
            cfg.header("sys/socket.h");
        }
        cfg.header("net/if.h");
        cfg.header("netdb.h");
        cfg.header("netinet/in.h");
        cfg.header("netinet/ip.h");
        cfg.header("netinet/tcp.h");
        cfg.header("pthread.h");
        cfg.header("dlfcn.h");
        cfg.header("signal.h");
        cfg.header("string.h");
        cfg.header("sys/file.h");
        cfg.header("sys/ioctl.h");
        cfg.header("sys/mman.h");
        cfg.header("sys/resource.h");
        cfg.header("sys/socket.h");
        cfg.header("sys/time.h");
        cfg.header("sys/un.h");
        cfg.header("sys/wait.h");
        cfg.header("unistd.h");
        cfg.header("utime.h");
        cfg.header("pwd.h");
        cfg.header("grp.h");
        cfg.header("sys/utsname.h");
        cfg.header("sys/ptrace.h");
        cfg.header("sys/mount.h");
        cfg.header("sys/uio.h");
        cfg.header("sched.h");
        cfg.header("termios.h");
        cfg.header("poll.h");
    }

    if android {
        cfg.header("arpa/inet.h");
        cfg.header("time64.h");
    } else if !windows {
        cfg.header("glob.h");
        cfg.header("ifaddrs.h");
        cfg.header("sys/statvfs.h");

        if !openbsd && !freebsd && !dragonfly {
            cfg.header("sys/quota.h");
        }

        if !musl {
            cfg.header("sys/sysctl.h");

            if !netbsd && !openbsd {
                cfg.header("execinfo.h");
            }
        }
    }

    if apple {
        cfg.header("mach-o/dyld.h");
        cfg.header("mach/mach_time.h");
        cfg.header("malloc/malloc.h");
        cfg.header("util.h");
        if target.starts_with("x86") {
            cfg.header("crt_externs.h");
        }
    }

    if bsdlike {
        cfg.header("sys/event.h");
    }

    if linux {
        cfg.header("mqueue.h");
        cfg.header("ucontext.h");
        cfg.header("sys/signalfd.h");
        cfg.header("sys/xattr.h");
        cfg.header("sys/ipc.h");
        cfg.header("sys/shm.h");
    }

    if linux || android {
        cfg.header("malloc.h");
        cfg.header("net/ethernet.h");
        cfg.header("netpacket/packet.h");
        cfg.header("sched.h");
        cfg.header("sys/epoll.h");
        cfg.header("sys/eventfd.h");
        cfg.header("sys/prctl.h");
        cfg.header("sys/sendfile.h");
        cfg.header("sys/vfs.h");
        cfg.header("sys/syscall.h");
        if !musl {
            cfg.header("linux/netlink.h");
            cfg.header("linux/magic.h");

            if !mips {
                cfg.header("linux/quota.h");
            }
        }
    }

    if freebsd {
        cfg.header("pthread_np.h");
        cfg.header("sched.h");
        cfg.header("ufs/ufs/quota.h");
    }

    if netbsd {
        cfg.header("ufs/ufs/quota.h");
        cfg.header("ufs/ufs/quota1.h");
        cfg.header("sys/ioctl_compat.h");
    }

    if openbsd {
        cfg.header("ufs/ufs/quota.h");
        cfg.header("rpcsvc/rex.h");
        cfg.header("pthread_np.h");
        cfg.header("sys/syscall.h");
    }

    if dragonfly {
        cfg.header("ufs/ufs/quota.h");
        cfg.header("pthread_np.h");
        cfg.header("sys/ioctl_compat.h");
    }

    cfg.type_name(move |ty, is_struct| {
        match ty {
            // Just pass all these through, no need for a "struct" prefix
            "FILE" |
            "fd_set" |
            "Dl_info" |
            "DIR" => ty.to_string(),

            // Fixup a few types on windows that don't actually exist.
            "time64_t" if windows => "__time64_t".to_string(),
            "ssize_t" if windows => "SSIZE_T".to_string(),

            // OSX calls this something else
            "sighandler_t" if bsdlike => "sig_t".to_string(),

            t if t.ends_with("_t") => t.to_string(),

            // Windows uppercase structs don't have `struct` in front, there's a
            // few special cases for windows, and then otherwise put `struct` in
            // front of everything.
            t if is_struct => {
                if windows && ty.chars().next().unwrap().is_uppercase() {
                    t.to_string()
                } else if windows && t == "stat" {
                    "struct __stat64".to_string()
                } else if windows && t == "utimbuf" {
                    "struct __utimbuf64".to_string()
                } else {
                    format!("struct {}", t)
                }
            }

            t => t.to_string(),
        }
    });

    let target2 = target.clone();
    cfg.field_name(move |struct_, field| {
        match field {
            "st_birthtime"      if openbsd && struct_ == "stat" => "__st_birthtime".to_string(),
            "st_birthtime_nsec" if openbsd && struct_ == "stat" => "__st_birthtimensec".to_string(),
            // Our stat *_nsec fields normally don't actually exist but are part
            // of a timeval struct
            s if s.ends_with("_nsec") && struct_.starts_with("stat") => {
                if target2.contains("apple") {
                    s.replace("_nsec", "spec.tv_nsec")
                } else if target2.contains("android") {
                    s.to_string()
                } else {
                    s.replace("e_nsec", ".tv_nsec")
                }
            }
            "u64" if struct_ == "epoll_event" => "data.u64".to_string(),
            s => s.to_string(),
        }
    });

    cfg.skip_type(move |ty| {
        match ty {
            // sighandler_t is crazy across platforms
            "sighandler_t" => true,

            _ => false
        }
    });

    cfg.skip_struct(move |ty| {
        match ty {
            "sockaddr_nl" => musl,

            // The alignment of this is 4 on 64-bit OSX...
            "kevent" if apple && x86_64 => true,

            _ => false
        }
    });

    cfg.skip_signededness(move |c| {
        match c {
            "LARGE_INTEGER" |
            "mach_timebase_info_data_t" |
            "float" |
            "double" => true,
            // uuid_t is a struct, not an integer.
            "uuid_t" if dragonfly => true,
            n if n.starts_with("pthread") => true,

            // windows-isms
            n if n.starts_with("P") => true,
            n if n.starts_with("H") => true,
            n if n.starts_with("LP") => true,
            _ => false,
        }
    });

    cfg.skip_const(move |name| {
        match name {
            // Apparently these don't exist in mingw headers?
            "MEM_RESET_UNDO" |
            "FILE_ATTRIBUTE_NO_SCRUB_DATA" |
            "FILE_ATTRIBUTE_INTEGRITY_STREAM" |
            "ERROR_NOTHING_TO_TERMINATE" if mingw => true,

            "SIG_IGN" => true, // sighandler_t weirdness

            // types on musl are defined a little differently
            n if musl && n.contains("__SIZEOF_PTHREAD") => true,

            // Skip constants not defined in MUSL but just passed down to the
            // kernel regardless
            "RLIMIT_NLIMITS" |
            "TCP_COOKIE_TRANSACTIONS" |
            "RLIMIT_RTTIME" if musl => true,
            // work around super old mips toolchain
            "SCHED_IDLE" | "SHM_NORESERVE" => mips,

            // weird signed extension or something like that?
            "MS_NOUSER" => true,

            // These OSX constants are flagged as deprecated
            "NOTE_EXIT_REPARENTED" |
            "NOTE_REAP" if apple => true,

            // The linux/quota.h header file which defines these can't be
            // included with sys/quota.h currently on MIPS, so we don't include
            // it and just ignore these constants
            "QFMT_VFS_OLD" |
            "QFMT_VFS_V0" if mips && linux => true,

            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        // skip those that are manually verified
        match name {
            "execv" |       // crazy stuff with const/mut
            "execve" |
            "execvp" |
            "execvpe" => true,

            "getrlimit" | "getrlimit64" |    // non-int in 1st arg
            "setrlimit" | "setrlimit64" |    // non-int in 1st arg
            "strerror_r" if linux => true,   // actually xpg-something-or-other

            // typed 2nd arg on linux and android
            "gettimeofday" if linux || android || freebsd || openbsd || dragonfly => true,

            // not declared in newer android toolchains
            "getdtablesize" if android => true,

            "dlerror" if android => true, // const-ness is added
            "dladdr" if musl => true, // const-ness only added recently

            // OSX has 'struct tm *const' which we can't actually represent in
            // Rust, but is close enough to *mut
            "timegm" if apple => true,

            // OSX's daemon is deprecated in 10.5 so we'll get a warning (which
            // we turn into an error) so just ignore it.
            "daemon" if apple => true,

            // These functions presumably exist on netbsd but don't look like
            // they're implemented on rumprun yet, just let them slide for now.
            // Some of them look like they have headers but then don't have
            // corresponding actual definitions either...
            "shm_open" |
            "shm_unlink" |
            "syscall" |
            "ptrace" |
            "sigaltstack" if rumprun => true,

            // There seems to be a small error in EGLIBC's eventfd.h header. The
            // [underlying system call][1] always takes its first `count`
            // argument as an `unsigned int`, but [EGLIBC's <sys/eventfd.h>
            // header][2] declares it to take an `int`. [GLIBC's header][3]
            // matches the kernel.
            //
            // EGLIBC is no longer actively developed, and Debian, the largest
            // distribution that had been using it, switched back to GLIBC in
            // April 2015. So effectively all Linux <sys/eventfd.h> headers will
            // be using `unsigned int` soon.
            //
            // [1]: https://git.kernel.org/cgit/linux/kernel/git/stable/linux-stable.git/tree/fs/eventfd.c?id=refs/tags/v3.12.51#n397
            // [2]: http://bazaar.launchpad.net/~ubuntu-branches/ubuntu/trusty/eglibc/trusty/view/head:/sysdeps/unix/sysv/linux/sys/eventfd.h
            // [3]: https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/sys/eventfd.h;h=6295f32e937e779e74318eb9d3bdbe76aef8a8f3;hb=4e42b5b8f89f0e288e68be7ad70f9525aebc2cff#l34
            "eventfd" if linux => true,

            // The `uname` funcion in freebsd is now an inline wrapper that
            // delegates to another, but the symbol still exists, so don't check
            // the symbol.
            "uname" if freebsd => true,

            _ => false,
        }
    });

    cfg.skip_fn_ptrcheck(move |name| {
        match name {
            // dllimport weirdness?
            _ if windows => true,

            _ => false,
        }
    });

    cfg.skip_field_type(move |struct_, field| {
        // This is a weird union, don't check the type.
        (struct_ == "ifaddrs" && field == "ifa_ifu") ||
        // sighandler_t type is super weird
        (struct_ == "sigaction" && field == "sa_sigaction")
    });

    cfg.skip_field(move |struct_, field| {
        // this is actually a union on linux, so we can't represent it well and
        // just insert some padding.
        (struct_ == "siginfo_t" && field == "_pad") ||
        // musl names this __dummy1 but it's still there
        (musl && struct_ == "glob_t" && field == "gl_flags") ||
        // musl seems to define this as an *anonymous* bitfield
        (musl && struct_ == "statvfs" && field == "__f_unused")
    });

    cfg.fn_cname(move |name, cname| {
        if windows {
            cname.unwrap_or(name).to_string()
        } else {
            name.to_string()
        }
    });

    if env::var("SKIP_COMPILE").is_ok() {
        cfg.generate_files("../src/lib.rs", "all.rs");
    } else {
        cfg.generate("../src/lib.rs", "all.rs");
    }
}
<|endoftext|>


<commit_before>#[cfg(windows)]
extern crate winapi;

#[cfg(not(windows))]
extern crate psutil;

pub trait ProcAccessor {
    type Item;

    fn enum_processes() -> std::io::Result<Vec<Self::Item>>;
    fn find_process_by_name(process_name : &str) -> Option<Self::Item>;

    fn get_process_name(&self) -> std::io::Result<String>;
}

pub mod sys {

    #[cfg(windows)]
    pub type Proc = crate::process_util::WinProc;
    #[cfg(not(windows))]
    pub type Proc = crate::process_util::LinProc;
}

#[cfg(windows)]
pub struct WinProc {
    pid : u32
}

#[cfg(windows)]
impl WinProc {
    fn str_to_wide(msg : &str) -> Vec<u16> {
        use std::os::windows::ffi::OsStrExt;

        std::ffi::OsStr::new(msg).encode_wide().chain(std::iter::once(0)).collect()
    }

    fn message_box(msg : &str) -> Result<(), std::io::Error> {
        use winapi::um::winuser::{MessageBoxW, MB_OK};

        let msg_wide = Self::str_to_wide(msg);
        let ret = unsafe {
            MessageBoxW(std::ptr::null_mut(), msg_wide.as_ptr(), msg_wide.as_ptr(), MB_OK)
        };

        if ret == 0 {
            Err(std::io::Error::last_os_error())
        }
        else {
            Ok(())
        }
    }
}

#[cfg(windows)]
impl ProcAccessor for WinProc {
    type Item = WinProc;

    fn enum_processes() -> std::io::Result<Vec<Self::Item>> {
        use winapi::shared::minwindef::DWORD;
        use winapi::um::psapi::EnumProcesses;

        let mut lpid_processes : [DWORD; 8192] = [0; 8192];
        let mut cb : DWORD = 8192 * std::mem::size_of::<DWORD>() as u32;

        let count = unsafe {
            let lpcb_needed : *mut DWORD = &mut cb;
            EnumProcesses(lpid_processes.as_mut_ptr(), cb, lpcb_needed as *mut DWORD)
        };
        if count == 0 {
            return Err(std::io::Error::last_os_error());
        }

        let mut ret : Vec<Self::Item> = Default::default();
        for process_id in lpid_processes.iter() {
            if *process_id != 0 {
                ret.push(WinProc{ pid: *process_id });
            }
        }

        Ok(ret)
    }

    fn get_process_name(&self) -> std::io::Result<String> {
        use winapi::um::processthreadsapi::OpenProcess;
        use winapi::um::psapi::{EnumProcessModules, GetModuleBaseNameW};
        use winapi::um::winnt::{PROCESS_QUERY_INFORMATION, PROCESS_VM_READ};
        use winapi::shared::minwindef::{FALSE, HMODULE, DWORD};
        use winapi::shared::ntdef::NULL;

        // open process handle
        let h_process = unsafe {
            OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, self.pid)
        };
        if h_process == NULL {
            return Err(std::io::Error::last_os_error());
        }

        // find a module from process
        /*
        let mut h_module : HMODULE = std::ptr::null_mut();
        let mut cb : DWORD = 1;

        let ret = unsafe {
            let cb_needed : *mut DWORD = &mut cb;
            EnumProcessModules(h_process, h_module as *mut HMODULE, cb, cb_needed as *mut DWORD)
        };
        if ret == FALSE {
            return Err(std::io::Error::last_os_error());
        }
        */

        // get base name
        let mut base_name : [u16; 1024] = [0; 1024];

        let name_len = unsafe {
            //GetModuleBaseNameW(h_process, h_module, base_name.as_mut_ptr() as *mut u16, 1024)
            GetModuleBaseNameW(h_process, std::ptr::null_mut() as HMODULE, base_name.as_mut_ptr() as *mut u16, 1024)
        };
        if name_len == 0 {
            return Err(std::io::Error::last_os_error());
        }

        Ok(String::from_utf16_lossy(&base_name[0..name_len as usize]))
    }

    fn find_process_id_by_name(process_name : &str) -> Option<Self::Item> {
        let proc_vec = match Self::enum_processes() {
            Err(_) => { return None; },
            Ok(v) => v
        };

        for proc in proc_vec {
            let pname = match proc.get_process_name() {
                Err(_) => { continue },
                Ok(s) => s.to_ascii_lowercase()
            };

            if pname == process_name.to_ascii_lowercase() {
                return Some(proc);
            }
        }

        None
    }
}

#[cfg(not(windows))]
pub struct LinProc {
    process: psutil::process::Process
}

#[cfg(not(windows))]
impl ProcAccessor for LinProc {
    type Item = LinProc;

    fn enum_processes() -> std::io::Result<Vec<Self::Item>> {
        use psutil::process;
        let mut all_procs : Vec<psutil::process::Process> = psutil::process::all()?;

        let mut ret : Vec<Self::Item> = Default::default();
        for process in all_procs {
            ret.push(LinProc { process: process });
        }

        Ok(ret)
    }

    fn find_process_by_name(process_name : &str) -> Option<Self::Item> {
        use psutil::process;
        let mut all_procs : Vec<psutil::process::Process> = match psutil::process::all() {
            Ok(procs) => procs,
            Err(e) => return None
        };

        for process in all_procs {
            if process.comm.to_ascii_lowercase() == process_name.to_ascii_lowercase() {
                return Some(LinProc { process : process });
            }
        }

        None
    }

    fn get_process_name(&self) -> std::io::Result<String> {
        Ok(self.process.comm.clone())
    }
}

<commit_msg>fix process_util.rs compilation error in windows<commit_after>#[cfg(windows)]
extern crate winapi;

#[cfg(not(windows))]
extern crate psutil;

pub trait ProcAccessor {
    type Item;

    fn enum_processes() -> std::io::Result<Vec<Self::Item>>;
    fn find_process_by_name(process_name : &str) -> Option<Self::Item>;

    fn get_process_name(&self) -> std::io::Result<String>;
}

pub mod sys {

    #[cfg(windows)]
    pub type Proc = crate::process_util::WinProc;
    #[cfg(not(windows))]
    pub type Proc = crate::process_util::LinProc;
}

#[cfg(windows)]
pub struct WinProc {
    pid : u32
}

#[cfg(windows)]
impl WinProc {
    fn str_to_wide(msg : &str) -> Vec<u16> {
        use std::os::windows::ffi::OsStrExt;

        std::ffi::OsStr::new(msg).encode_wide().chain(std::iter::once(0)).collect()
    }

    fn message_box(msg : &str) -> Result<(), std::io::Error> {
        use winapi::um::winuser::{MessageBoxW, MB_OK};

        let msg_wide = Self::str_to_wide(msg);
        let ret = unsafe {
            MessageBoxW(std::ptr::null_mut(), msg_wide.as_ptr(), msg_wide.as_ptr(), MB_OK)
        };

        if ret == 0 {
            Err(std::io::Error::last_os_error())
        }
        else {
            Ok(())
        }
    }
}

#[cfg(windows)]
impl ProcAccessor for WinProc {
    type Item = WinProc;

    fn enum_processes() -> std::io::Result<Vec<Self::Item>> {
        use winapi::shared::minwindef::DWORD;
        use winapi::um::psapi::EnumProcesses;

        let mut lpid_processes : [DWORD; 8192] = [0; 8192];
        let mut cb : DWORD = 8192 * std::mem::size_of::<DWORD>() as u32;

        let count = unsafe {
            let lpcb_needed : *mut DWORD = &mut cb;
            EnumProcesses(lpid_processes.as_mut_ptr(), cb, lpcb_needed as *mut DWORD)
        };
        if count == 0 {
            return Err(std::io::Error::last_os_error());
        }

        let mut ret : Vec<Self::Item> = Default::default();
        for process_id in lpid_processes.iter() {
            if *process_id != 0 {
                ret.push(WinProc{ pid: *process_id });
            }
        }

        Ok(ret)
    }

    fn get_process_name(&self) -> std::io::Result<String> {
        use winapi::um::processthreadsapi::OpenProcess;
        use winapi::um::psapi::{EnumProcessModules, GetModuleBaseNameW};
        use winapi::um::winnt::{PROCESS_QUERY_INFORMATION, PROCESS_VM_READ};
        use winapi::shared::minwindef::{FALSE, HMODULE, DWORD};
        use winapi::shared::ntdef::NULL;

        // open process handle
        let h_process = unsafe {
            OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, self.pid)
        };
        if h_process == NULL {
            return Err(std::io::Error::last_os_error());
        }

        // find a module from process
        /*
        let mut h_module : HMODULE = std::ptr::null_mut();
        let mut cb : DWORD = 1;

        let ret = unsafe {
            let cb_needed : *mut DWORD = &mut cb;
            EnumProcessModules(h_process, h_module as *mut HMODULE, cb, cb_needed as *mut DWORD)
        };
        if ret == FALSE {
            return Err(std::io::Error::last_os_error());
        }
        */

        // get base name
        let mut base_name : [u16; 1024] = [0; 1024];

        let name_len = unsafe {
            //GetModuleBaseNameW(h_process, h_module, base_name.as_mut_ptr() as *mut u16, 1024)
            GetModuleBaseNameW(h_process, std::ptr::null_mut() as HMODULE, base_name.as_mut_ptr() as *mut u16, 1024)
        };
        if name_len == 0 {
            return Err(std::io::Error::last_os_error());
        }

        Ok(String::from_utf16_lossy(&base_name[0..name_len as usize]))
    }

    fn find_process_by_name(process_name : &str) -> Option<Self::Item> {
        let proc_vec = match Self::enum_processes() {
            Err(_) => { return None; },
            Ok(v) => v
        };

        for proc in proc_vec {
            let pname = match proc.get_process_name() {
                Err(_) => { continue },
                Ok(s) => s.to_ascii_lowercase()
            };

            if pname == process_name.to_ascii_lowercase() {
                return Some(proc);
            }
        }

        None
    }
}

#[cfg(not(windows))]
pub struct LinProc {
    process: psutil::process::Process
}

#[cfg(not(windows))]
impl ProcAccessor for LinProc {
    type Item = LinProc;

    fn enum_processes() -> std::io::Result<Vec<Self::Item>> {
        use psutil::process;
        let mut all_procs : Vec<psutil::process::Process> = psutil::process::all()?;

        let mut ret : Vec<Self::Item> = Default::default();
        for process in all_procs {
            ret.push(LinProc { process: process });
        }

        Ok(ret)
    }

    fn find_process_by_name(process_name : &str) -> Option<Self::Item> {
        use psutil::process;
        let mut all_procs : Vec<psutil::process::Process> = match psutil::process::all() {
            Ok(procs) => procs,
            Err(e) => return None
        };

        for process in all_procs {
            if process.comm.to_ascii_lowercase() == process_name.to_ascii_lowercase() {
                return Some(LinProc { process : process });
            }
        }

        None
    }

    fn get_process_name(&self) -> std::io::Result<String> {
        Ok(self.process.comm.clone())
    }
}

<|endoftext|>


<commit_before>use std::io;
use std::io::Cursor;

use msgpack::core::*;
use msgpack::core::decode::*;
use msgpack::core::encode::*;

#[test]
fn from_nil() {
    let buf: &[u8] = &[0xc0];
    let mut cur = Cursor::new(buf);

    assert_eq!((), read_nil(&mut cur).unwrap());
    assert_eq!(1, cur.position());
}

#[test]
fn from_nil_invalid_marker() {
    let buf: &[u8] = &[0xc1];
    let mut cur = Cursor::new(buf);

    assert_eq!(Error::TypeMismatch(Marker::Reserved),
        read_nil(&mut cur).err().unwrap());
    assert_eq!(1, cur.position());
}

#[test]
fn from_nil_invalid_marker_read() {
    let buf: &[u8] = &[];
    let mut cur = Cursor::new(buf);

    assert_eq!(Error::InvalidMarkerRead(ReadError::UnexpectedEOF),
        read_nil(&mut cur).err().unwrap());
    assert_eq!(0, cur.position());
}

#[test]
fn pass_pack() {
    let mut buf = [0x00];

    assert_eq!(1, write_nil(&mut &mut buf[..]).unwrap());
    assert_eq!([0xc0], buf);
}

#[test]
fn fail_pack_too_small_buffer() {
    let mut buf = [];

    assert_eq!(Error::InvalidMarkerWrite(WriteError::IO(io::Error::new(io::ErrorKind::WriteZero, ""))),
        write_nil(&mut &mut buf[..]).err().unwrap());
}
<commit_msg>[UT] Naming.<commit_after>use std::io;
use std::io::Cursor;

use msgpack::core::*;
use msgpack::core::decode::*;
use msgpack::core::encode::*;

#[test]
fn pass_read_nil() {
    let buf: &[u8] = &[0xc0];
    let mut cur = Cursor::new(buf);

    assert_eq!((), read_nil(&mut cur).unwrap());
    assert_eq!(1, cur.position());
}

#[test]
fn fail_read_nil_invalid_marker() {
    let buf: &[u8] = &[0xc1];
    let mut cur = Cursor::new(buf);

    assert_eq!(Error::TypeMismatch(Marker::Reserved),
        read_nil(&mut cur).err().unwrap());
    assert_eq!(1, cur.position());
}

#[test]
fn fail_read_nil_invalid_marker_read() {
    let buf: &[u8] = &[];
    let mut cur = Cursor::new(buf);

    assert_eq!(Error::InvalidMarkerRead(ReadError::UnexpectedEOF),
        read_nil(&mut cur).err().unwrap());
    assert_eq!(0, cur.position());
}

#[test]
fn pass_pack() {
    let mut buf = [0x00];

    assert_eq!(1, write_nil(&mut &mut buf[..]).unwrap());
    assert_eq!([0xc0], buf);
}

#[test]
fn fail_pack_too_small_buffer() {
    let mut buf = [];

    assert_eq!(Error::InvalidMarkerWrite(WriteError::IO(io::Error::new(io::ErrorKind::WriteZero, ""))),
        write_nil(&mut &mut buf[..]).err().unwrap());
}
<|endoftext|>


<commit_before>extern crate translator;

extern crate piston;
extern crate piston_window;
#[macro_use]
extern crate conrod;
extern crate find_folder;

use piston_window::{PistonWindow, WindowSettings, Glyphs, UpdateEvent};
use piston::event_loop::EventLoop;
use conrod::{Theme, Ui, Canvas, TextBox, Widget, Sizeable, Positionable};
use conrod::color::{self, Colorable};

fn main() {
    let window: PistonWindow = WindowSettings::new("Hello Conrod", [800, 600])
                                   .exit_on_esc(true)
                                   .vsync(true)
                                   .build()
                                   .unwrap();

    let mut ui = {
        let assets_path = find_folder::Search::KidsThenParents(3, 5).for_folder("assets").unwrap();
        let font_path = assets_path.join("NotoSans-Regular.ttf");
        let theme = Theme::default();
        let glyph_cache = Glyphs::new(&font_path, window.factory.borrow().clone());
        Ui::new(glyph_cache.unwrap(), theme)
    };

    for w in window.ups(60) {
        ui.handle_event(&w);

        w.update(|_| {
            ui.set_widgets(|ui| {
                let background_color = color::rgb(0.2, 0.35, 0.45);
                let mut text = "".to_owned();

                // TODO: Use frame width for text boxes.
                // TODO: Use separate text-string.3
                Canvas::new()
                    .pad(30.)
                    .color(background_color)
                    .scroll_kids()
                    .set(CANVAS, ui);

                TextBox::new(&mut text)
                    .font_size(20)
                    .w_h(420.0, 40.0)
                    .mid_left_of(CANVAS)
                    .color(background_color.invert())
                    .react(|_string: &mut String| {})
                    .set(INPUT_TEXT, ui);

                TextBox::new(&mut text)
                    .font_size(20)
                    .w_h(420.0, 40.0)
                    .down_from(INPUT_TEXT, 45.0)
                    .color(background_color.invert())
                    .react(|_string: &mut String| {})
                    .set(OUTPUT_TEXT, ui);
            })
        });

        w.draw_2d(|context, graphic| ui.draw_if_changed(context, graphic));
    }
}

widget_ids! {
    CANVAS,
    INPUT_TEXT,
    OUTPUT_TEXT,
}
<commit_msg>Separate text-string<commit_after>extern crate translator;

extern crate piston;
extern crate piston_window;
#[macro_use]
extern crate conrod;
extern crate find_folder;

use piston_window::{PistonWindow, WindowSettings, Glyphs, UpdateEvent};
use piston::event_loop::EventLoop;
use conrod::{Theme, Ui, Canvas, TextBox, Widget, Sizeable, Positionable};
use conrod::color::{self, Colorable};

fn main() {
    let window: PistonWindow = WindowSettings::new("Hello Conrod", [800, 600])
                                   .exit_on_esc(true)
                                   .vsync(true)
                                   .build()
                                   .unwrap();

    let mut ui = {
        let assets_path = find_folder::Search::KidsThenParents(3, 5).for_folder("assets").unwrap();
        let font_path = assets_path.join("NotoSans-Regular.ttf");
        let theme = Theme::default();
        let glyph_cache = Glyphs::new(&font_path, window.factory.borrow().clone());
        Ui::new(glyph_cache.unwrap(), theme)
    };

    let mut original_text = "".to_owned();
    let mut translated_text = "".to_owned();

    for w in window.ups(60) {
        ui.handle_event(&w);

        w.update(|_| {
            ui.set_widgets(|ui| {
                let background_color = color::rgb(0.2, 0.35, 0.45);

                // TODO: Use frame width for text boxes.
                Canvas::new()
                    .pad(30.)
                    .color(background_color)
                    .scroll_kids()
                    .set(CANVAS, ui);

                TextBox::new(&mut original_text)
                    .font_size(20)
                    .w_h(420.0, 40.0)
                    .mid_left_of(CANVAS)
                    .color(background_color.invert())
                    .react(|_string: &mut String| {})
                    .set(INPUT_TEXT, ui);

                TextBox::new(&mut translated_text)
                    .font_size(20)
                    .w_h(420.0, 40.0)
                    .down_from(INPUT_TEXT, 45.0)
                    .color(background_color.invert())
                    .react(|_string: &mut String| {})
                    .set(OUTPUT_TEXT, ui);
            })
        });

        w.draw_2d(|context, graphic| ui.draw_if_changed(context, graphic));
    }
}

widget_ids! {
    CANVAS,
    INPUT_TEXT,
    OUTPUT_TEXT,
}
<|endoftext|>


<commit_before>use super::utils::types::{ Sha256Digest };
use super::blake2::{ Blake2s, Digest };
use super::config::Config;

// Interprets a 3-byte slice from a [u8] as an integer.
fn get_shift_from_source(source: &[u8], offset: usize) -> u32 {
    (source[offset + 2] as u32) |
        ((source[offset + 1] as u32) << 8) |
        ((source[offset    ] as u32) << 16)
}

// Given entropy in the form of `seed`, return a shuffled list of validators
// of size `validator_count` or `sample`.
pub fn get_shuffling(
    seed: Sha256Digest,
    validator_count: u32,
    sample: Option<u32>,
    config: Config)
    -> Vec<u32>
{
    let max_validators = config.max_validators;
    assert!(validator_count <= max_validators);

    // TODO: figure out why the Python implementation uses
    // this `rand_max` var.
    // let rand_max = max_validators - (max_validators % validator_count);
    let validator_range = match sample {
        Some(x) => x,
        None => validator_count
    };
    let mut output: Vec<u32> = (0..validator_range).collect();
    let mut source = Blake2s::new();
    source.input(&seed);

    let mut v = 0;
    while v < validator_range {
        let current_source = source.result();
        let mut source_offset = 0;
        while source_offset < 30 {
            let m = get_shift_from_source(&current_source, source_offset);
            let shuffled_position = (m % (validator_count - v)) + v;
            output.swap(v as usize, shuffled_position as usize);
            v += 1;
            if v >= validator_count { break; }
            source_offset += 3;
        }
        // Re-hash the source
        source = Blake2s::new();
        source.input(&current_source);
    }
    output
}

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

    #[test]
    fn test_shuffling_shift_fn() {
        let mut x = get_shift_from_source(
            &vec![0_u8, 0, 1],
            0);
        assert_eq!((x as u32), 1);

        x = get_shift_from_source(
            &vec![0_u8, 1, 1],
            0);
        assert_eq!(x, 257);

        x = get_shift_from_source(
            &vec![1_u8, 1, 1],
            0);
        assert_eq!(x, 65793);

        x = get_shift_from_source(
            &vec![255_u8, 1, 1],
            0);
        assert_eq!(x, 16711937);
    }

    #[test]
    fn test_shuffling() {
        let s = get_shuffling(
            Sha256Digest::zero(),
            10,
            None,
            Config::standard());
        assert_eq!(s,
                   vec!(0, 9, 7, 6, 4, 1, 8, 5, 2, 3),
                   "10 validator shuffle was not as expected");
    }

    #[test]
    fn test_shuffling_with_gt_half_max_validators() {
        let mut config = Config::standard();
        config.max_validators = 19;
        let s = get_shuffling(
            Sha256Digest::zero(),
            10,
            None,
            Config::standard());
        assert_eq!(s,
                   vec!(0, 9, 7, 6, 4, 1, 8, 5, 2, 3),
                   "10 validator shuffle was not as expected");
    }
}
<commit_msg>Change get_shuffling to borrow<commit_after>use super::utils::types::{ Sha256Digest };
use super::blake2::{ Blake2s, Digest };
use super::config::Config;

// Interprets a 3-byte slice from a [u8] as an integer.
fn get_shift_from_source(source: &[u8], offset: usize) -> u32 {
    (source[offset + 2] as u32) |
        ((source[offset + 1] as u32) << 8) |
        ((source[offset    ] as u32) << 16)
}

// Given entropy in the form of `seed`, return a shuffled list of validators
// of size `validator_count` or `sample`.
pub fn get_shuffling(
    seed: &Sha256Digest,
    validator_count: &u32,
    sample: &Option<u32>,
    config: &Config)
    -> Vec<u32>
{
    let max_validators = config.max_validators;
    assert!(*validator_count <= max_validators);

    // TODO: figure out why the Python implementation uses
    // this `rand_max` var.
    // let rand_max = max_validators - (max_validators % validator_count);
    let validator_range = match sample {
        Some(x) => x,
        None => validator_count
    };
    let mut output: Vec<u32> = (0..*validator_range).collect();
    let mut source = Blake2s::new();
    source.input(&seed);

    let mut v = 0;
    while v < *validator_range {
        let current_source = source.result();
        let mut source_offset = 0;
        while source_offset < 30 {
            let m = get_shift_from_source(&current_source, source_offset);
            let shuffled_position = (m % (validator_count - v)) + v;
            output.swap(v as usize, shuffled_position as usize);
            v += 1;
            if v >= *validator_count { break; }
            source_offset += 3;
        }
        // Re-hash the source
        source = Blake2s::new();
        source.input(&current_source);
    }
    output
}

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

    #[test]
    fn test_shuffling_shift_fn() {
        let mut x = get_shift_from_source(
            &vec![0_u8, 0, 1],
            0);
        assert_eq!((x as u32), 1);

        x = get_shift_from_source(
            &vec![0_u8, 1, 1],
            0);
        assert_eq!(x, 257);

        x = get_shift_from_source(
            &vec![1_u8, 1, 1],
            0);
        assert_eq!(x, 65793);

        x = get_shift_from_source(
            &vec![255_u8, 1, 1],
            0);
        assert_eq!(x, 16711937);
    }

    #[test]
    fn test_shuffling() {
        let s = get_shuffling(
            &Sha256Digest::zero(),
            &10,
            &None,
            &Config::standard());
        assert_eq!(s,
                   vec!(0, 9, 7, 6, 4, 1, 8, 5, 2, 3),
                   "10 validator shuffle was not as expected");
    }

    #[test]
    fn test_shuffling_with_gt_half_max_validators() {
        let mut config = Config::standard();
        config.max_validators = 19;
        let s = get_shuffling(
            Sha256Digest::zero(),
            10,
            None,
            Config::standard());
        assert_eq!(s,
                   vec!(0, 9, 7, 6, 4, 1, 8, 5, 2, 3),
                   "10 validator shuffle was not as expected");
    }
}
<|endoftext|>


<commit_before>// Copyright 2014 Felix S. Klock II. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![crate_name="glm"]
#![crate_type = "lib"]

#![desc = "GLM port"]
#![license = "MIT"]

#![feature(macro_rules)]

extern crate test;

pub use src::typedefs::{vec1,vec2,vec3,vec4};
pub use src::typedefs::{dvec1,dvec2,dvec3,dvec4};
pub use src::typedefs::{bvec1,bvec2,bvec3,bvec4};
pub use src::typedefs::{ivec1,ivec2,ivec3,ivec4};
pub use src::typedefs::{uvec1,uvec2,uvec3,uvec4};

pub use src::typedefs::{mat2,mat3,mat4};
pub use src::typedefs::{mat2x2,mat2x3,mat2x4};
pub use src::typedefs::{mat3x2,mat3x3,mat3x4};
pub use src::typedefs::{mat4x2,mat4x3,mat4x4};

pub use src::vector::vec2;
pub use src::matrix::{mat2,mat2x2,mat2x3,mat2x4};
pub use src::matrix::{mat3,mat3x2,mat3x3,mat3x4};
pub use src::matrix::{mat4,mat4x2,mat4x3,mat4x4};
pub use src::matrix::inverse;

macro_rules! double_dispatch_T {
    ( $trait_:ident for $LHS_type:ident $method:ident via $RHS_trait:ident $rev_method:ident ) =>
    {
        pub trait $RHS_trait<T,RET> {
            fn $rev_method(&self, lhs: & $LHS_type<T>) -> RET;
        }

        impl<T,RET,RHS:$RHS_trait<T,RET>> $trait_<RHS,RET> for $LHS_type<T> {
            fn $method(&self, rhs: &RHS) -> RET { rhs.$rev_method(self) }
        }
    };
    ( $trait_:ident for mut $LHS_type:ident $method:ident via $RHS_trait:ident $rev_method:ident ) =>
    {
        pub trait $RHS_trait<T> {
            fn $rev_method(&self, lhs: &mut $LHS_type<T>);
        }

        impl<T,RHS:$RHS_trait<T>> $trait_<RHS> for $LHS_type<T> {
            fn $method(&mut self, rhs: &RHS) { rhs.$rev_method(self) }
        }
    };
}

macro_rules! all_choices {
    ( $m:ident :
      todo: {}
      done: { $( ( $($i:ident),* ) )* } ) =>
    {
        $( $m!( $($i),* ) )*
    };
    ( $m:ident :
      todo: { ($a:ident | $b:ident) $( ($p:ident | $q:ident) )* }
      done: { $( ( $($i:ident),* ) )* } ) =>
    {
        all_choices!( $m :
                      todo: { $( ( $p | $q ) )* }
                      done: { $( ( $a, $( $i ),* ) )* $( ( $b, $( $i ),* ) )* } )
    };
}

mod src {
    // all non-lib.rs files go into src/ subdirectory and are thus
    // listed here.

    pub mod typedefs;
    pub mod operators;
    pub mod matrix;
    pub mod vector;
    pub mod scalar;
}

/// This is to work around bugs in our reachability analysis that can
/// cause false lint-warnings (Issue #14421), or worse, link failures
/// (Issue #14422).
pub mod dont_use {
    pub use src::vector;
}
<commit_msg>Remove duplicate imports of typedefs already imported from `src::matrix`.<commit_after>// Copyright 2014 Felix S. Klock II. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![crate_name="glm"]
#![crate_type = "lib"]

#![desc = "GLM port"]
#![license = "MIT"]

#![feature(macro_rules)]

extern crate test;

pub use src::typedefs::{vec1,vec2,vec3,vec4};
pub use src::typedefs::{dvec1,dvec2,dvec3,dvec4};
pub use src::typedefs::{bvec1,bvec2,bvec3,bvec4};
pub use src::typedefs::{ivec1,ivec2,ivec3,ivec4};
pub use src::typedefs::{uvec1,uvec2,uvec3,uvec4};

pub use src::vector::vec2;
pub use src::matrix::{mat2,mat2x2,mat2x3,mat2x4};
pub use src::matrix::{mat3,mat3x2,mat3x3,mat3x4};
pub use src::matrix::{mat4,mat4x2,mat4x3,mat4x4};
pub use src::matrix::inverse;

macro_rules! double_dispatch_T {
    ( $trait_:ident for $LHS_type:ident $method:ident via $RHS_trait:ident $rev_method:ident ) =>
    {
        pub trait $RHS_trait<T,RET> {
            fn $rev_method(&self, lhs: & $LHS_type<T>) -> RET;
        }

        impl<T,RET,RHS:$RHS_trait<T,RET>> $trait_<RHS,RET> for $LHS_type<T> {
            fn $method(&self, rhs: &RHS) -> RET { rhs.$rev_method(self) }
        }
    };
    ( $trait_:ident for mut $LHS_type:ident $method:ident via $RHS_trait:ident $rev_method:ident ) =>
    {
        pub trait $RHS_trait<T> {
            fn $rev_method(&self, lhs: &mut $LHS_type<T>);
        }

        impl<T,RHS:$RHS_trait<T>> $trait_<RHS> for $LHS_type<T> {
            fn $method(&mut self, rhs: &RHS) { rhs.$rev_method(self) }
        }
    };
}

macro_rules! all_choices {
    ( $m:ident :
      todo: {}
      done: { $( ( $($i:ident),* ) )* } ) =>
    {
        $( $m!( $($i),* ) )*
    };
    ( $m:ident :
      todo: { ($a:ident | $b:ident) $( ($p:ident | $q:ident) )* }
      done: { $( ( $($i:ident),* ) )* } ) =>
    {
        all_choices!( $m :
                      todo: { $( ( $p | $q ) )* }
                      done: { $( ( $a, $( $i ),* ) )* $( ( $b, $( $i ),* ) )* } )
    };
}

mod src {
    // all non-lib.rs files go into src/ subdirectory and are thus
    // listed here.

    pub mod typedefs;
    pub mod operators;
    pub mod matrix;
    pub mod vector;
    pub mod scalar;
}

/// This is to work around bugs in our reachability analysis that can
/// cause false lint-warnings (Issue #14421), or worse, link failures
/// (Issue #14422).
pub mod dont_use {
    pub use src::vector;
}
<|endoftext|>


<commit_before>// Copyright 2015 Pierre Talbot (IRCAM)

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

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

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

pub use self::rust::*;

grammar! rust {

  integer
    = decimal

  decimal = sign? number integer_suffix? > make_decimal

  sign
    = "-" > make_minus_sign
    / "+" > make_plus_sign

  number = digits > make_number
  digits = digit+ (underscore* digit)* > concat

  integer_suffix
    = "u8" > make_u8
    / "u16" > make_u16
    / "u32" > make_u32
    / "u64" > make_u64
    / "usize" > make_usize
    / "i8" > make_i8
    / "i16" > make_i16
    / "i32" > make_i32
    / "i64" > make_i64
    / "isize" > make_isize

  digit = ["0-9"]
  underscore = "_" -> (^)

  pub use syntax::ast::*;
  use std::str::FromStr;

  fn concat(mut x: Vec<char>, y: Vec<char>) -> Vec<char> {
    x.extend(y.into_iter());
    x
  }

  fn make_u8() -> LitIntType { UnsignedIntLit(TyU8) }
  fn make_u16() -> LitIntType { UnsignedIntLit(TyU16) }
  fn make_u32() -> LitIntType { UnsignedIntLit(TyU32) }
  fn make_u64() -> LitIntType { UnsignedIntLit(TyU64) }
  fn make_usize() -> LitIntType { UnsignedIntLit(TyUs) }
  fn make_i8() -> LitIntType { SignedIntLit(TyI8, Sign::Plus) }
  fn make_i16() -> LitIntType { SignedIntLit(TyI16, Sign::Plus) }
  fn make_i32() -> LitIntType { SignedIntLit(TyI32, Sign::Plus) }
  fn make_i64() -> LitIntType { SignedIntLit(TyI64, Sign::Plus) }
  fn make_isize() -> LitIntType { SignedIntLit(TyIs, Sign::Plus) }

  fn make_minus_sign() -> Sign { Sign::Minus }
  fn make_plus_sign() -> Sign { Sign::Plus }

  fn make_decimal(sign: Option<Sign>, number: u64, suffix: Option<LitIntType>) -> Lit_ {
    let sign = sign.unwrap_or(Sign::Plus);
    let ty = match suffix {
      None => UnsuffixedIntLit(sign),
      Some(SignedIntLit(ty, _)) => SignedIntLit(ty, sign),
      Some(UnsignedIntLit(_)) if sign == Sign::Minus => {
        panic!("unary negation of unsigned integers is forbidden.");
      },
      Some(x) => x
    };
    Lit_::LitInt(number, ty)
  }

  fn make_number(raw_number: Vec<char>) -> u64 {
    match u64::from_str(&*to_string(raw_number)).ok() {
      Some(x) => x,
      None => panic!("int literal is too large")
    }
  }

  fn to_string(raw_text: Vec<char>) -> String {
    raw_text.into_iter().collect()
  }
}

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

  #[test]
  fn integer_success_tests() {
    assert_eq!(parse_integer("123i32".stream()).unwrap_data(),
      Lit_::LitInt(123u64, LitIntType::SignedIntLit(IntTy::TyI32, Sign::Plus)));
    assert_eq!(parse_integer("-123i32".stream()).unwrap_data(),
      Lit_::LitInt(123u64, LitIntType::SignedIntLit(IntTy::TyI32, Sign::Minus)));
    // Overflows are checked by lints.
    assert_eq!(parse_integer("1000i8".stream()).unwrap_data(),
      Lit_::LitInt(1000u64, LitIntType::SignedIntLit(IntTy::TyI8, Sign::Plus)));
    assert_eq!(parse_integer("123_123_123i32".stream()).unwrap_data(),
      Lit_::LitInt(123123123u64, LitIntType::SignedIntLit(IntTy::TyI32, Sign::Plus)));
    assert_eq!(parse_integer("123".stream()).unwrap_data(),
      Lit_::LitInt(123u64, LitIntType::UnsuffixedIntLit(Sign::Plus)));
    assert_eq!(parse_integer("123u32".stream()).unwrap_data(),
      Lit_::LitInt(123u64, LitIntType::UnsignedIntLit(UintTy::TyU32)));
  }

  #[test]
  #[should_panic]
  fn too_large_integer() {
    parse_integer("10000000000000000000000".stream());
  }

  #[test]
  #[should_panic]
  fn negation_signed_integer() {
    parse_integer("-10000u8".stream());
  }
}
<commit_msg>[Grammars] Add identifier and Rust keyword.<commit_after>// Copyright 2015 Pierre Talbot (IRCAM)

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

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

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

pub use self::rust::*;

grammar! rust {

  identifier = !digit !keyword ident_char+ spacing > to_string
  ident_char = ["a-zA-Z0-9_"]

  keyword
    = strict_keyword kw_tail
    / reserved_keyword kw_tail

  kw_tail = !ident_char spacing

  special_idents
    = "self"
    / "static"
    / "super"
    / "'static"
    // for matcher NTs
    / "tt"
    / "matchers"
    // outside of libsyntax
    / "__rust_abi"
    / "<opaque>"
    / "<unnamed_field>"
    / "Self"
    / "prelude_import"

  strict_keyword
    = "as"
    / "break"
    / "crate"
    / "else"
    / "enum"
    / "extern"
    / "false"
    / "fn"
    / "for"
    / "if"
    / "impl"
    / "in"
    / "let"
    / "loop"
    / "match"
    / "mod"
    / "move"
    / "mut"
    / "pub"
    / "ref"
    / "return"
    // Static and Self are also special idents (prefill de-dupes)
    / "static"
    / "self"
    / "Self"
    / "struct"
    / "super"
    / "true"
    / "trait"
    / "type"
    / "unsafe"
    / "use"
    / "while"
    / "continue"
    / "box"
    / "const"
    / "where"

  reserved_keyword
    = "virtual"
    / "proc"
    / "alignof"
    / "become"
    / "offsetof"
    / "priv"
    / "pure"
    / "sizeof"
    / "typeof"
    / "unsized"
    / "yield"
    / "do"
    / "abstract"
    / "final"
    / "override"
    / "macro"

  integer
    = decimal

  decimal = sign? number integer_suffix? > make_decimal

  sign
    = "-" > make_minus_sign
    / "+" > make_plus_sign

  number = digits > make_number
  digits = digit+ (underscore* digit)* > concat

  integer_suffix
    = "u8" > make_u8
    / "u16" > make_u16
    / "u32" > make_u32
    / "u64" > make_u64
    / "usize" > make_usize
    / "i8" > make_i8
    / "i16" > make_i16
    / "i32" > make_i32
    / "i64" > make_i64
    / "isize" > make_isize

  digit = ["0-9"]
  underscore = "_" -> (^)
  spacing = [" \n\r\t"]* -> ()

  pub use syntax::ast::*;
  use std::str::FromStr;

  fn concat(mut x: Vec<char>, y: Vec<char>) -> Vec<char> {
    x.extend(y.into_iter());
    x
  }

  fn make_u8() -> LitIntType { UnsignedIntLit(TyU8) }
  fn make_u16() -> LitIntType { UnsignedIntLit(TyU16) }
  fn make_u32() -> LitIntType { UnsignedIntLit(TyU32) }
  fn make_u64() -> LitIntType { UnsignedIntLit(TyU64) }
  fn make_usize() -> LitIntType { UnsignedIntLit(TyUs) }
  fn make_i8() -> LitIntType { SignedIntLit(TyI8, Sign::Plus) }
  fn make_i16() -> LitIntType { SignedIntLit(TyI16, Sign::Plus) }
  fn make_i32() -> LitIntType { SignedIntLit(TyI32, Sign::Plus) }
  fn make_i64() -> LitIntType { SignedIntLit(TyI64, Sign::Plus) }
  fn make_isize() -> LitIntType { SignedIntLit(TyIs, Sign::Plus) }

  fn make_minus_sign() -> Sign { Sign::Minus }
  fn make_plus_sign() -> Sign { Sign::Plus }

  fn make_decimal(sign: Option<Sign>, number: u64, suffix: Option<LitIntType>) -> Lit_ {
    let sign = sign.unwrap_or(Sign::Plus);
    let ty = match suffix {
      None => UnsuffixedIntLit(sign),
      Some(SignedIntLit(ty, _)) => SignedIntLit(ty, sign),
      Some(UnsignedIntLit(_)) if sign == Sign::Minus => {
        panic!("unary negation of unsigned integers is forbidden.");
      },
      Some(x) => x
    };
    Lit_::LitInt(number, ty)
  }

  fn make_number(raw_number: Vec<char>) -> u64 {
    match u64::from_str(&*to_string(raw_number)).ok() {
      Some(x) => x,
      None => panic!("int literal is too large")
    }
  }

  fn to_string(raw_text: Vec<char>) -> String {
    raw_text.into_iter().collect()
  }
}

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

  #[test]
  fn integer_success_tests() {
    assert_eq!(parse_integer("123i32".stream()).unwrap_data(),
      Lit_::LitInt(123u64, LitIntType::SignedIntLit(IntTy::TyI32, Sign::Plus)));
    assert_eq!(parse_integer("-123i32".stream()).unwrap_data(),
      Lit_::LitInt(123u64, LitIntType::SignedIntLit(IntTy::TyI32, Sign::Minus)));
    // Overflows are checked by lints.
    assert_eq!(parse_integer("1000i8".stream()).unwrap_data(),
      Lit_::LitInt(1000u64, LitIntType::SignedIntLit(IntTy::TyI8, Sign::Plus)));
    assert_eq!(parse_integer("123_123_123i32".stream()).unwrap_data(),
      Lit_::LitInt(123123123u64, LitIntType::SignedIntLit(IntTy::TyI32, Sign::Plus)));
    assert_eq!(parse_integer("123".stream()).unwrap_data(),
      Lit_::LitInt(123u64, LitIntType::UnsuffixedIntLit(Sign::Plus)));
    assert_eq!(parse_integer("123u32".stream()).unwrap_data(),
      Lit_::LitInt(123u64, LitIntType::UnsignedIntLit(UintTy::TyU32)));
  }

  #[test]
  #[should_panic]
  fn too_large_integer() {
    parse_integer("10000000000000000000000".stream());
  }

  #[test]
  #[should_panic]
  fn negation_signed_integer() {
    parse_integer("-10000u8".stream());
  }

  #[test]
  fn identifier_test() {
    assert_eq!(parse_identifier("foo  ".stream()).unwrap_data(), "foo");
    assert_eq!(parse_identifier("let".stream()).is_successful(), false);
    assert_eq!(parse_identifier("leti".stream()).is_successful(), true);
    assert_eq!(parse_keyword("let  ".stream()).is_successful(), true);
  }
}
<|endoftext|>


<commit_before>// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::indices::{DataId, ElemId, MemId, TableId};
use crate::io::Wasmbin;
use crate::visit::Visit;
use arbitrary::Arbitrary;

#[crate::wasmbin_discriminants]
#[derive(Wasmbin, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[repr(u32)]
pub enum Misc {
    I32TruncSatF32S = 0x00,
    I32TruncSatF32U = 0x01,
    I32TruncSatF64S = 0x02,
    I32TruncSatF64U = 0x03,
    I64TruncSatF32S = 0x04,
    I64TruncSatF32U = 0x05,
    I64TruncSatF64S = 0x06,
    I64TruncSatF64U = 0x07,
    MemoryInit { data: DataId, mem: MemId } = 0x08,
    DataDrop(DataId) = 0x09,
    MemoryCopy { dest: MemId, src: MemId } = 0x0A,
    MemoryFill(MemId) = 0x0B,
    TableInit { elem: ElemId, table: TableId } = 0x0C,
    ElemDrop(ElemId) = 0x0D,
    TableCopy { dest: MemId, src: MemId } = 0x0E,
    TableGrow(TableId) = 0x0F,
    TableSize(TableId) = 0x10,
    TableFill(TableId) = 0x11,
}
<commit_msg>Fix TableCopy to use TableId<commit_after>// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::indices::{DataId, ElemId, MemId, TableId};
use crate::io::Wasmbin;
use crate::visit::Visit;
use arbitrary::Arbitrary;

#[crate::wasmbin_discriminants]
#[derive(Wasmbin, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[repr(u32)]
pub enum Misc {
    I32TruncSatF32S = 0x00,
    I32TruncSatF32U = 0x01,
    I32TruncSatF64S = 0x02,
    I32TruncSatF64U = 0x03,
    I64TruncSatF32S = 0x04,
    I64TruncSatF32U = 0x05,
    I64TruncSatF64S = 0x06,
    I64TruncSatF64U = 0x07,
    MemoryInit { data: DataId, mem: MemId } = 0x08,
    DataDrop(DataId) = 0x09,
    MemoryCopy { dest: MemId, src: MemId } = 0x0A,
    MemoryFill(MemId) = 0x0B,
    TableInit { elem: ElemId, table: TableId } = 0x0C,
    ElemDrop(ElemId) = 0x0D,
    TableCopy { dest: TableId, src: TableId } = 0x0E,
    TableGrow(TableId) = 0x0F,
    TableSize(TableId) = 0x10,
    TableFill(TableId) = 0x11,
}
<|endoftext|>


<commit_before>#[cfg(target_arch="x86")]
const B: [usize; 5]
    = [ 0x2, 0xC, 0xF0
      , 0xFF00
      , 0xFFFF0000];
#[cfg(target_arch="x86")]
const S: [usize; 5] = [ 1, 2, 4, 8, 16 ];

#[cfg(target_arch="x86_64")]
const B: [usize; 6]
    = [ 0x2, 0xC, 0xF0
      , 0xFF00, 0xFFFF0000
      , 0xFFFFFFFF00000000];

#[cfg(target_arch="x86_64")]
const S: [usize; 6] = [ 1, 2, 4, 8, 16, 32 ];

pub trait PowersOf2 {
    fn is_pow2(&self) -> bool;
    fn next_pow2(&self) -> Self;
    fn log2(&self) -> Self;
}

impl PowersOf2 for usize {
    fn is_pow2(&self) -> bool {
        *self != 0 && (self & (self - 1)) == 0
    }

    /// Returns the next power of 2
    fn next_pow2(&self) -> usize {
        let mut v = *self;
        if v == 0 {
            1
        } else {
            v -= 1;
            v = v | (v >> 1);
            v = v | (v >> 2);
            v = v | (v >> 4);
            v = v | (v >> 8);
            v = v | (v >> 16);
            v + 1
        }
    }

    #[cfg(not(any(target_arch="x86_64", target_arch="x86")))]
    fn log2(&self) -> usize {
        // This is the "obvious" log base 2 implementation. The lookup table
        // -based approach would be much faster, but we can't use it for
        // `usize` since we aren't sure what size a usize is without conditional
        // compilation.
        let mut res = 0;
        let mut num = *self >> 1;
        while num != 0 {
            res += 1;
            num >>= 1;
        }
        res
    }

    #[cfg(any(target_arch="x86_64", target_arch="x86"))]
    fn log2(&self) -> usize {
        let mut r: usize = 0;
        let mut v = *self;

        for i in (0..S.len()).rev() {
            if v & B[i] != 0 {
                v >>= S[i];
                r |=  S[i];
            }
        }
        r
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "bench")]
    use test::{self, Bencher};

    #[test]
    fn test_next_pow2() {
        assert_eq!(2usize.next_pow2(), 2);
        assert_eq!(0usize.next_pow2(), 1);
        assert_eq!(3usize.next_pow2(), 4);
        assert_eq!(5678usize.next_pow2(), 8192);
        assert_eq!(1,  0.next_pow2());
        assert_eq!(1,  1.next_pow2());
        assert_eq!(2,  2.next_pow2());
        assert_eq!(4,  3.next_pow2());
        assert_eq!(4,  4.next_pow2());
        assert_eq!(8,  5.next_pow2());
        assert_eq!(8,  8.next_pow2());
        assert_eq!(16, 9.next_pow2());
        assert_eq!(16, 16.next_pow2());
        assert_eq!(32, 17.next_pow2());
        assert_eq!(32, 32.next_pow2());
        assert_eq!(8388608, 8376263.next_pow2());
    }

    #[test]
    fn test_is_pow2() {
    assert_eq!(false, 0.is_pow2());
    assert_eq!(true,  1.is_pow2());
    assert_eq!(true,  2.is_pow2());
    assert_eq!(false, 3.is_pow2());
    assert_eq!(true,  4.is_pow2());
    assert_eq!(false, 255.is_pow2());
    assert_eq!(true,  256.is_pow2());
    assert_eq!(false, 257.is_pow2());
    assert_eq!(false, 4294967295.is_pow2());
    }

    #[test]
    fn test_log2() {
    assert_eq!(0, 0.log2());
    assert_eq!(0, 1.log2());
    assert_eq!(1, 2.log2());
    assert_eq!(5, 32.log2());
    assert_eq!(10, 1024.log2());
    }

    #[bench]
    fn our_next_pow2(b: &mut Bencher) {
        use collections::Vec;
        b.iter(|| {
            let n = test::black_box(10000);

            (0..n).map(|x: usize| x.next_pow2())
                  .collect::<Vec<_>>() // force the map to return so it doesn't get optimised away
        })
    }

    #[bench]
    fn std_next_power_of_two(b: &mut Bencher) {
        use collections::Vec;
        b.iter(|| {
            let n = test::black_box(10000);

            (0..n).map(|x: usize| x.next_power_of_two())
                  .collect::<Vec<_>>() // force the map to return so it doesn't get optimised away
        })
    }
}
<commit_msg>[alloc] add benchmarks for is_pow2<commit_after>#[cfg(target_arch="x86")]
const B: [usize; 5]
    = [ 0x2, 0xC, 0xF0
      , 0xFF00
      , 0xFFFF0000];
#[cfg(target_arch="x86")]
const S: [usize; 5] = [ 1, 2, 4, 8, 16 ];

#[cfg(target_arch="x86_64")]
const B: [usize; 6]
    = [ 0x2, 0xC, 0xF0
      , 0xFF00, 0xFFFF0000
      , 0xFFFFFFFF00000000];

#[cfg(target_arch="x86_64")]
const S: [usize; 6] = [ 1, 2, 4, 8, 16, 32 ];

pub trait PowersOf2 {
    fn is_pow2(&self) -> bool;
    fn next_pow2(&self) -> Self;
    fn log2(&self) -> Self;
}

impl PowersOf2 for usize {
    fn is_pow2(&self) -> bool {
        *self != 0 && (self & (self - 1)) == 0
    }

    /// Returns the next power of 2
    fn next_pow2(&self) -> usize {
        let mut v = *self;
        if v == 0 {
            1
        } else {
            v -= 1;
            v = v | (v >> 1);
            v = v | (v >> 2);
            v = v | (v >> 4);
            v = v | (v >> 8);
            v = v | (v >> 16);
            v + 1
        }
    }

    #[cfg(not(any(target_arch="x86_64", target_arch="x86")))]
    fn log2(&self) -> usize {
        // This is the "obvious" log base 2 implementation. The lookup table
        // -based approach would be much faster, but we can't use it for
        // `usize` since we aren't sure what size a usize is without conditional
        // compilation.
        let mut res = 0;
        let mut num = *self >> 1;
        while num != 0 {
            res += 1;
            num >>= 1;
        }
        res
    }

    #[cfg(any(target_arch="x86_64", target_arch="x86"))]
    fn log2(&self) -> usize {
        let mut r: usize = 0;
        let mut v = *self;

        for i in (0..S.len()).rev() {
            if v & B[i] != 0 {
                v >>= S[i];
                r |=  S[i];
            }
        }
        r
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "bench")]
    use test::{self, Bencher};

    #[test]
    fn test_next_pow2() {
        assert_eq!(2usize.next_pow2(), 2);
        assert_eq!(0usize.next_pow2(), 1);
        assert_eq!(3usize.next_pow2(), 4);
        assert_eq!(5678usize.next_pow2(), 8192);
        assert_eq!(1,  0.next_pow2());
        assert_eq!(1,  1.next_pow2());
        assert_eq!(2,  2.next_pow2());
        assert_eq!(4,  3.next_pow2());
        assert_eq!(4,  4.next_pow2());
        assert_eq!(8,  5.next_pow2());
        assert_eq!(8,  8.next_pow2());
        assert_eq!(16, 9.next_pow2());
        assert_eq!(16, 16.next_pow2());
        assert_eq!(32, 17.next_pow2());
        assert_eq!(32, 32.next_pow2());
        assert_eq!(8388608, 8376263.next_pow2());
    }

    #[test]
    fn test_is_pow2() {
    assert_eq!(false, 0.is_pow2());
    assert_eq!(true,  1.is_pow2());
    assert_eq!(true,  2.is_pow2());
    assert_eq!(false, 3.is_pow2());
    assert_eq!(true,  4.is_pow2());
    assert_eq!(false, 255.is_pow2());
    assert_eq!(true,  256.is_pow2());
    assert_eq!(false, 257.is_pow2());
    assert_eq!(false, 4294967295.is_pow2());
    }

    #[test]
    fn test_log2() {
    assert_eq!(0, 0.log2());
    assert_eq!(0, 1.log2());
    assert_eq!(1, 2.log2());
    assert_eq!(5, 32.log2());
    assert_eq!(10, 1024.log2());
    }

    #[bench]
    fn our_next_pow2(b: &mut Bencher) {
        use collections::Vec;
        b.iter(|| {
            let n = test::black_box(100_000);

            (0..n).map(|x: usize| x.next_pow2())
                  .collect::<Vec<_>>() // force the map to return so it doesn't get optimised away
        })
    }

    #[bench]
    fn std_next_power_of_two(b: &mut Bencher) {
        use collections::Vec;
        b.iter(|| {
            let n = test::black_box(100_000);

            (0..n).map(|x: usize| x.next_power_of_two())
                  .collect::<Vec<_>>() // force the map to return so it doesn't get optimised away
        })
    }

    #[bench]
    fn our_is_pow2(b: &mut Bencher) {
        use collections::Vec;
        b.iter(|| {
            let n = test::black_box(100_000);

            (0..n).map(|ref x: usize| x.is_pow2())
                  .collect::<Vec<_>>() // force the map to return so it doesn't get optimised away
        })
    }

    #[bench]
    fn std_is_power_of_two(b: &mut Bencher) {
        use collections::Vec;
        b.iter(|| {
            let n = test::black_box(100_000);

            (0..n).map(|x: usize| x.next_power_of_two())
                  .collect::<Vec<_>>() // force the map to return so it doesn't get optimised away
        })
    }
}
<|endoftext|>


<commit_before>// This file is part of the uutils coreutils package.
//
// (c) Derek Chiang <derekchiang93@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

#[macro_use]
extern crate uucore;

use clap::{crate_version, App, Arg};
use std::path::Path;
use uucore::error::{UResult, USimpleError};
use uucore::InvalidEncodingHandling;

static ABOUT: &str = "strip last component from file name";

mod options {
    pub const ZERO: &str = "zero";
    pub const DIR: &str = "dir";
}

fn get_usage() -> String {
    format!("{0} [OPTION] NAME...", executable!())
}

fn get_long_usage() -> String {
    String::from(
        "Output each NAME with its last non-slash component and trailing slashes
        removed; if NAME contains no /'s, output '.' (meaning the current directory).",
    )
}

#[uucore_procs::gen_uumain]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
    let args = args
        .collect_str(InvalidEncodingHandling::ConvertLossy)
        .accept_any();

    let usage = get_usage();
    let after_help = get_long_usage();

    let matches = uu_app()
        .usage(&usage[..])
        .after_help(&after_help[..])
        .get_matches_from(args);

    let separator = if matches.is_present(options::ZERO) {
        "\0"
    } else {
        "\n"
    };

    let dirnames: Vec<String> = matches
        .values_of(options::DIR)
        .unwrap_or_default()
        .map(str::to_owned)
        .collect();

    if !dirnames.is_empty() {
        for path in dirnames.iter() {
            let p = Path::new(path);
            match p.parent() {
                Some(d) => {
                    if d.components().next() == None {
                        print!(".")
                    } else {
                        print!("{}", d.to_string_lossy());
                    }
                }
                None => {
                    if p.is_absolute() || path == "/" {
                        print!("/");
                    } else {
                        print!(".");
                    }
                }
            }
            print!("{}", separator);
        }
    } else {
        return Err(USimpleError::new(1, format!("missing operand")));
    }

    Ok(())
}

pub fn uu_app() -> App<'static, 'static> {
    App::new(executable!())
        .about(ABOUT)
        .version(crate_version!())
        .arg(
            Arg::with_name(options::ZERO)
                .long(options::ZERO)
                .short("z")
                .help("separate output with NUL rather than newline"),
        )
        .arg(Arg::with_name(options::DIR).hidden(true).multiple(true))
}
<commit_msg>fix the clippy warning<commit_after>// This file is part of the uutils coreutils package.
//
// (c) Derek Chiang <derekchiang93@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

#[macro_use]
extern crate uucore;

use clap::{crate_version, App, Arg};
use std::path::Path;
use uucore::error::{UResult, USimpleError};
use uucore::InvalidEncodingHandling;

static ABOUT: &str = "strip last component from file name";

mod options {
    pub const ZERO: &str = "zero";
    pub const DIR: &str = "dir";
}

fn get_usage() -> String {
    format!("{0} [OPTION] NAME...", executable!())
}

fn get_long_usage() -> String {
    String::from(
        "Output each NAME with its last non-slash component and trailing slashes
        removed; if NAME contains no /'s, output '.' (meaning the current directory).",
    )
}

#[uucore_procs::gen_uumain]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
    let args = args
        .collect_str(InvalidEncodingHandling::ConvertLossy)
        .accept_any();

    let usage = get_usage();
    let after_help = get_long_usage();

    let matches = uu_app()
        .usage(&usage[..])
        .after_help(&after_help[..])
        .get_matches_from(args);

    let separator = if matches.is_present(options::ZERO) {
        "\0"
    } else {
        "\n"
    };

    let dirnames: Vec<String> = matches
        .values_of(options::DIR)
        .unwrap_or_default()
        .map(str::to_owned)
        .collect();

    if !dirnames.is_empty() {
        for path in dirnames.iter() {
            let p = Path::new(path);
            match p.parent() {
                Some(d) => {
                    if d.components().next() == None {
                        print!(".")
                    } else {
                        print!("{}", d.to_string_lossy());
                    }
                }
                None => {
                    if p.is_absolute() || path == "/" {
                        print!("/");
                    } else {
                        print!(".");
                    }
                }
            }
            print!("{}", separator);
        }
    } else {
        return Err(UUsageError::new(1, "missing operand".to_string()));
    }

    Ok(())
}

pub fn uu_app() -> App<'static, 'static> {
    App::new(executable!())
        .about(ABOUT)
        .version(crate_version!())
        .arg(
            Arg::with_name(options::ZERO)
                .long(options::ZERO)
                .short("z")
                .help("separate output with NUL rather than newline"),
        )
        .arg(Arg::with_name(options::DIR).hidden(true).multiple(true))
}
<|endoftext|>