<commit_before>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#[deriving(Eq, TotalEq)]
pub enum IpAddr {
    Ipv4(u8, u8, u8, u8, u16),
    Ipv6
}
<commit_msg>IPv6 struct<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

type Port = u16;

#[deriving(Eq, TotalEq)]
pub enum IpAddr {
    Ipv4(u8, u8, u8, u8, Port),
    Ipv6(u16, u16, u16, u16, u16, u16, u16, u16, Port)
}
<|endoftext|>


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

use core::prelude::*;
use io::prelude::*;
use os::unix::prelude::*;

use ffi::{self, CString, OsString, AsOsStr, OsStr};
use io::{self, Error, Seek, SeekFrom};
use libc::{self, c_int, c_void, size_t, off_t, c_char, mode_t};
use mem;
use path::{Path, PathBuf};
use ptr;
use rc::Rc;
use sys::fd::FileDesc;
use sys::{c, cvt, cvt_r};
use sys_common::FromInner;
use vec::Vec;

pub struct File(FileDesc);

pub struct FileAttr {
    stat: libc::stat,
}

pub struct ReadDir {
    dirp: *mut libc::DIR,
    root: Rc<PathBuf>,
}

pub struct DirEntry {
    buf: Vec<u8>,
    dirent: *mut libc::dirent_t,
    root: Rc<PathBuf>,
}

#[derive(Clone)]
pub struct OpenOptions {
    flags: c_int,
    read: bool,
    write: bool,
    mode: mode_t,
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FilePermissions { mode: mode_t }

impl FileAttr {
    pub fn is_dir(&self) -> bool {
        (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR
    }
    pub fn is_file(&self) -> bool {
        (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG
    }
    pub fn size(&self) -> u64 { self.stat.st_size as u64 }
    pub fn perm(&self) -> FilePermissions {
        FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
    }

    pub fn accessed(&self) -> u64 {
        self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64)
    }
    pub fn modified(&self) -> u64 {
        self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64)
    }

    // times are in milliseconds (currently)
    fn mktime(&self, secs: u64, nsecs: u64) -> u64 {
        secs * 1000 + nsecs / 1000000
    }
}

impl FilePermissions {
    pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
    pub fn set_readonly(&mut self, readonly: bool) {
        if readonly {
            self.mode &= !0o222;
        } else {
            self.mode |= 0o222;
        }
    }
}

impl FromInner<i32> for FilePermissions {
    fn from_inner(mode: i32) -> FilePermissions {
        FilePermissions { mode: mode as mode_t }
    }
}

impl Iterator for ReadDir {
    type Item = io::Result<DirEntry>;

    fn next(&mut self) -> Option<io::Result<DirEntry>> {
        extern {
            fn rust_dirent_t_size() -> c_int;
        }

        let mut buf: Vec<u8> = Vec::with_capacity(unsafe {
            rust_dirent_t_size() as usize
        });
        let ptr = buf.as_mut_ptr() as *mut libc::dirent_t;

        let mut entry_ptr = ptr::null_mut();
        loop {
            if unsafe { libc::readdir_r(self.dirp, ptr, &mut entry_ptr) != 0 } {
                return Some(Err(Error::last_os_error()))
            }
            if entry_ptr.is_null() {
                return None
            }

            let entry = DirEntry {
                buf: buf,
                dirent: entry_ptr,
                root: self.root.clone()
            };
            if entry.name_bytes() == b"." || entry.name_bytes() == b".." {
                buf = entry.buf;
            } else {
                return Some(Ok(entry))
            }
        }
    }
}

impl Drop for ReadDir {
    fn drop(&mut self) {
        let r = unsafe { libc::closedir(self.dirp) };
        debug_assert_eq!(r, 0);
    }
}

impl DirEntry {
    pub fn path(&self) -> PathBuf {
        self.root.join(<OsStr as OsStrExt>::from_byte_slice(self.name_bytes()))
    }

    fn name_bytes(&self) -> &[u8] {
        extern {
            fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char;
        }
        unsafe {
            let ptr = rust_list_dir_val(self.dirent);
            ffi::c_str_to_bytes(mem::copy_lifetime(self, &ptr))
        }
    }
}

impl OpenOptions {
    pub fn new() -> OpenOptions {
        OpenOptions {
            flags: 0,
            read: false,
            write: false,
            mode: libc::S_IRUSR | libc::S_IWUSR,
        }
    }

    pub fn read(&mut self, read: bool) {
        self.read = read;
    }

    pub fn write(&mut self, write: bool) {
        self.write = write;
    }

    pub fn append(&mut self, append: bool) {
        self.flag(libc::O_APPEND, append);
    }

    pub fn truncate(&mut self, truncate: bool) {
        self.flag(libc::O_TRUNC, truncate);
    }

    pub fn create(&mut self, create: bool) {
        self.flag(libc::O_CREAT, create);
    }

    pub fn mode(&mut self, mode: i32) {
        self.mode = mode as mode_t;
    }

    fn flag(&mut self, bit: c_int, on: bool) {
        if on {
            self.flags |= bit;
        } else {
            self.flags &= !bit;
        }
    }
}

impl File {
    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
        let flags = opts.flags | match (opts.read, opts.write) {
            (true, true) => libc::O_RDWR,
            (false, true) => libc::O_WRONLY,
            (true, false) |
            (false, false) => libc::O_RDONLY,
        };
        let path = cstr(path);
        let fd = try!(cvt_r(|| unsafe {
            libc::open(path.as_ptr(), flags, opts.mode)
        }));
        Ok(File(FileDesc::new(fd)))
    }

    pub fn file_attr(&self) -> io::Result<FileAttr> {
        let mut stat: libc::stat = unsafe { mem::zeroed() };
        try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat) }));
        Ok(FileAttr { stat: stat })
    }

    pub fn fsync(&self) -> io::Result<()> {
        try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
        Ok(())
    }

    pub fn datasync(&self) -> io::Result<()> {
        try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
        return Ok(());

        #[cfg(any(target_os = "macos", target_os = "ios"))]
        unsafe fn os_datasync(fd: c_int) -> c_int {
            libc::fcntl(fd, libc::F_FULLFSYNC)
        }
        #[cfg(target_os = "linux")]
        unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
        #[cfg(not(any(target_os = "macos",
                      target_os = "ios",
                      target_os = "linux")))]
        unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
    }

    pub fn truncate(&self, size: u64) -> io::Result<()> {
        try!(cvt_r(|| unsafe {
            libc::ftruncate(self.0.raw(), size as libc::off_t)
        }));
        Ok(())
    }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }

    pub fn flush(&self) -> io::Result<()> { Ok(()) }

    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
        let (whence, pos) = match pos {
            SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t),
            SeekFrom::End(off) => (libc::SEEK_END, off as off_t),
            SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t),
        };
        let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) }));
        Ok(n as u64)
    }

    pub fn fd(&self) -> &FileDesc { &self.0 }
}

fn cstr(path: &Path) -> CString {
    CString::from_slice(path.as_os_str().as_byte_slice())
}

pub fn mkdir(p: &Path) -> io::Result<()> {
    let p = cstr(p);
    try!(cvt(unsafe { libc::mkdir(p.as_ptr(), 0o777) }));
    Ok(())
}

pub fn readdir(p: &Path) -> io::Result<ReadDir> {
    let root = Rc::new(p.to_path_buf());
    let p = cstr(p);
    unsafe {
        let ptr = libc::opendir(p.as_ptr());
        if ptr.is_null() {
            Err(Error::last_os_error())
        } else {
            Ok(ReadDir { dirp: ptr, root: root })
        }
    }
}

pub fn unlink(p: &Path) -> io::Result<()> {
    let p = cstr(p);
    try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
    Ok(())
}

pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
    let old = cstr(old);
    let new = cstr(new);
    try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
    Ok(())
}

pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
    let p = cstr(p);
    try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
    Ok(())
}

pub fn rmdir(p: &Path) -> io::Result<()> {
    let p = cstr(p);
    try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
    Ok(())
}

pub fn chown(p: &Path, uid: isize, gid: isize) -> io::Result<()> {
    let p = cstr(p);
    try!(cvt_r(|| unsafe {
        libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
    }));
    Ok(())
}

pub fn readlink(p: &Path) -> io::Result<PathBuf> {
    let c_path = cstr(p);
    let p = c_path.as_ptr();
    let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
    if len < 0 {
        len = 1024; // FIXME: read PATH_MAX from C ffi?
    }
    let mut buf: Vec<u8> = Vec::with_capacity(len as usize);
    unsafe {
        let n = try!(cvt({
            libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t)
        }));
        buf.set_len(n as usize);
    }
    let s: OsString = OsStringExt::from_vec(buf);
    Ok(PathBuf::new(&s))
}

pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
    let src = cstr(src);
    let dst = cstr(dst);
    try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
    Ok(())
}

pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
    let src = cstr(src);
    let dst = cstr(dst);
    try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
    Ok(())
}

pub fn stat(p: &Path) -> io::Result<FileAttr> {
    let p = cstr(p);
    let mut stat: libc::stat = unsafe { mem::zeroed() };
    try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat) }));
    Ok(FileAttr { stat: stat })
}

pub fn lstat(p: &Path) -> io::Result<FileAttr> {
    let p = cstr(p);
    let mut stat: libc::stat = unsafe { mem::zeroed() };
    try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat) }));
    Ok(FileAttr { stat: stat })
}

pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> {
    let p = cstr(p);
    let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)];
    try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) }));
    Ok(())
}
<commit_msg>rollup merge of #22186: GuillaumeGomez/fix-fs<commit_after>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::prelude::*;
use io::prelude::*;
use os::unix::prelude::*;

use ffi::{self, CString, OsString, AsOsStr, OsStr};
use io::{self, Error, Seek, SeekFrom};
use libc::{self, c_int, c_void, size_t, off_t, c_char, mode_t};
use mem;
use path::{Path, PathBuf};
use ptr;
use rc::Rc;
use sys::fd::FileDesc;
use sys::{c, cvt, cvt_r};
use sys_common::FromInner;
use vec::Vec;

pub struct File(FileDesc);

pub struct FileAttr {
    stat: libc::stat,
}

pub struct ReadDir {
    dirp: *mut libc::DIR,
    root: Rc<PathBuf>,
}

pub struct DirEntry {
    buf: Vec<u8>,
    dirent: *mut libc::dirent_t,
    root: Rc<PathBuf>,
}

#[derive(Clone)]
pub struct OpenOptions {
    flags: c_int,
    read: bool,
    write: bool,
    mode: mode_t,
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FilePermissions { mode: mode_t }

impl FileAttr {
    pub fn is_dir(&self) -> bool {
        (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR
    }
    pub fn is_file(&self) -> bool {
        (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG
    }
    pub fn size(&self) -> u64 { self.stat.st_size as u64 }
    pub fn perm(&self) -> FilePermissions {
        FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
    }

    pub fn accessed(&self) -> u64 {
        self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64)
    }
    pub fn modified(&self) -> u64 {
        self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64)
    }

    // times are in milliseconds (currently)
    fn mktime(&self, secs: u64, nsecs: u64) -> u64 {
        secs * 1000 + nsecs / 1000000
    }
}

impl FilePermissions {
    pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
    pub fn set_readonly(&mut self, readonly: bool) {
        if readonly {
            self.mode &= !0o222;
        } else {
            self.mode |= 0o222;
        }
    }
}

impl FromInner<i32> for FilePermissions {
    fn from_inner(mode: i32) -> FilePermissions {
        FilePermissions { mode: mode as mode_t }
    }
}

impl Iterator for ReadDir {
    type Item = io::Result<DirEntry>;

    fn next(&mut self) -> Option<io::Result<DirEntry>> {
        extern {
            fn rust_dirent_t_size() -> c_int;
        }

        let mut buf: Vec<u8> = Vec::with_capacity(unsafe {
            rust_dirent_t_size() as usize
        });
        let ptr = buf.as_mut_ptr() as *mut libc::dirent_t;

        let mut entry_ptr = ptr::null_mut();
        loop {
            if unsafe { libc::readdir_r(self.dirp, ptr, &mut entry_ptr) != 0 } {
                return Some(Err(Error::last_os_error()))
            }
            if entry_ptr.is_null() {
                return None
            }

            let entry = DirEntry {
                buf: buf,
                dirent: entry_ptr,
                root: self.root.clone()
            };
            if entry.name_bytes() == b"." || entry.name_bytes() == b".." {
                buf = entry.buf;
            } else {
                return Some(Ok(entry))
            }
        }
    }
}

impl Drop for ReadDir {
    fn drop(&mut self) {
        let r = unsafe { libc::closedir(self.dirp) };
        debug_assert_eq!(r, 0);
    }
}

impl DirEntry {
    pub fn path(&self) -> PathBuf {
        self.root.join(<OsStr as OsStrExt>::from_byte_slice(self.name_bytes()))
    }

    fn name_bytes(&self) -> &[u8] {
        extern {
            fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char;
        }
        unsafe {
            let ptr = rust_list_dir_val(self.dirent);
            ffi::c_str_to_bytes(mem::copy_lifetime(self, &ptr))
        }
    }
}

impl OpenOptions {
    pub fn new() -> OpenOptions {
        OpenOptions {
            flags: 0,
            read: false,
            write: false,
            mode: libc::S_IRUSR | libc::S_IWUSR
                | libc::S_IRGRP | libc::S_IWGRP
                | libc::S_IROTH | libc::S_IWOTH,
        }
    }

    pub fn read(&mut self, read: bool) {
        self.read = read;
    }

    pub fn write(&mut self, write: bool) {
        self.write = write;
    }

    pub fn append(&mut self, append: bool) {
        self.flag(libc::O_APPEND, append);
    }

    pub fn truncate(&mut self, truncate: bool) {
        self.flag(libc::O_TRUNC, truncate);
    }

    pub fn create(&mut self, create: bool) {
        self.flag(libc::O_CREAT, create);
    }

    pub fn mode(&mut self, mode: i32) {
        self.mode = mode as mode_t;
    }

    fn flag(&mut self, bit: c_int, on: bool) {
        if on {
            self.flags |= bit;
        } else {
            self.flags &= !bit;
        }
    }
}

impl File {
    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
        let flags = opts.flags | match (opts.read, opts.write) {
            (true, true) => libc::O_RDWR,
            (false, true) => libc::O_WRONLY,
            (true, false) |
            (false, false) => libc::O_RDONLY,
        };
        let path = cstr(path);
        let fd = try!(cvt_r(|| unsafe {
            libc::open(path.as_ptr(), flags, opts.mode)
        }));
        Ok(File(FileDesc::new(fd)))
    }

    pub fn file_attr(&self) -> io::Result<FileAttr> {
        let mut stat: libc::stat = unsafe { mem::zeroed() };
        try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat) }));
        Ok(FileAttr { stat: stat })
    }

    pub fn fsync(&self) -> io::Result<()> {
        try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
        Ok(())
    }

    pub fn datasync(&self) -> io::Result<()> {
        try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
        return Ok(());

        #[cfg(any(target_os = "macos", target_os = "ios"))]
        unsafe fn os_datasync(fd: c_int) -> c_int {
            libc::fcntl(fd, libc::F_FULLFSYNC)
        }
        #[cfg(target_os = "linux")]
        unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
        #[cfg(not(any(target_os = "macos",
                      target_os = "ios",
                      target_os = "linux")))]
        unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
    }

    pub fn truncate(&self, size: u64) -> io::Result<()> {
        try!(cvt_r(|| unsafe {
            libc::ftruncate(self.0.raw(), size as libc::off_t)
        }));
        Ok(())
    }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }

    pub fn flush(&self) -> io::Result<()> { Ok(()) }

    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
        let (whence, pos) = match pos {
            SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t),
            SeekFrom::End(off) => (libc::SEEK_END, off as off_t),
            SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t),
        };
        let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) }));
        Ok(n as u64)
    }

    pub fn fd(&self) -> &FileDesc { &self.0 }
}

fn cstr(path: &Path) -> CString {
    CString::from_slice(path.as_os_str().as_byte_slice())
}

pub fn mkdir(p: &Path) -> io::Result<()> {
    let p = cstr(p);
    try!(cvt(unsafe { libc::mkdir(p.as_ptr(), 0o777) }));
    Ok(())
}

pub fn readdir(p: &Path) -> io::Result<ReadDir> {
    let root = Rc::new(p.to_path_buf());
    let p = cstr(p);
    unsafe {
        let ptr = libc::opendir(p.as_ptr());
        if ptr.is_null() {
            Err(Error::last_os_error())
        } else {
            Ok(ReadDir { dirp: ptr, root: root })
        }
    }
}

pub fn unlink(p: &Path) -> io::Result<()> {
    let p = cstr(p);
    try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
    Ok(())
}

pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
    let old = cstr(old);
    let new = cstr(new);
    try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
    Ok(())
}

pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
    let p = cstr(p);
    try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
    Ok(())
}

pub fn rmdir(p: &Path) -> io::Result<()> {
    let p = cstr(p);
    try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
    Ok(())
}

pub fn chown(p: &Path, uid: isize, gid: isize) -> io::Result<()> {
    let p = cstr(p);
    try!(cvt_r(|| unsafe {
        libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
    }));
    Ok(())
}

pub fn readlink(p: &Path) -> io::Result<PathBuf> {
    let c_path = cstr(p);
    let p = c_path.as_ptr();
    let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
    if len < 0 {
        len = 1024; // FIXME: read PATH_MAX from C ffi?
    }
    let mut buf: Vec<u8> = Vec::with_capacity(len as usize);
    unsafe {
        let n = try!(cvt({
            libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t)
        }));
        buf.set_len(n as usize);
    }
    let s: OsString = OsStringExt::from_vec(buf);
    Ok(PathBuf::new(&s))
}

pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
    let src = cstr(src);
    let dst = cstr(dst);
    try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
    Ok(())
}

pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
    let src = cstr(src);
    let dst = cstr(dst);
    try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
    Ok(())
}

pub fn stat(p: &Path) -> io::Result<FileAttr> {
    let p = cstr(p);
    let mut stat: libc::stat = unsafe { mem::zeroed() };
    try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat) }));
    Ok(FileAttr { stat: stat })
}

pub fn lstat(p: &Path) -> io::Result<FileAttr> {
    let p = cstr(p);
    let mut stat: libc::stat = unsafe { mem::zeroed() };
    try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat) }));
    Ok(FileAttr { stat: stat })
}

pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> {
    let p = cstr(p);
    let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)];
    try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) }));
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>add test that checks overflows on arithmetic operators<commit_after>// run-pass
// compile-flags: -O
#![allow(const_err)]

// Make sure arithmetic unary/binary ops actually return the right result, even when overflowing.
// We have to put them in `const fn` and turn on optimizations to avoid overflow checks.

const fn add(x: i8, y: i8) -> i8 { x+y }
const fn sub(x: i8, y: i8) -> i8 { x-y }
const fn mul(x: i8, y: i8) -> i8 { x*y }
// div and rem are always checked, so we cannot test their result in case of oveflow.
const fn neg(x: i8) -> i8 { -x }

fn main() {
    const ADD_OFLOW: i8 = add(100, 100);
    assert_eq!(ADD_OFLOW, -56);

    const SUB_OFLOW: i8 = sub(100, -100);
    assert_eq!(SUB_OFLOW, -56);

    const MUL_OFLOW: i8 = mul(-100, -2);
    assert_eq!(MUL_OFLOW, -56);

    const NEG_OFLOW: i8 = neg(-128);
    assert_eq!(NEG_OFLOW, -128);
}
<|endoftext|>


<commit_before><commit_msg>Add a benchmark for dfs<commit_after>#![feature(test)]

extern crate chappie;
extern crate test;

use chappie::search::SearchSpace;
use test::{Bencher, black_box};
use std::vec::IntoIter;

enum Dir { Left, Right}

struct BinaryTree;

const MAX_DEPTH: u64 = 16;
const MAX_OFFSET: u64 = 1 << (MAX_DEPTH + 1);

impl SearchSpace for BinaryTree {
    type State = u64;
    type Action = Dir;
    type Iterator = IntoIter<(Self::Action, Self::State)>;

    fn expand(&self, state: &Self::State) -> Self::Iterator {
        let offset = (*state + 2).next_power_of_two();
        if offset >= MAX_OFFSET {
            return vec![].into_iter();
        }
        let right = *state + offset;
        let left = *state + offset / 2;
        vec![(Dir::Left, left), (Dir::Right, right)].into_iter()
    }
}

#[bench]
fn dfs(b: &mut Bencher) {
    let tree = BinaryTree;
    b.iter(|| { black_box(tree.dfs(0, 2)) });
}
<|endoftext|>


<commit_before><commit_msg>Add a few more types<commit_after><|endoftext|>


<commit_before><commit_msg>Rewrite tests not to use stainless and enforce<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: Print processed IDs if output is not a pipe.<commit_after><|endoftext|>


<commit_before>use {io, poll, Evented, Ready, Poll, PollOpt, Token};
use magenta_sys::mx_handle_t;
use std::sync::Mutex;

/// Wrapper for registering a `HandleBase` type with mio.
#[derive(Debug)]
pub struct EventedHandle {
    /// The handle to be registered.
    handle: mx_handle_t,

    /// The current `Token` with which the handle is registered with mio.
    token: Mutex<Option<Token>>,
}

impl EventedHandle {
    /// Create a new `EventedHandle` which can be registered with mio
    /// in order to receive event notifications.
    ///
    /// The underlying handle must not be
    pub unsafe fn new(handle: mx_handle_t) -> Self {
        EventedHandle {
            handle: handle,
            token: Mutex::new(None),
        }
    }

    /// Get the underlying handle being registered.
    pub fn get_handle(&self) -> mx_handle_t {
        self.handle
    }
}

impl Evented for EventedHandle {
    fn register(&self,
                poll: &Poll,
                token: Token,
                interest: Ready,
                opts: PollOpt) -> io::Result<()>
    {
        let mut this_token = self.token.lock().unwrap();
        {
            poll::selector(poll).register_handle(self.handle, token, interest, opts)?;
            *this_token = Some(token);
        }
        Ok(())
    }

    fn reregister(&self,
        poll: &Poll,
        token: Token,
        interest: Ready,
        opts: PollOpt) -> io::Result<()>
    {
        let mut this_token = self.token.lock().unwrap();
        {
            poll::selector(poll).deregister_handle(self.handle, token)?;
            *this_token = None;
            poll::selector(poll).register_handle(self.handle, token, interest, opts)?;
            *this_token = Some(token);
        }
        Ok(())
    }

    fn deregister(&self, poll: &Poll) -> io::Result<()> {
        let mut this_token = self.token.lock().unwrap();
        let token = if let Some(token) = *this_token { token } else {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "Attempted to deregister an unregistered handle."))
        };
        {
            poll::selector(poll).deregister_handle(self.handle, token)?;
            *this_token = None;
        }
        Ok(())
    }
}
<commit_msg>Fix missing comment (#719)<commit_after>use {io, poll, Evented, Ready, Poll, PollOpt, Token};
use magenta_sys::mx_handle_t;
use std::sync::Mutex;

/// Wrapper for registering a `HandleBase` type with mio.
#[derive(Debug)]
pub struct EventedHandle {
    /// The handle to be registered.
    handle: mx_handle_t,

    /// The current `Token` with which the handle is registered with mio.
    token: Mutex<Option<Token>>,
}

impl EventedHandle {
    /// Create a new `EventedHandle` which can be registered with mio
    /// in order to receive event notifications.
    ///
    /// The underlying handle must not be dropped while the
    /// `EventedHandle` still exists.
    pub unsafe fn new(handle: mx_handle_t) -> Self {
        EventedHandle {
            handle: handle,
            token: Mutex::new(None),
        }
    }

    /// Get the underlying handle being registered.
    pub fn get_handle(&self) -> mx_handle_t {
        self.handle
    }
}

impl Evented for EventedHandle {
    fn register(&self,
                poll: &Poll,
                token: Token,
                interest: Ready,
                opts: PollOpt) -> io::Result<()>
    {
        let mut this_token = self.token.lock().unwrap();
        {
            poll::selector(poll).register_handle(self.handle, token, interest, opts)?;
            *this_token = Some(token);
        }
        Ok(())
    }

    fn reregister(&self,
        poll: &Poll,
        token: Token,
        interest: Ready,
        opts: PollOpt) -> io::Result<()>
    {
        let mut this_token = self.token.lock().unwrap();
        {
            poll::selector(poll).deregister_handle(self.handle, token)?;
            *this_token = None;
            poll::selector(poll).register_handle(self.handle, token, interest, opts)?;
            *this_token = Some(token);
        }
        Ok(())
    }

    fn deregister(&self, poll: &Poll) -> io::Result<()> {
        let mut this_token = self.token.lock().unwrap();
        let token = if let Some(token) = *this_token { token } else {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "Attempted to deregister an unregistered handle."))
        };
        {
            poll::selector(poll).deregister_handle(self.handle, token)?;
            *this_token = None;
        }
        Ok(())
    }
}
<|endoftext|>


<commit_before>use std::sync::Arc;
use std::mem;

use program::Program;
use vertex_buffer::{mod, VertexBuffer, BindingType};
use {DisplayImpl, IndicesSource, GlObject};

use {libc, gl};

///
pub struct VertexArrayObject {
    display: Arc<DisplayImpl>,
    id: gl::types::GLuint,
}

impl VertexArrayObject {
    ///
    fn new<T>(display: Arc<DisplayImpl>, vertex_buffer: &VertexBuffer<T>,
              ib_id: gl::types::GLuint, program: &Program) -> VertexArrayObject
    {
        let (tx, rx) = channel();

        let bindings = vertex_buffer::get_bindings(vertex_buffer).clone();
        let vb_elementssize = vertex_buffer::get_elements_size(vertex_buffer);
        let vertex_buffer = GlObject::get_id(vertex_buffer);
        let attributes = ::program::get_attributes(program);

        // checking the attributes types
        for &(ref name, _, ty) in bindings.iter() {
            let attribute = match attributes.get(name) {
                Some(a) => a,
                None => continue
            };

            if !vertex_type_matches(ty, attribute.ty, attribute.size) {
                panic!("The program attributes do not match the vertex format");
            }
        }

        display.context.exec(move |: ctxt| {
            unsafe {
                let id: gl::types::GLuint = mem::uninitialized();
                ctxt.gl.GenVertexArrays(1, mem::transmute(&id));
                tx.send(id);

                ctxt.gl.BindVertexArray(id);
                ctxt.state.vertex_array = id;

                // binding vertex buffer
                if ctxt.state.array_buffer_binding != vertex_buffer {
                    ctxt.gl.BindBuffer(gl::ARRAY_BUFFER, vertex_buffer);
                    ctxt.state.array_buffer_binding = vertex_buffer;
                }

                // binding index buffer
                ctxt.gl.BindBuffer(gl::ELEMENT_ARRAY_BUFFER, ib_id);

                // binding attributes
                for (name, offset, ty) in bindings.into_iter() {
                    let (data_type, elements_count) = vertex_binding_type_to_gl(ty);

                    let attribute = match attributes.get(&name) {
                        Some(a) => a,
                        None => continue
                    };

                    if attribute.location != -1 {
                        match data_type {
                            gl::BYTE | gl::UNSIGNED_BYTE | gl::SHORT | gl::UNSIGNED_SHORT |
                            gl::INT | gl::UNSIGNED_INT =>
                                ctxt.gl.VertexAttribIPointer(attribute.location as u32,
                                    elements_count as gl::types::GLint, data_type,
                                    vb_elementssize as i32, offset as *const libc::c_void),

                            _ => ctxt.gl.VertexAttribPointer(attribute.location as u32,
                                    elements_count as gl::types::GLint, data_type, 0,
                                    vb_elementssize as i32, offset as *const libc::c_void)
                        }

                        ctxt.gl.EnableVertexAttribArray(attribute.location as u32);
                    }
                }
            }
        });

        VertexArrayObject {
            display: display,
            id: rx.recv(),
        }
    }
}

impl Drop for VertexArrayObject {
    fn drop(&mut self) {
        let id = self.id.clone();
        self.display.context.exec(move |: ctxt| {
            unsafe {
                // unbinding
                if ctxt.state.vertex_array == id {
                    ctxt.gl.BindVertexArray(0);
                    ctxt.state.vertex_array = 0;
                }

                // deleting
                ctxt.gl.DeleteVertexArrays(1, [ id ].as_ptr());
            }
        });
    }
}

impl GlObject for VertexArrayObject {
    fn get_id(&self) -> gl::types::GLuint {
        self.id
    }
}

pub fn get_vertex_array_object<T, I>(display: &Arc<DisplayImpl>, vertex_buffer: &VertexBuffer<T>,
                                     indices: &I, program: &Program) -> gl::types::GLuint
                                     where I: IndicesSource
{
    let mut vaos = display.vertex_array_objects.lock();

    let ib_id = indices.to_indices_source_helper().index_buffer.map(|b| b.get_id()).unwrap_or(0);
    let vb_id = GlObject::get_id(vertex_buffer);
    let program_id = program.get_id();

    if let Some(value) = vaos.get(&(vb_id, ib_id, program_id)) {
        return value.id;
    }

    let new_vao = VertexArrayObject::new(display.clone(), vertex_buffer, ib_id, program);
    let new_vao_id = new_vao.id;
    vaos.insert((vb_id, ib_id, program_id), new_vao);
    new_vao_id
}

fn vertex_binding_type_to_gl(ty: BindingType) -> (gl::types::GLenum, gl::types::GLint) {
    match ty {
        BindingType::I8 => (gl::BYTE, 1),
        BindingType::I8I8 => (gl::BYTE, 2),
        BindingType::I8I8I8 => (gl::BYTE, 3),
        BindingType::I8I8I8I8 => (gl::BYTE, 4),
        BindingType::U8 => (gl::UNSIGNED_BYTE, 1),
        BindingType::U8U8 => (gl::UNSIGNED_BYTE, 2),
        BindingType::U8U8U8 => (gl::UNSIGNED_BYTE, 3),
        BindingType::U8U8U8U8 => (gl::UNSIGNED_BYTE, 4),
        BindingType::I16 => (gl::SHORT, 1),
        BindingType::I16I16 => (gl::SHORT, 2),
        BindingType::I16I16I16 => (gl::SHORT, 3),
        BindingType::I16I16I16I16 => (gl::SHORT, 4),
        BindingType::U16 => (gl::UNSIGNED_SHORT, 1),
        BindingType::U16U16 => (gl::UNSIGNED_SHORT, 2),
        BindingType::U16U16U16 => (gl::UNSIGNED_SHORT, 3),
        BindingType::U16U16U16U16 => (gl::UNSIGNED_SHORT, 4),
        BindingType::I32 => (gl::INT, 1),
        BindingType::I32I32 => (gl::INT, 2),
        BindingType::I32I32I32 => (gl::INT, 3),
        BindingType::I32I32I32I32 => (gl::INT, 4),
        BindingType::U32 => (gl::UNSIGNED_INT, 1),
        BindingType::U32U32 => (gl::UNSIGNED_INT, 2),
        BindingType::U32U32U32 => (gl::UNSIGNED_INT, 3),
        BindingType::U32U32U32U32 => (gl::UNSIGNED_INT, 4),
        BindingType::F32 => (gl::FLOAT, 1),
        BindingType::F32F32 => (gl::FLOAT, 2),
        BindingType::F32F32F32 => (gl::FLOAT, 3),
        BindingType::F32F32F32F32 => (gl::FLOAT, 4),
    }
}

fn vertex_type_matches(ty: BindingType, gl_ty: gl::types::GLenum,
                       gl_size: gl::types::GLint) -> bool
{
    match (ty, gl_ty, gl_size) {
        (BindingType::I8, gl::BYTE, 1) => true,
        (BindingType::I8I8, gl::BYTE, 2) => true,
        (BindingType::I8I8I8, gl::BYTE, 3) => true,
        (BindingType::I8I8I8I8, gl::BYTE, 4) => true,
        (BindingType::U8, gl::UNSIGNED_BYTE, 1) => true,
        (BindingType::U8U8, gl::UNSIGNED_BYTE, 2) => true,
        (BindingType::U8U8U8, gl::UNSIGNED_BYTE, 3) => true,
        (BindingType::U8U8U8U8, gl::UNSIGNED_BYTE, 4) => true,
        (BindingType::I16, gl::SHORT, 1) => true,
        (BindingType::I16I16, gl::SHORT, 2) => true,
        (BindingType::I16I16I16, gl::SHORT, 3) => true,
        (BindingType::I16I16I16I16, gl::SHORT, 4) => true,
        (BindingType::U16, gl::UNSIGNED_SHORT, 1) => true,
        (BindingType::U16U16, gl::UNSIGNED_SHORT, 2) => true,
        (BindingType::U16U16U16, gl::UNSIGNED_SHORT, 3) => true,
        (BindingType::U16U16U16U16, gl::UNSIGNED_SHORT, 4) => true,
        (BindingType::I32, gl::INT, 1) => true,
        (BindingType::I32I32, gl::INT, 2) => true,
        (BindingType::I32I32, gl::INT_VEC2, 1) => true,
        (BindingType::I32I32I32, gl::INT, 3) => true,
        (BindingType::I32I32I32, gl::INT_VEC3, 1) => true,
        (BindingType::I32I32I32I32, gl::INT, 4) => true,
        (BindingType::I32I32I32I32, gl::INT_VEC4, 1) => true,
        (BindingType::I32I32I32I32, gl::INT_VEC2, 2) => true,
        (BindingType::U32, gl::UNSIGNED_INT, 1) => true,
        (BindingType::U32U32, gl::UNSIGNED_INT, 2) => true,
        (BindingType::U32U32, gl::UNSIGNED_INT_VEC2, 1) => true,
        (BindingType::U32U32U32, gl::UNSIGNED_INT, 3) => true,
        (BindingType::U32U32U32, gl::UNSIGNED_INT_VEC3, 1) => true,
        (BindingType::U32U32U32U32, gl::UNSIGNED_INT, 4) => true,
        (BindingType::U32U32U32U32, gl::UNSIGNED_INT_VEC4, 1) => true,
        (BindingType::U32U32U32U32, gl::UNSIGNED_INT_VEC2, 2) => true,
        (BindingType::F32, gl::FLOAT, 1) => true,
        (BindingType::F32F32, gl::FLOAT, 2) => true,
        (BindingType::F32F32, gl::FLOAT_VEC2, 1) => true,
        (BindingType::F32F32F32, gl::FLOAT, 3) => true,
        (BindingType::F32F32F32, gl::FLOAT_VEC3, 1) => true,
        (BindingType::F32F32F32F32, gl::FLOAT, 4) => true,
        (BindingType::F32F32F32F32, gl::FLOAT_VEC4, 1) => true,
        (BindingType::F32F32F32F32, gl::FLOAT_VEC2, 2) => true,
        _ => false,
    }
}
<commit_msg>No longer lock the VAOs mutex while building a new VAO<commit_after>use std::sync::Arc;
use std::mem;

use program::Program;
use vertex_buffer::{mod, VertexBuffer, BindingType};
use {DisplayImpl, IndicesSource, GlObject};

use {libc, gl};

///
pub struct VertexArrayObject {
    display: Arc<DisplayImpl>,
    id: gl::types::GLuint,
}

impl VertexArrayObject {
    ///
    fn new<T>(display: Arc<DisplayImpl>, vertex_buffer: &VertexBuffer<T>,
              ib_id: gl::types::GLuint, program: &Program) -> VertexArrayObject
    {
        let bindings = vertex_buffer::get_bindings(vertex_buffer).clone();
        let vb_elementssize = vertex_buffer::get_elements_size(vertex_buffer);
        let vertex_buffer = GlObject::get_id(vertex_buffer);
        let attributes = ::program::get_attributes(program);

        // checking the attributes types
        for &(ref name, _, ty) in bindings.iter() {
            let attribute = match attributes.get(name) {
                Some(a) => a,
                None => continue
            };

            if !vertex_type_matches(ty, attribute.ty, attribute.size) {
                panic!("The program attributes do not match the vertex format");
            }
        }

        let (tx, rx) = channel();

        display.context.exec(move |: ctxt| {
            unsafe {
                let id: gl::types::GLuint = mem::uninitialized();
                ctxt.gl.GenVertexArrays(1, mem::transmute(&id));
                tx.send(id);

                ctxt.gl.BindVertexArray(id);
                ctxt.state.vertex_array = id;

                // binding vertex buffer
                if ctxt.state.array_buffer_binding != vertex_buffer {
                    ctxt.gl.BindBuffer(gl::ARRAY_BUFFER, vertex_buffer);
                    ctxt.state.array_buffer_binding = vertex_buffer;
                }

                // binding index buffer
                ctxt.gl.BindBuffer(gl::ELEMENT_ARRAY_BUFFER, ib_id);

                // binding attributes
                for (name, offset, ty) in bindings.into_iter() {
                    let (data_type, elements_count) = vertex_binding_type_to_gl(ty);

                    let attribute = match attributes.get(&name) {
                        Some(a) => a,
                        None => continue
                    };

                    if attribute.location != -1 {
                        match data_type {
                            gl::BYTE | gl::UNSIGNED_BYTE | gl::SHORT | gl::UNSIGNED_SHORT |
                            gl::INT | gl::UNSIGNED_INT =>
                                ctxt.gl.VertexAttribIPointer(attribute.location as u32,
                                    elements_count as gl::types::GLint, data_type,
                                    vb_elementssize as i32, offset as *const libc::c_void),

                            _ => ctxt.gl.VertexAttribPointer(attribute.location as u32,
                                    elements_count as gl::types::GLint, data_type, 0,
                                    vb_elementssize as i32, offset as *const libc::c_void)
                        }

                        ctxt.gl.EnableVertexAttribArray(attribute.location as u32);
                    }
                }
            }
        });

        VertexArrayObject {
            display: display,
            id: rx.recv(),
        }
    }
}

impl Drop for VertexArrayObject {
    fn drop(&mut self) {
        let id = self.id.clone();
        self.display.context.exec(move |: ctxt| {
            unsafe {
                // unbinding
                if ctxt.state.vertex_array == id {
                    ctxt.gl.BindVertexArray(0);
                    ctxt.state.vertex_array = 0;
                }

                // deleting
                ctxt.gl.DeleteVertexArrays(1, [ id ].as_ptr());
            }
        });
    }
}

impl GlObject for VertexArrayObject {
    fn get_id(&self) -> gl::types::GLuint {
        self.id
    }
}

pub fn get_vertex_array_object<T, I>(display: &Arc<DisplayImpl>, vertex_buffer: &VertexBuffer<T>,
                                     indices: &I, program: &Program) -> gl::types::GLuint
                                     where I: IndicesSource
{
    let ib_id = indices.to_indices_source_helper().index_buffer.map(|b| b.get_id()).unwrap_or(0);
    let vb_id = GlObject::get_id(vertex_buffer);
    let program_id = program.get_id();

    if let Some(value) = display.vertex_array_objects.lock().get(&(vb_id, ib_id, program_id)) {
        return value.id;
    }

    // we create the new VAO without the mutex locked
    let new_vao = VertexArrayObject::new(display.clone(), vertex_buffer, ib_id, program);
    let new_vao_id = new_vao.id;
    display.vertex_array_objects.lock().insert((vb_id, ib_id, program_id), new_vao);
    new_vao_id
}

fn vertex_binding_type_to_gl(ty: BindingType) -> (gl::types::GLenum, gl::types::GLint) {
    match ty {
        BindingType::I8 => (gl::BYTE, 1),
        BindingType::I8I8 => (gl::BYTE, 2),
        BindingType::I8I8I8 => (gl::BYTE, 3),
        BindingType::I8I8I8I8 => (gl::BYTE, 4),
        BindingType::U8 => (gl::UNSIGNED_BYTE, 1),
        BindingType::U8U8 => (gl::UNSIGNED_BYTE, 2),
        BindingType::U8U8U8 => (gl::UNSIGNED_BYTE, 3),
        BindingType::U8U8U8U8 => (gl::UNSIGNED_BYTE, 4),
        BindingType::I16 => (gl::SHORT, 1),
        BindingType::I16I16 => (gl::SHORT, 2),
        BindingType::I16I16I16 => (gl::SHORT, 3),
        BindingType::I16I16I16I16 => (gl::SHORT, 4),
        BindingType::U16 => (gl::UNSIGNED_SHORT, 1),
        BindingType::U16U16 => (gl::UNSIGNED_SHORT, 2),
        BindingType::U16U16U16 => (gl::UNSIGNED_SHORT, 3),
        BindingType::U16U16U16U16 => (gl::UNSIGNED_SHORT, 4),
        BindingType::I32 => (gl::INT, 1),
        BindingType::I32I32 => (gl::INT, 2),
        BindingType::I32I32I32 => (gl::INT, 3),
        BindingType::I32I32I32I32 => (gl::INT, 4),
        BindingType::U32 => (gl::UNSIGNED_INT, 1),
        BindingType::U32U32 => (gl::UNSIGNED_INT, 2),
        BindingType::U32U32U32 => (gl::UNSIGNED_INT, 3),
        BindingType::U32U32U32U32 => (gl::UNSIGNED_INT, 4),
        BindingType::F32 => (gl::FLOAT, 1),
        BindingType::F32F32 => (gl::FLOAT, 2),
        BindingType::F32F32F32 => (gl::FLOAT, 3),
        BindingType::F32F32F32F32 => (gl::FLOAT, 4),
    }
}

fn vertex_type_matches(ty: BindingType, gl_ty: gl::types::GLenum,
                       gl_size: gl::types::GLint) -> bool
{
    match (ty, gl_ty, gl_size) {
        (BindingType::I8, gl::BYTE, 1) => true,
        (BindingType::I8I8, gl::BYTE, 2) => true,
        (BindingType::I8I8I8, gl::BYTE, 3) => true,
        (BindingType::I8I8I8I8, gl::BYTE, 4) => true,
        (BindingType::U8, gl::UNSIGNED_BYTE, 1) => true,
        (BindingType::U8U8, gl::UNSIGNED_BYTE, 2) => true,
        (BindingType::U8U8U8, gl::UNSIGNED_BYTE, 3) => true,
        (BindingType::U8U8U8U8, gl::UNSIGNED_BYTE, 4) => true,
        (BindingType::I16, gl::SHORT, 1) => true,
        (BindingType::I16I16, gl::SHORT, 2) => true,
        (BindingType::I16I16I16, gl::SHORT, 3) => true,
        (BindingType::I16I16I16I16, gl::SHORT, 4) => true,
        (BindingType::U16, gl::UNSIGNED_SHORT, 1) => true,
        (BindingType::U16U16, gl::UNSIGNED_SHORT, 2) => true,
        (BindingType::U16U16U16, gl::UNSIGNED_SHORT, 3) => true,
        (BindingType::U16U16U16U16, gl::UNSIGNED_SHORT, 4) => true,
        (BindingType::I32, gl::INT, 1) => true,
        (BindingType::I32I32, gl::INT, 2) => true,
        (BindingType::I32I32, gl::INT_VEC2, 1) => true,
        (BindingType::I32I32I32, gl::INT, 3) => true,
        (BindingType::I32I32I32, gl::INT_VEC3, 1) => true,
        (BindingType::I32I32I32I32, gl::INT, 4) => true,
        (BindingType::I32I32I32I32, gl::INT_VEC4, 1) => true,
        (BindingType::I32I32I32I32, gl::INT_VEC2, 2) => true,
        (BindingType::U32, gl::UNSIGNED_INT, 1) => true,
        (BindingType::U32U32, gl::UNSIGNED_INT, 2) => true,
        (BindingType::U32U32, gl::UNSIGNED_INT_VEC2, 1) => true,
        (BindingType::U32U32U32, gl::UNSIGNED_INT, 3) => true,
        (BindingType::U32U32U32, gl::UNSIGNED_INT_VEC3, 1) => true,
        (BindingType::U32U32U32U32, gl::UNSIGNED_INT, 4) => true,
        (BindingType::U32U32U32U32, gl::UNSIGNED_INT_VEC4, 1) => true,
        (BindingType::U32U32U32U32, gl::UNSIGNED_INT_VEC2, 2) => true,
        (BindingType::F32, gl::FLOAT, 1) => true,
        (BindingType::F32F32, gl::FLOAT, 2) => true,
        (BindingType::F32F32, gl::FLOAT_VEC2, 1) => true,
        (BindingType::F32F32F32, gl::FLOAT, 3) => true,
        (BindingType::F32F32F32, gl::FLOAT_VEC3, 1) => true,
        (BindingType::F32F32F32F32, gl::FLOAT, 4) => true,
        (BindingType::F32F32F32F32, gl::FLOAT_VEC4, 1) => true,
        (BindingType::F32F32F32F32, gl::FLOAT_VEC2, 2) => true,
        _ => false,
    }
}
<|endoftext|>


<commit_before><commit_msg>test VecDeque<commit_after>use std::collections::VecDeque;

fn main() {
    let mut dst = VecDeque::new();
    dst.push_front(Box::new(1));
    dst.push_front(Box::new(2));
    dst.pop_back();

    let mut src = VecDeque::new();
    src.push_front(Box::new(2));
    dst.append(&mut src);
    for a in dst {
      assert_eq!(*a, 2);
    }
}
<|endoftext|>


<commit_before>use libimagstore::storeid::StoreId;
use libimagstore::store::Entry;
use libimagstore::store::EntryHeader;
use libimagstore::store::Result as StoreResult;

use error::{LinkError, LinkErrorKind};
use result::Result;

use toml::Value;
use itertools::Itertools;

pub type Link = StoreId;

pub trait InternalLinker {

    /// Get the internal links from the implementor object
    fn get_internal_links(&self) -> Result<Vec<Link>>;

    /// Set the internal links for the implementor object
    fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>>;

    /// Add an internal link to the implementor object
    fn add_internal_link(&mut self, link: &mut Entry) -> Result<()>;

    /// Remove an internal link from the implementor object
    fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()>;

}

impl InternalLinker for Entry {

    fn get_internal_links(&self) -> Result<Vec<Link>> {
        process_rw_result(self.get_header().read("imag.links"))
    }

    /// Set the links in a header and return the old links, if any.
    fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>> {
        let self_location = self.get_location().clone();
        let mut new_links = vec![];

        for link in links {
            if let Err(e) = add_foreign_link(link, self_location.clone()) {
                return Err(e);
            }
            let link = link.get_location().clone();
            let link = link.to_str();
            if link.is_none() {
                return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
            }
            let link = link.unwrap();

            new_links.push(String::from(link));
        }

        let new_links = new_links.into_iter().unique().map(|s| Value::String(s)).collect();
        process_rw_result(self.get_header_mut().set("imag.links", Value::Array(new_links)))
    }

    fn add_internal_link(&mut self, link: &mut Entry) -> Result<()> {
        let new_link = link.get_location().clone();

        add_foreign_link(link, self.get_location().clone())
            .and_then(|_| {
                self.get_internal_links()
                    .and_then(|mut links| {
                        links.push(new_link);
                        rewrite_links(self.get_header_mut(), links)
                    })
            })
    }

    fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()> {
        let own_loc   = link.get_location().clone();
        let other_loc = link.get_location().clone();

        link.get_internal_links()
            .and_then(|links| {
                let links = links.into_iter().filter(|l| l.clone() != own_loc).collect();
                rewrite_links(self.get_header_mut(), links)
            })
            .and_then(|_| {
                self.get_internal_links()
                    .and_then(|links| {
                        let links = links.into_iter().filter(|l| l.clone() != other_loc).collect();
                        rewrite_links(link.get_header_mut(), links)
                    })
            })
    }

}

fn rewrite_links(header: &mut EntryHeader, links: Vec<StoreId>) -> Result<()> {
    let links : Vec<Option<Value>> = links
        .into_iter()
        .map(|s| s.to_str().map(|s| String::from(s)))
        .unique()
        .map(|elem| elem.map(|s| Value::String(s)))
        .collect();

    if links.iter().any(|o| o.is_none()) {
        // if any type convert failed we fail as well
        Err(LinkError::new(LinkErrorKind::InternalConversionError, None))
    } else {
        // I know it is ugly
        let links = links.into_iter().map(|opt| opt.unwrap()).collect();
        let process = header.set("imag.links", Value::Array(links));
        process_rw_result(process).map(|_| ())
    }
}

/// When Linking A -> B, the specification wants us to link back B -> A.
/// This is a helper function which does this.
fn add_foreign_link(target: &mut Entry, from: StoreId) -> Result<()> {
    target.get_internal_links()
        .and_then(|mut links| {
            links.push(from);
            let links : Vec<Option<Value>> = links
                .into_iter()
                .map(|s| {
                    match s.to_str() {
                        Some(s) => Some(String::from(s)),
                        _ => None
                    }
                })
                .unique()
                .map(|elem| elem.map(|s| Value::String(s)))
                .collect();
            if links.iter().any(|o| o.is_none()) {
                Err(LinkError::new(LinkErrorKind::InternalConversionError, None))
            } else {
                let links = links.into_iter().map(|opt| opt.unwrap()).collect();
                process_rw_result(target.get_header_mut().set("imag.links", Value::Array(links)))
                    .map(|_| ())
            }
        })
}

fn process_rw_result(links: StoreResult<Option<Value>>) -> Result<Vec<Link>> {
    if links.is_err() {
        debug!("RW action on store failed. Generating LinkError");
        let lerr  = LinkError::new(LinkErrorKind::EntryHeaderReadError,
                                   Some(Box::new(links.err().unwrap())));
        return Err(lerr);
    }
    let links = links.unwrap();

    if links.is_none() {
        debug!("We got no value from the header!");
        return Ok(vec![])
    }
    let links = links.unwrap();

    let links = {
        match links {
            Value::Array(a) => a,
            _ => {
                debug!("We expected an Array for the links, but there was a non-Array!");
                return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None));
            },
        }
    };

    if !links.iter().all(|l| match l { &Value::String(_) => true, _ => false }) {
        debug!("At least one of the Values which were expected in the Array of links is a non-String!");
        debug!("Generating LinkError");
        return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None));
    }

    let links : Vec<Link> = links.into_iter()
        .map(|link| {
            match link {
                Value::String(s) => StoreId::from(s),
                _ => unreachable!(),
            }
        })
        .collect();

    debug!("Ok, the RW action was successful, returning link vector now!");
    Ok(links)
}

<commit_msg>Sort links alphabetically before writing<commit_after>use std::cmp::Ordering;

use libimagstore::storeid::StoreId;
use libimagstore::store::Entry;
use libimagstore::store::EntryHeader;
use libimagstore::store::Result as StoreResult;

use error::{LinkError, LinkErrorKind};
use result::Result;

use toml::Value;
use itertools::Itertools;

pub type Link = StoreId;

pub trait InternalLinker {

    /// Get the internal links from the implementor object
    fn get_internal_links(&self) -> Result<Vec<Link>>;

    /// Set the internal links for the implementor object
    fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>>;

    /// Add an internal link to the implementor object
    fn add_internal_link(&mut self, link: &mut Entry) -> Result<()>;

    /// Remove an internal link from the implementor object
    fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()>;

}

impl InternalLinker for Entry {

    fn get_internal_links(&self) -> Result<Vec<Link>> {
        process_rw_result(self.get_header().read("imag.links"))
    }

    /// Set the links in a header and return the old links, if any.
    fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>> {
        let self_location = self.get_location().clone();
        let mut new_links = vec![];

        for link in links {
            if let Err(e) = add_foreign_link(link, self_location.clone()) {
                return Err(e);
            }
            let link = link.get_location().clone();
            let link = link.to_str();
            if link.is_none() {
                return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
            }
            let link = link.unwrap();

            new_links.push(String::from(link));
        }

        let new_links = new_links
            .into_iter()
            .unique()
            .map(|s| Value::String(s))
            .sorted_by(|a, b| {
                match (a, b) {
                    (&Value::String(ref a), &Value::String(ref b)) => Ord::cmp(a, b),
                    _                                              => unreachable!()
                }
            });
        process_rw_result(self.get_header_mut().set("imag.links", Value::Array(new_links)))
    }

    fn add_internal_link(&mut self, link: &mut Entry) -> Result<()> {
        let new_link = link.get_location().clone();

        add_foreign_link(link, self.get_location().clone())
            .and_then(|_| {
                self.get_internal_links()
                    .and_then(|mut links| {
                        links.push(new_link);
                        rewrite_links(self.get_header_mut(), links)
                    })
            })
    }

    fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()> {
        let own_loc   = link.get_location().clone();
        let other_loc = link.get_location().clone();

        link.get_internal_links()
            .and_then(|links| {
                let links = links.into_iter().filter(|l| l.clone() != own_loc).collect();
                rewrite_links(self.get_header_mut(), links)
            })
            .and_then(|_| {
                self.get_internal_links()
                    .and_then(|links| {
                        let links = links.into_iter().filter(|l| l.clone() != other_loc).collect();
                        rewrite_links(link.get_header_mut(), links)
                    })
            })
    }

}

fn rewrite_links(header: &mut EntryHeader, links: Vec<StoreId>) -> Result<()> {
    let links : Vec<Option<Value>> = links
        .into_iter()
        .map(|s| s.to_str().map(|s| String::from(s)))
        .unique()
        .map(|elem| elem.map(|s| Value::String(s)))
        .sorted_by(|a, b| {
            match (a, b) {
                (&Some(Value::String(ref a)), &Some(Value::String(ref b))) => Ord::cmp(a, b),
                (&None, _) | (_, &None) => Ordering::Equal,
                _                                              => unreachable!()
            }
        });

    if links.iter().any(|o| o.is_none()) {
        // if any type convert failed we fail as well
        Err(LinkError::new(LinkErrorKind::InternalConversionError, None))
    } else {
        // I know it is ugly
        let links = links.into_iter().map(|opt| opt.unwrap()).collect();
        let process = header.set("imag.links", Value::Array(links));
        process_rw_result(process).map(|_| ())
    }
}

/// When Linking A -> B, the specification wants us to link back B -> A.
/// This is a helper function which does this.
fn add_foreign_link(target: &mut Entry, from: StoreId) -> Result<()> {
    target.get_internal_links()
        .and_then(|mut links| {
            links.push(from);
            let links : Vec<Option<Value>> = links
                .into_iter()
                .map(|s| {
                    match s.to_str() {
                        Some(s) => Some(String::from(s)),
                        _ => None
                    }
                })
                .unique()
                .map(|elem| elem.map(|s| Value::String(s)))
                .sorted_by(|a, b| {
                    match (a, b) {
                        (&Some(Value::String(ref a)), &Some(Value::String(ref b))) => Ord::cmp(a, b),
                        (&None, _) | (_, &None) => Ordering::Equal,
                        _                                              => unreachable!()
                    }
                });
            if links.iter().any(|o| o.is_none()) {
                Err(LinkError::new(LinkErrorKind::InternalConversionError, None))
            } else {
                let links = links.into_iter().map(|opt| opt.unwrap()).collect();
                process_rw_result(target.get_header_mut().set("imag.links", Value::Array(links)))
                    .map(|_| ())
            }
        })
}

fn process_rw_result(links: StoreResult<Option<Value>>) -> Result<Vec<Link>> {
    if links.is_err() {
        debug!("RW action on store failed. Generating LinkError");
        let lerr  = LinkError::new(LinkErrorKind::EntryHeaderReadError,
                                   Some(Box::new(links.err().unwrap())));
        return Err(lerr);
    }
    let links = links.unwrap();

    if links.is_none() {
        debug!("We got no value from the header!");
        return Ok(vec![])
    }
    let links = links.unwrap();

    let links = {
        match links {
            Value::Array(a) => a,
            _ => {
                debug!("We expected an Array for the links, but there was a non-Array!");
                return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None));
            },
        }
    };

    if !links.iter().all(|l| match l { &Value::String(_) => true, _ => false }) {
        debug!("At least one of the Values which were expected in the Array of links is a non-String!");
        debug!("Generating LinkError");
        return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None));
    }

    let links : Vec<Link> = links.into_iter()
        .map(|link| {
            match link {
                Value::String(s) => StoreId::from(s),
                _ => unreachable!(),
            }
        })
        .collect();

    debug!("Ok, the RW action was successful, returning link vector now!");
    Ok(links)
}

<|endoftext|>


<commit_before><commit_msg>Start of Rust implementation.<commit_after>fn main() {
    println!("hello, world");
}
<|endoftext|>


<commit_before><commit_msg>(WIP) Ability to walk with a player through the world<commit_after>use super::camera::*;
use super::event_manager::*;
use glium::backend::glutin_backend::GlutinFacade;
use glium::glutin::{CursorState, ElementState, Event, MouseButton, VirtualKeyCode};
use base::math::*;
use std::time::{Duration, Instant};
use std::thread::sleep;

pub struct Player {
    cam: Camera,
    // velocity: f32,
    prev_mouse_pos: Option<(i32, i32)>,
    context: GlutinFacade,
    delta_x: f32,
    vel_z: f32,
    delta_y: f32,
    delta_z: f32,
    dz: f32,
    gravity: f32,
    is_jumping: bool,
    is_moving: bool,
    tick_count: f32,
}

impl Player {
    pub fn new(context: GlutinFacade) -> Self {
        Player {
            cam: Camera {
                position: Point3::new(0.0, 0.0, 50.0),
                phi: -0.27,
                theta: 2.6,
            },
            prev_mouse_pos: None,
            context: context,
            delta_x: 0.0,
            delta_y: 0.0,
            delta_z: 0.0,
            gravity: 0.005,
            vel_z: 0.0,
            dz: 0.0,
            is_jumping: false,
            is_moving: false,
            tick_count: 1.0,
        }
    }

    pub fn get_camera(&self) -> Camera {
        self.cam
    }
    pub fn jump(&mut self) {

        if self.is_jumping == false {
            self.dz = 0.11;
            self.is_jumping = true;
        }

        // if self.delta_x == 0.0 && self.delta_y == 0.0 {
        //     // Jump vertically because sideways motion is zero
        //     let now = Instant::now();

        //     tick_count = 1.0;
        //     while 1.0 > 0.999999 {

        //         let mut dz: f32 = 1.0;

        //         self.cam.move_up(20.0);
        //         // self.cam.move_up(dz);
        //         sleep(Duration::new(1, 0));
        //         tick_count += 1.0;
        //         println!("dz: {}", dz);
        //     }
        //     // self.cam.move_down(self.cam.position[2] - 1.0);
        // }
    }

    pub fn update(&mut self, delta: f32) {
        // let mut tick_count = self.tick_count;
        // phyiscal calulcations and update cam pos
        // let mut dz: f32 = (10.0 * tick_count * 0.1) -
        //         ((self.gravity / 2.0) * (tick_count * 0.1) * (tick_count *
        //         0.1));
        // println!("cam position: {:?}", self.cam.position);
        if self.is_jumping == true {
            if self.cam.position[2] >= 50.0 {
                self.dz = self.dz - self.gravity;
                // let mut dz = (1.5 * self.tick_count * 0.007) -
                //              ((self.gravity) * (self.tick_count * 0.007) *
                //               (self.tick_count * 0.007));
                // if dz < -0.03 {
                //     dz = -0.03;
                // }
                println!("dz: {:?}", self.dz);
                if self.dz < -0.2 {
                    self.dz = -0.2;
                }
                self.cam.move_up(self.dz);
                self.tick_count += 1.0;
                // self.cam.position[2] += self.delta_z - self.gravity;
                if self.delta_z > -100.0 {
                    self.delta_z -= 1.0;
                }
            } else {
                self.tick_count = 1.0;
                self.is_jumping = false;
                self.cam.position[2] = 1.0;
            }

        }

        // if self.is_moving {
        //     self.get_curr_motion();
        // }
    }

    // pub fn get_curr_motion() -> (f32, f32) {
    //     (self.vel_x, self.vel_y)
    // }
    // pub fn get_jumping_vel(&self) -> f32 {

    //     self.delta_z = self.delta_z

    // }
    // pub fn move(&self) {

    // }
}

impl EventHandler for Player {
    fn handle_event(&mut self, e: &Event) -> EventResponse {
        match *e {
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::W)) => {
                self.cam.move_forward(0.1);
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::S)) => {
                self.cam.move_backward(0.1);
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::A)) => {
                self.cam.move_left(0.1);

                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::D)) => {
                self.cam.move_right(0.1);
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::Space)) => {

                // if !self.is_jumping() {
                self.jump();
                //  self.cam.move_down(0.1);
                EventResponse::Continue
            }

            // X only for the fact, that you cannot hold LControl to go down,
            // because holding the key only counts as one keystroke
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::C)) => {
                self.cam.move_down(1.0);
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::LControl)) => {
                self.cam.move_down(1.0);
                EventResponse::Continue
            }

            Event::MouseInput(ElementState::Pressed, MouseButton::Left) => {
                info!("clicked");
                if let Some(window) = self.context.get_window() {
                    let res = window.set_cursor_state(CursorState::Grab);
                    warn!("{:?}", res);
                } else {
                    warn!("Failed to obtain window from facade");
                }
                EventResponse::Continue
            }
            Event::MouseMoved(x, y) => {

                if let Some((prev_x, prev_y)) = self.prev_mouse_pos {
                    let x_diff = x - prev_x;
                    let y_diff = y - prev_y;
                    info!("x = {}, y = {}", x_diff, y_diff);
                    self.cam.change_dir(y_diff as f32 / 300.0, x_diff as f32 / 300.0);
                }

                self.prev_mouse_pos = Some((x, y));

                EventResponse::Continue
            }

            _ => EventResponse::NotHandled,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add method to count Alive neighbors<commit_after><|endoftext|>


<commit_before>//! Helper module to enable serializing bytes more efficiently

use std::ops;

use ser;
use de;

///////////////////////////////////////////////////////////////////////////////

/// `Bytes` wraps a `&[u8]` in order to serialize into a byte array.
pub struct Bytes<'a> {
    bytes: &'a [u8],
}

impl<'a> From<&'a [u8]> for Bytes<'a> {
    fn from(bytes: &'a [u8]) -> Self {
        Bytes {
            bytes: bytes,
        }
    }
}

impl<'a> From<&'a Vec<u8>> for Bytes<'a> {
    fn from(bytes: &'a Vec<u8>) -> Self {
        Bytes {
            bytes: &bytes,
        }
    }
}

impl<'a> ops::Deref for Bytes<'a> {
    type Target = [u8];

    fn deref(&self) -> &[u8] { self.bytes }
}

impl<'a> ser::Serialize for Bytes<'a> {
    #[inline]
    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
        where S: ser::Serializer
    {
        serializer.visit_bytes(self.bytes)
    }
}

///////////////////////////////////////////////////////////////////////////////

/// `ByteBuf` wraps a `Vec<u8>` in order to hook into serialize and from deserialize a byte array.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct ByteBuf {
    bytes: Vec<u8>,
}

impl ByteBuf {
    pub fn new() -> Self {
        ByteBuf {
            bytes: Vec::new(),
        }
    }

    pub fn with_capacity(cap: usize) -> Self {
        ByteBuf {
            bytes: Vec::with_capacity(cap)
        }
    }
}

impl<T> From<T> for ByteBuf where T: Into<Vec<u8>> {
    fn from(bytes: T) -> Self {
        ByteBuf {
            bytes: bytes.into(),
        }
    }
}

impl AsRef<Vec<u8>> for ByteBuf {
    fn as_ref(&self) -> &Vec<u8> {
        &self.bytes
    }
}

impl AsRef<[u8]> for ByteBuf {
    fn as_ref(&self) -> &[u8] {
        &self.bytes
    }
}

impl AsMut<Vec<u8>> for ByteBuf {
    fn as_mut(&mut self) -> &mut Vec<u8> {
        &mut self.bytes
    }
}

impl AsMut<[u8]> for ByteBuf {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.bytes
    }
}

impl Into<Vec<u8>> for ByteBuf {
    fn into(self) -> Vec<u8> {
        self.bytes
    }
}

impl ops::Deref for ByteBuf {
    type Target = [u8];

    fn deref(&self) -> &[u8] { &self.bytes[..] }
}

impl ops::DerefMut for ByteBuf {
    fn deref_mut(&mut self) -> &mut [u8] { &mut self.bytes[..] }
}

impl ser::Serialize for ByteBuf {
    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
        where S: ser::Serializer
    {
        serializer.visit_bytes(&self)
    }
}

pub struct ByteBufVisitor;

impl de::Visitor for ByteBufVisitor {
    type Value = ByteBuf;

    #[inline]
    fn visit_unit<E>(&mut self) -> Result<ByteBuf, E>
        where E: de::Error,
    {
        Ok(ByteBuf {
            bytes: Vec::new(),
        })
    }

    #[inline]
    fn visit_seq<V>(&mut self, mut visitor: V) -> Result<ByteBuf, V::Error>
        where V: de::SeqVisitor,
    {
        let (len, _) = visitor.size_hint();
        let mut values = Vec::with_capacity(len);

        while let Some(value) = try!(visitor.visit()) {
            values.push(value);
        }

        try!(visitor.end());

        Ok(ByteBuf {
            bytes: values,
        })
    }

    #[inline]
    fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<ByteBuf, E>
        where E: de::Error,
    {
        self.visit_byte_buf(v.to_vec())
    }

    #[inline]
    fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<ByteBuf, E>
        where E: de::Error,
    {
        Ok(ByteBuf {
            bytes: v,
        })
    }
}

impl de::Deserialize for ByteBuf {
    #[inline]
    fn deserialize<D>(deserializer: &mut D) -> Result<ByteBuf, D::Error>
        where D: de::Deserializer
    {
        deserializer.visit_bytes(ByteBufVisitor)
    }
}
<commit_msg>Remove `impl Into<Vec<u8>> for ByteBuf` since it causes a compile error<commit_after>//! Helper module to enable serializing bytes more efficiently

use std::ops;

use ser;
use de;

///////////////////////////////////////////////////////////////////////////////

/// `Bytes` wraps a `&[u8]` in order to serialize into a byte array.
pub struct Bytes<'a> {
    bytes: &'a [u8],
}

impl<'a> From<&'a [u8]> for Bytes<'a> {
    fn from(bytes: &'a [u8]) -> Self {
        Bytes {
            bytes: bytes,
        }
    }
}

impl<'a> From<&'a Vec<u8>> for Bytes<'a> {
    fn from(bytes: &'a Vec<u8>) -> Self {
        Bytes {
            bytes: &bytes,
        }
    }
}

impl<'a> ops::Deref for Bytes<'a> {
    type Target = [u8];

    fn deref(&self) -> &[u8] { self.bytes }
}

impl<'a> ser::Serialize for Bytes<'a> {
    #[inline]
    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
        where S: ser::Serializer
    {
        serializer.visit_bytes(self.bytes)
    }
}

///////////////////////////////////////////////////////////////////////////////

/// `ByteBuf` wraps a `Vec<u8>` in order to hook into serialize and from deserialize a byte array.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct ByteBuf {
    bytes: Vec<u8>,
}

impl ByteBuf {
    pub fn new() -> Self {
        ByteBuf {
            bytes: Vec::new(),
        }
    }

    pub fn with_capacity(cap: usize) -> Self {
        ByteBuf {
            bytes: Vec::with_capacity(cap)
        }
    }
}

impl<T> From<T> for ByteBuf where T: Into<Vec<u8>> {
    fn from(bytes: T) -> Self {
        ByteBuf {
            bytes: bytes.into(),
        }
    }
}

impl AsRef<Vec<u8>> for ByteBuf {
    fn as_ref(&self) -> &Vec<u8> {
        &self.bytes
    }
}

impl AsRef<[u8]> for ByteBuf {
    fn as_ref(&self) -> &[u8] {
        &self.bytes
    }
}

impl AsMut<Vec<u8>> for ByteBuf {
    fn as_mut(&mut self) -> &mut Vec<u8> {
        &mut self.bytes
    }
}

impl AsMut<[u8]> for ByteBuf {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.bytes
    }
}

impl ops::Deref for ByteBuf {
    type Target = [u8];

    fn deref(&self) -> &[u8] { &self.bytes[..] }
}

impl ops::DerefMut for ByteBuf {
    fn deref_mut(&mut self) -> &mut [u8] { &mut self.bytes[..] }
}

impl ser::Serialize for ByteBuf {
    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
        where S: ser::Serializer
    {
        serializer.visit_bytes(&self)
    }
}

pub struct ByteBufVisitor;

impl de::Visitor for ByteBufVisitor {
    type Value = ByteBuf;

    #[inline]
    fn visit_unit<E>(&mut self) -> Result<ByteBuf, E>
        where E: de::Error,
    {
        Ok(ByteBuf {
            bytes: Vec::new(),
        })
    }

    #[inline]
    fn visit_seq<V>(&mut self, mut visitor: V) -> Result<ByteBuf, V::Error>
        where V: de::SeqVisitor,
    {
        let (len, _) = visitor.size_hint();
        let mut values = Vec::with_capacity(len);

        while let Some(value) = try!(visitor.visit()) {
            values.push(value);
        }

        try!(visitor.end());

        Ok(ByteBuf {
            bytes: values,
        })
    }

    #[inline]
    fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<ByteBuf, E>
        where E: de::Error,
    {
        self.visit_byte_buf(v.to_vec())
    }

    #[inline]
    fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<ByteBuf, E>
        where E: de::Error,
    {
        Ok(ByteBuf {
            bytes: v,
        })
    }
}

impl de::Deserialize for ByteBuf {
    #[inline]
    fn deserialize<D>(deserializer: &mut D) -> Result<ByteBuf, D::Error>
        where D: de::Deserializer
    {
        deserializer.visit_bytes(ByteBufVisitor)
    }
}
<|endoftext|>


<commit_before><commit_msg>Added Debug derive to PamError<commit_after><|endoftext|>


<commit_before><commit_msg>Fix write error<commit_after><|endoftext|>


<commit_before><commit_msg>class is fixed, not dynamic<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for item hiding<commit_after>#![allow(unused)]

// @has 'item_hide_threshold/struct.PubStruct.html'
// @count - '//details[@class="rustdoc-toggle type-contents-toggle"]' 0
pub struct PubStruct {
    pub a: usize,
    pub b: usize,
}

// @has 'item_hide_threshold/struct.BigPubStruct.html'
// @count - '//details[@class="rustdoc-toggle type-contents-toggle"]' 1
// @has - '//details[@class="rustdoc-toggle type-contents-toggle"]' 'Show fields'
pub struct BigPubStruct {
    pub a: usize,
    pub b: usize,
    pub c: usize,
    pub d: usize,
    pub e: usize,
    pub f: usize,
    pub g: usize,
    pub h: usize,
    pub i: usize,
    pub j: usize,
    pub k: usize,
    pub l: usize,
    pub m: usize,
}

// @has 'item_hide_threshold/union.BigUnion.html'
// @count - '//details[@class="rustdoc-toggle type-contents-toggle"]' 1
// @has - '//details[@class="rustdoc-toggle type-contents-toggle"]' 'Show fields'
pub union BigUnion {
    pub a: usize,
    pub b: usize,
    pub c: usize,
    pub d: usize,
    pub e: usize,
    pub f: usize,
    pub g: usize,
    pub h: usize,
    pub i: usize,
    pub j: usize,
    pub k: usize,
    pub l: usize,
    pub m: usize,
}

// @has 'item_hide_threshold/union.Union.html'
// @count - '//details[@class="rustdoc-toggle type-contents-toggle"]' 0
pub union Union {
    pub a: usize,
    pub b: usize,
    pub c: usize,
}

// @has 'item_hide_threshold/struct.PrivStruct.html'
// @count - '//details[@class="rustdoc-toggle type-contents-toggle"]' 0
// @has - '//div[@class="docblock type-decl"]' 'fields omitted'
pub struct PrivStruct {
    a: usize,
    b: usize,
}

// @has 'item_hide_threshold/enum.Enum.html'
// @count - '//details[@class="rustdoc-toggle type-contents-toggle"]' 0
pub enum Enum {
    A, B, C,
    D {
        a: u8,
        b: u8
    }
}

// @has 'item_hide_threshold/enum.LargeEnum.html'
// @count - '//details[@class="rustdoc-toggle type-contents-toggle"]' 1
// @has - '//details[@class="rustdoc-toggle type-contents-toggle"]' 'Show variants'
pub enum LargeEnum {
    A, B, C, D, E, F(u8), G, H, I, J, K, L, M
}

// @has 'item_hide_threshold/trait.Trait.html'
// @count - '//details[@class="rustdoc-toggle type-contents-toggle"]' 0
pub trait Trait {
    type A;
    #[must_use]
    fn foo();
    fn bar();
}

// @has 'item_hide_threshold/trait.GinormousTrait.html'
// @count - '//details[@class="rustdoc-toggle type-contents-toggle"]' 1
// @has - '//details[@class="rustdoc-toggle type-contents-toggle"]' 'Show associated items'
pub trait GinormousTrait {
    type A;
    type B;
    type C;
    type D;
    type E;
    type F;
    type G;
    type H;
    type I;
    type J;
    type K;
    type L;
    type M;
    const N: usize = 1;
    #[must_use]
    fn foo();
    fn bar();
}

// @has 'item_hide_threshold/trait.HugeTrait.html'
// @count - '//details[@class="rustdoc-toggle type-contents-toggle"]' 1
// @has - '//details[@class="rustdoc-toggle type-contents-toggle"]' 'Show associated constants and methods'
pub trait HugeTrait {
    type A;
    const M: usize = 1;
    const N: usize = 1;
    const O: usize = 1;
    const P: usize = 1;
    const Q: usize = 1;
    const R: usize = 1;
    const S: usize = 1;
    const T: usize = 1;
    const U: usize = 1;
    const V: usize = 1;
    const W: usize = 1;
    const X: usize = 1;
    #[must_use]
    fn foo();
    fn bar();
}

// @has 'item_hide_threshold/trait.BigTrait.html'
// @count - '//details[@class="rustdoc-toggle type-contents-toggle"]' 1
// @has - '//details[@class="rustdoc-toggle type-contents-toggle"]' 'Show methods'
pub trait BigTrait {
    type A;
    #[must_use]
    fn foo();
    fn bar();
    fn baz();
    fn quux();
    fn frob();
    fn greeble();
    fn blap();
    fn whoop();
    fn pow();
    fn bang();
    fn oomph();
    fn argh();
    fn wap();
    fn ouch();
}
<|endoftext|>


<commit_before><commit_msg>Move inner deflate function as well<commit_after>use std::mem;
use crate::{MZResult, MZFlush, MZError, MZStatus};
use crate::deflate::core::{TDEFLStatus, TDEFLFlush, CompressorOxide, compress};

pub fn deflate(compressor: &mut CompressorOxide, next_in: &mut &[u8],
               next_out: &mut &mut [u8],
               total_in: &mut u64, total_out: &mut u64,
               flush: MZFlush) -> MZResult {

    if next_out.is_empty() {
        return Err(MZError::Buf);
    }

    if compressor.prev_return_status() == TDEFLStatus::Done {
        return if flush == MZFlush::Finish {
            Ok(MZStatus::StreamEnd)
        } else {
            Err(MZError::Buf)
        };
    }

    let original_total_in = *total_in;
    let original_total_out = *total_out;

    loop {
        let in_bytes;
        let out_bytes;
        let defl_status = {
            let res = compress(compressor, *next_in, *next_out, TDEFLFlush::from(flush));
            in_bytes = res.1;
            out_bytes = res.2;
            res.0
        };

        *next_in = &next_in[in_bytes..];
        *next_out = &mut mem::replace(next_out, &mut [])[out_bytes..];
        *total_in += in_bytes as u64;
        *total_out += out_bytes as u64;

        if defl_status == TDEFLStatus::BadParam || defl_status == TDEFLStatus::PutBufFailed {
            return Err(MZError::Stream);
        }

        if defl_status == TDEFLStatus::Done {
            return Ok(MZStatus::StreamEnd);
        }

        if next_out.is_empty() {
            return Ok(MZStatus::Ok);
        }

        if next_in.is_empty() && (flush != MZFlush::Finish) {
            let total_changed = (*total_in != original_total_in) ||
                (*total_out != original_total_out);

            return if (flush != MZFlush::None) || total_changed {
                Ok(MZStatus::Ok)
            } else {
                Err(MZError::Buf)
            };
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>add rust implementation.<commit_after>use std::cmp::max;
use std::env::args;

struct Diff {
    a: String,
    b: String,
    m: usize,
    n: usize,
}

fn build_diff(a: String, b: String) -> Diff {
    if a.len() > b.len() {
        return Diff {
            a: b.to_string(),
            b: a.to_string(),
            m: b.len(),
            n: a.len(),
        };
    }
    return Diff {
        a: a.to_string(),
        b: b.to_string(),
        m: a.len(),
        n: b.len(),
    };
}

impl Diff {
    fn snake(&self, mut x: usize, mut y: usize) -> usize {
        while x < self.m
            && y < self.n
            && self.a.chars().nth(x).unwrap() == self.b.chars().nth(y).unwrap()
        {
            x = x + 1;
            y = y + 1;
        }

        return y;
    }

    fn ed(&self) -> usize {
        let offset: usize = self.m + 1;
        let delta: usize = self.n - self.m;
        let size = self.m + self.n + 3;
        let mut fp: Vec<usize> = vec![0; size];

        let mut p: usize = 0;
        loop {
            let mut k = offset - p;
            while k <= delta + offset - 1 {
                let y = max(fp[k - 1] + 1, fp[k + 1]);
                if offset < k {
                    fp[k] = self.snake(y - (k - offset), y);
                } else {
                    fp[k] = self.snake(y + (offset - k), y);
                }
                k = k + 1;
            }
            let mut l = delta + p;
            while l >= delta + 1 {
                let y = max(fp[l + offset - 1] + 1, fp[l + 1 + offset]);
                fp[l + offset] = self.snake(y - l, y);
                l = l - 1;
            }

            let y = max(fp[delta + offset - 1] + 1, fp[delta + 1 + offset]);
            fp[delta + offset] = self.snake(y - delta, y);

            if fp[delta + offset] >= self.n {
                break;
            }
            p = p + 1;
        }
        return delta + 2 * p;
    }
}

fn main() {
    let args: Vec<String> = args().collect();

    if args.len() < 3 {
        println!("few arguments");
        std::process::exit(1);
    }

    let a = &args[1];
    let b = &args[2];

    println!("{}", a);
    println!("{}", b);

    let d = build_diff(a.to_string(), b.to_string());

    println!("ed: {}", d.ed());
}
<|endoftext|>


<commit_before><commit_msg>add !enable and !disable commands<commit_after><|endoftext|>


<commit_before><commit_msg>Improve the Vulkan framebuffer creation so that it would be useful in more circumstances<commit_after><|endoftext|>


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

//! Unwind library interface

#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)] // these are just bindings

#[cfg(any(not(target_arch = "arm"), target_os = "ios"))]
pub use self::_Unwind_Action::*;
#[cfg(target_arch = "arm")]
pub use self::_Unwind_State::*;
pub use self::_Unwind_Reason_Code::*;

use libc;

#[cfg(any(not(target_arch = "arm"), target_os = "ios"))]
#[repr(C)]
#[derive(Copy)]
pub enum _Unwind_Action {
    _UA_SEARCH_PHASE = 1,
    _UA_CLEANUP_PHASE = 2,
    _UA_HANDLER_FRAME = 4,
    _UA_FORCE_UNWIND = 8,
    _UA_END_OF_STACK = 16,
}

#[cfg(target_arch = "arm")]
#[repr(C)]
pub enum _Unwind_State {
    _US_VIRTUAL_UNWIND_FRAME = 0,
    _US_UNWIND_FRAME_STARTING = 1,
    _US_UNWIND_FRAME_RESUME = 2,
    _US_ACTION_MASK = 3,
    _US_FORCE_UNWIND = 8,
    _US_END_OF_STACK = 16
}

#[repr(C)]
pub enum _Unwind_Reason_Code {
    _URC_NO_REASON = 0,
    _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
    _URC_FATAL_PHASE2_ERROR = 2,
    _URC_FATAL_PHASE1_ERROR = 3,
    _URC_NORMAL_STOP = 4,
    _URC_END_OF_STACK = 5,
    _URC_HANDLER_FOUND = 6,
    _URC_INSTALL_CONTEXT = 7,
    _URC_CONTINUE_UNWIND = 8,
    _URC_FAILURE = 9, // used only by ARM EABI
}

pub type _Unwind_Exception_Class = u64;

pub type _Unwind_Word = libc::uintptr_t;

#[cfg(target_arch = "x86")]
pub const unwinder_private_data_size: uint = 5;

#[cfg(target_arch = "x86_64")]
pub const unwinder_private_data_size: uint = 6;

#[cfg(all(target_arch = "arm", not(target_os = "ios")))]
pub const unwinder_private_data_size: uint = 20;

#[cfg(all(target_arch = "arm", target_os = "ios"))]
pub const unwinder_private_data_size: uint = 5;

#[cfg(target_arch = "aarch64")]
pub const unwinder_private_data_size: uint = 2;

#[cfg(any(target_arch = "mips", target_arch = "mipsel"))]
pub const unwinder_private_data_size: uint = 2;

#[repr(C)]
pub struct _Unwind_Exception {
    pub exception_class: _Unwind_Exception_Class,
    pub exception_cleanup: _Unwind_Exception_Cleanup_Fn,
    pub private: [_Unwind_Word; unwinder_private_data_size],
}

pub enum _Unwind_Context {}

pub type _Unwind_Exception_Cleanup_Fn =
        extern "C" fn(unwind_code: _Unwind_Reason_Code,
                      exception: *mut _Unwind_Exception);

#[cfg(any(target_os = "linux", target_os = "freebsd"))]
#[link(name = "gcc_s")]
extern {}

#[cfg(target_os = "android")]
#[link(name = "gcc")]
extern {}

#[cfg(target_os = "dragonfly")]
#[link(name = "gcc_pic")]
extern {}

extern "C" {
    // iOS on armv7 uses SjLj exceptions and requires to link
    // against corresponding routine (..._SjLj_...)
    #[cfg(not(all(target_os = "ios", target_arch = "arm")))]
    pub fn _Unwind_RaiseException(exception: *mut _Unwind_Exception)
                                  -> _Unwind_Reason_Code;

    #[cfg(all(target_os = "ios", target_arch = "arm"))]
    fn _Unwind_SjLj_RaiseException(e: *mut _Unwind_Exception)
                                   -> _Unwind_Reason_Code;

    pub fn _Unwind_DeleteException(exception: *mut _Unwind_Exception);
}

// ... and now we just providing access to SjLj counterspart
// through a standard name to hide those details from others
// (see also comment above regarding _Unwind_RaiseException)
#[cfg(all(target_os = "ios", target_arch = "arm"))]
#[inline(always)]
pub unsafe fn _Unwind_RaiseException(exc: *mut _Unwind_Exception)
                                     -> _Unwind_Reason_Code {
    _Unwind_SjLj_RaiseException(exc)
}
<commit_msg>powerpc: Add unwinder size REVISIT<commit_after>// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Unwind library interface

#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)] // these are just bindings

#[cfg(any(not(target_arch = "arm"), target_os = "ios"))]
pub use self::_Unwind_Action::*;
#[cfg(target_arch = "arm")]
pub use self::_Unwind_State::*;
pub use self::_Unwind_Reason_Code::*;

use libc;

#[cfg(any(not(target_arch = "arm"), target_os = "ios"))]
#[repr(C)]
#[derive(Copy)]
pub enum _Unwind_Action {
    _UA_SEARCH_PHASE = 1,
    _UA_CLEANUP_PHASE = 2,
    _UA_HANDLER_FRAME = 4,
    _UA_FORCE_UNWIND = 8,
    _UA_END_OF_STACK = 16,
}

#[cfg(target_arch = "arm")]
#[repr(C)]
pub enum _Unwind_State {
    _US_VIRTUAL_UNWIND_FRAME = 0,
    _US_UNWIND_FRAME_STARTING = 1,
    _US_UNWIND_FRAME_RESUME = 2,
    _US_ACTION_MASK = 3,
    _US_FORCE_UNWIND = 8,
    _US_END_OF_STACK = 16
}

#[repr(C)]
pub enum _Unwind_Reason_Code {
    _URC_NO_REASON = 0,
    _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
    _URC_FATAL_PHASE2_ERROR = 2,
    _URC_FATAL_PHASE1_ERROR = 3,
    _URC_NORMAL_STOP = 4,
    _URC_END_OF_STACK = 5,
    _URC_HANDLER_FOUND = 6,
    _URC_INSTALL_CONTEXT = 7,
    _URC_CONTINUE_UNWIND = 8,
    _URC_FAILURE = 9, // used only by ARM EABI
}

pub type _Unwind_Exception_Class = u64;

pub type _Unwind_Word = libc::uintptr_t;

#[cfg(target_arch = "x86")]
pub const unwinder_private_data_size: uint = 5;

#[cfg(target_arch = "x86_64")]
pub const unwinder_private_data_size: uint = 6;

#[cfg(all(target_arch = "arm", not(target_os = "ios")))]
pub const unwinder_private_data_size: uint = 20;

#[cfg(all(target_arch = "arm", target_os = "ios"))]
pub const unwinder_private_data_size: uint = 5;

#[cfg(target_arch = "aarch64")]
pub const unwinder_private_data_size: uint = 2;

#[cfg(any(target_arch = "mips", target_arch = "mipsel"))]
pub const unwinder_private_data_size: uint = 2;

#[cfg(target_arch = "powerpc")]
pub const unwinder_private_data_size: uint = 2;

#[repr(C)]
pub struct _Unwind_Exception {
    pub exception_class: _Unwind_Exception_Class,
    pub exception_cleanup: _Unwind_Exception_Cleanup_Fn,
    pub private: [_Unwind_Word; unwinder_private_data_size],
}

pub enum _Unwind_Context {}

pub type _Unwind_Exception_Cleanup_Fn =
        extern "C" fn(unwind_code: _Unwind_Reason_Code,
                      exception: *mut _Unwind_Exception);

#[cfg(any(target_os = "linux", target_os = "freebsd"))]
#[link(name = "gcc_s")]
extern {}

#[cfg(target_os = "android")]
#[link(name = "gcc")]
extern {}

#[cfg(target_os = "dragonfly")]
#[link(name = "gcc_pic")]
extern {}

extern "C" {
    // iOS on armv7 uses SjLj exceptions and requires to link
    // against corresponding routine (..._SjLj_...)
    #[cfg(not(all(target_os = "ios", target_arch = "arm")))]
    pub fn _Unwind_RaiseException(exception: *mut _Unwind_Exception)
                                  -> _Unwind_Reason_Code;

    #[cfg(all(target_os = "ios", target_arch = "arm"))]
    fn _Unwind_SjLj_RaiseException(e: *mut _Unwind_Exception)
                                   -> _Unwind_Reason_Code;

    pub fn _Unwind_DeleteException(exception: *mut _Unwind_Exception);
}

// ... and now we just providing access to SjLj counterspart
// through a standard name to hide those details from others
// (see also comment above regarding _Unwind_RaiseException)
#[cfg(all(target_os = "ios", target_arch = "arm"))]
#[inline(always)]
pub unsafe fn _Unwind_RaiseException(exc: *mut _Unwind_Exception)
                                     -> _Unwind_Reason_Code {
    _Unwind_SjLj_RaiseException(exc)
}
<|endoftext|>