<commit_before>//! Linux-specific definitions for linux-like values

pub type useconds_t = u32;
pub type dev_t = u64;
pub type socklen_t = u32;
pub type pthread_t = c_ulong;

s! {
    pub struct glob_t {
        pub gl_pathc: size_t,
        pub gl_pathv: *mut *mut c_char,
        pub gl_offs:  size_t,
        pub gl_flags: ::c_int,

        __unused1: *mut ::c_void,
        __unused2: *mut ::c_void,
        __unused3: *mut ::c_void,
        __unused4: *mut ::c_void,
        __unused5: *mut ::c_void,
    }

    pub struct ifaddrs {
        pub ifa_next: *mut ifaddrs,
        pub ifa_name: *mut c_char,
        pub ifa_flags: ::c_uint,
        pub ifa_addr: *mut ::sockaddr,
        pub ifa_netmask: *mut ::sockaddr,
        pub ifa_ifu: *mut ::sockaddr, // FIXME This should be a union
        pub ifa_data: *mut ::c_void
    }

    pub struct pthread_mutex_t {
        #[cfg(any(target_arch = "mips", target_arch = "mipsel",
                  target_arch = "arm"))]
        __align: [::c_long; 0],
        #[cfg(not(any(target_arch = "mips", target_arch = "mipsel",
                      target_arch = "arm")))]
        __align: [::c_longlong; 0],
        size: [u8; __SIZEOF_PTHREAD_MUTEX_T],
    }

    pub struct pthread_rwlock_t {
        #[cfg(any(target_arch = "mips", target_arch = "mipsel",
                  target_arch = "arm"))]
        __align: [::c_long; 0],
        #[cfg(not(any(target_arch = "mips", target_arch = "mipsel",
                      target_arch = "arm")))]
        __align: [::c_longlong; 0],
        size: [u8; __SIZEOF_PTHREAD_RWLOCK_T],
    }

    pub struct pthread_mutexattr_t {
        __align: [::c_long; 0],
        size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T],
    }

    pub struct pthread_cond_t {
        __align: [::c_longlong; 0],
        size: [u8; __SIZEOF_PTHREAD_COND_T],
    }

    pub struct passwd {
        pub pw_name: *mut ::c_char,
        pub pw_passwd: *mut ::c_char,
        pub pw_uid: ::uid_t,
        pub pw_gid: ::gid_t,
        pub pw_gecos: *mut ::c_char,
        pub pw_dir: *mut ::c_char,
        pub pw_shell: *mut ::c_char,
    }
}

pub const BUFSIZ: ::c_uint = 8192;
pub const FILENAME_MAX: ::c_uint = 4096;
pub const FOPEN_MAX: ::c_uint = 16;
pub const L_tmpnam: ::c_uint = 20;
pub const TMP_MAX: ::c_uint = 238328;
pub const _PC_NAME_MAX: ::c_int = 3;

pub const _SC_ARG_MAX: ::c_int = 0;
pub const _SC_CHILD_MAX: ::c_int = 1;
pub const _SC_CLK_TCK: ::c_int = 2;
pub const _SC_NGROUPS_MAX: ::c_int = 3;
pub const _SC_OPEN_MAX: ::c_int = 4;
pub const _SC_STREAM_MAX: ::c_int = 5;
pub const _SC_TZNAME_MAX: ::c_int = 6;
pub const _SC_JOB_CONTROL: ::c_int = 7;
pub const _SC_SAVED_IDS: ::c_int = 8;
pub const _SC_REALTIME_SIGNALS: ::c_int = 9;
pub const _SC_PRIORITY_SCHEDULING: ::c_int = 10;
pub const _SC_TIMERS: ::c_int = 11;
pub const _SC_ASYNCHRONOUS_IO: ::c_int = 12;
pub const _SC_PRIORITIZED_IO: ::c_int = 13;
pub const _SC_SYNCHRONIZED_IO: ::c_int = 14;
pub const _SC_FSYNC: ::c_int = 15;
pub const _SC_MAPPED_FILES: ::c_int = 16;
pub const _SC_MEMLOCK: ::c_int = 17;
pub const _SC_MEMLOCK_RANGE: ::c_int = 18;
pub const _SC_MEMORY_PROTECTION: ::c_int = 19;
pub const _SC_MESSAGE_PASSING: ::c_int = 20;
pub const _SC_SEMAPHORES: ::c_int = 21;
pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 22;
pub const _SC_AIO_LISTIO_MAX: ::c_int = 23;
pub const _SC_AIO_MAX: ::c_int = 24;
pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 25;
pub const _SC_DELAYTIMER_MAX: ::c_int = 26;
pub const _SC_MQ_OPEN_MAX: ::c_int = 27;
pub const _SC_MQ_PRIO_MAX: ::c_int = 28;
pub const _SC_VERSION: ::c_int = 29;
pub const _SC_PAGESIZE: ::c_int = 30;
pub const _SC_RTSIG_MAX: ::c_int = 31;
pub const _SC_SEM_NSEMS_MAX: ::c_int = 32;
pub const _SC_SEM_VALUE_MAX: ::c_int = 33;
pub const _SC_SIGQUEUE_MAX: ::c_int = 34;
pub const _SC_TIMER_MAX: ::c_int = 35;
pub const _SC_BC_BASE_MAX: ::c_int = 36;
pub const _SC_BC_DIM_MAX: ::c_int = 37;
pub const _SC_BC_SCALE_MAX: ::c_int = 38;
pub const _SC_BC_STRING_MAX: ::c_int = 39;
pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 40;
pub const _SC_EXPR_NEST_MAX: ::c_int = 42;
pub const _SC_LINE_MAX: ::c_int = 43;
pub const _SC_RE_DUP_MAX: ::c_int = 44;
pub const _SC_2_VERSION: ::c_int = 46;
pub const _SC_2_C_BIND: ::c_int = 47;
pub const _SC_2_C_DEV: ::c_int = 48;
pub const _SC_2_FORT_DEV: ::c_int = 49;
pub const _SC_2_FORT_RUN: ::c_int = 50;
pub const _SC_2_SW_DEV: ::c_int = 51;
pub const _SC_2_LOCALEDEF: ::c_int = 52;
pub const _SC_IOV_MAX: ::c_int = 60;
pub const _SC_THREADS: ::c_int = 67;
pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 68;
pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 69;
pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 70;
pub const _SC_LOGIN_NAME_MAX: ::c_int = 71;
pub const _SC_TTY_NAME_MAX: ::c_int = 72;
pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 73;
pub const _SC_THREAD_KEYS_MAX: ::c_int = 74;
pub const _SC_THREAD_STACK_MIN: ::c_int = 75;
pub const _SC_THREAD_THREADS_MAX: ::c_int = 76;
pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 77;
pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 78;
pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 79;
pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 80;
pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 81;
pub const _SC_NPROCESSORS_ONLN: ::c_int = 84;
pub const _SC_ATEXIT_MAX: ::c_int = 87;
pub const _SC_XOPEN_VERSION: ::c_int = 89;
pub const _SC_XOPEN_XCU_VERSION: ::c_int = 90;
pub const _SC_XOPEN_UNIX: ::c_int = 91;
pub const _SC_XOPEN_CRYPT: ::c_int = 92;
pub const _SC_XOPEN_ENH_I18N: ::c_int = 93;
pub const _SC_XOPEN_SHM: ::c_int = 94;
pub const _SC_2_CHAR_TERM: ::c_int = 95;
pub const _SC_2_C_VERSION: ::c_int = 96;
pub const _SC_2_UPE: ::c_int = 97;
pub const _SC_XBS5_ILP32_OFF32: ::c_int = 125;
pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 126;
pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 128;
pub const _SC_XOPEN_LEGACY: ::c_int = 129;
pub const _SC_XOPEN_REALTIME: ::c_int = 130;
pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 131;

pub const RLIM_SAVED_MAX: ::rlim_t = RLIM_INFINITY;
pub const RLIM_SAVED_CUR: ::rlim_t = RLIM_INFINITY;

#[cfg(not(target_env = "musl"))]
pub const RUSAGE_THREAD: ::c_int = 1;

pub const GLOB_ERR: ::c_int = 1 << 0;
pub const GLOB_MARK: ::c_int = 1 << 1;
pub const GLOB_NOSORT: ::c_int = 1 << 2;
pub const GLOB_DOOFFS: ::c_int = 1 << 3;
pub const GLOB_NOCHECK: ::c_int = 1 << 4;
pub const GLOB_APPEND: ::c_int = 1 << 5;
pub const GLOB_NOESCAPE: ::c_int = 1 << 6;

pub const GLOB_NOSPACE: ::c_int = 1;
pub const GLOB_ABORTED: ::c_int = 2;
pub const GLOB_NOMATCH: ::c_int = 3;

pub const POSIX_MADV_NORMAL: ::c_int = 0;
pub const POSIX_MADV_RANDOM: ::c_int = 1;
pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2;
pub const POSIX_MADV_WILLNEED: ::c_int = 3;
pub const POSIX_MADV_DONTNEED: ::c_int = 4;

pub const S_IEXEC: mode_t = 64;
pub const S_IWRITE: mode_t = 128;
pub const S_IREAD: mode_t = 256;

pub const F_LOCK: ::c_int = 1;
pub const F_TEST: ::c_int = 3;
pub const F_TLOCK: ::c_int = 2;
pub const F_ULOCK: ::c_int = 0;

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub const MAP_32BIT: ::c_int = 0x0040;

pub const TCP_MD5SIG: ::c_int = 14;

pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t {
    __align: [],
    size: [0; __SIZEOF_PTHREAD_MUTEX_T],
};
pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t {
    __align: [],
    size: [0; __SIZEOF_PTHREAD_COND_T],
};
pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t {
    __align: [],
    size: [0; __SIZEOF_PTHREAD_RWLOCK_T],
};
pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1;
pub const __SIZEOF_PTHREAD_COND_T: usize = 48;

extern {
    pub fn shm_open(name: *const c_char, oflag: ::c_int,
                    mode: mode_t) -> ::c_int;
    #[cfg(not(target_env = "musl"))]
    pub fn sysctl(name: *mut ::c_int,
                  namelen: ::c_int,
                  oldp: *mut ::c_void,
                  oldlenp: *mut size_t,
                  newp: *mut ::c_void,
                  newlen: size_t)
                  -> ::c_int;
    pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int)
                    -> ::c_int;
    pub fn __errno_location() -> *mut ::c_int;
}

cfg_if! {
    if #[cfg(any(target_arch = "arm", target_arch = "x86",
                 target_arch = "x86_64"))] {
        pub const PTHREAD_STACK_MIN: size_t = 16384;
    } else {
        pub const PTHREAD_STACK_MIN: size_t = 131072;
    }
}

cfg_if! {
    if #[cfg(any(target_arch = "mips", target_arch = "mipsel"))] {
        mod mips;
        pub use self::mips::*;
    } else {
        mod notmips;
        pub use self::notmips::*;
    }
}
<commit_msg>Fix x86_64 linux<commit_after>//! Linux-specific definitions for linux-like values

pub type useconds_t = u32;
pub type dev_t = u64;
pub type socklen_t = u32;
pub type pthread_t = c_ulong;

s! {
    pub struct glob_t {
        pub gl_pathc: size_t,
        pub gl_pathv: *mut *mut c_char,
        pub gl_offs:  size_t,
        pub gl_flags: ::c_int,

        __unused1: *mut ::c_void,
        __unused2: *mut ::c_void,
        __unused3: *mut ::c_void,
        __unused4: *mut ::c_void,
        __unused5: *mut ::c_void,
    }

    pub struct ifaddrs {
        pub ifa_next: *mut ifaddrs,
        pub ifa_name: *mut c_char,
        pub ifa_flags: ::c_uint,
        pub ifa_addr: *mut ::sockaddr,
        pub ifa_netmask: *mut ::sockaddr,
        pub ifa_ifu: *mut ::sockaddr, // FIXME This should be a union
        pub ifa_data: *mut ::c_void
    }

    pub struct pthread_mutex_t {
        #[cfg(any(target_arch = "mips", target_arch = "mipsel",
                  target_arch = "arm"))]
        __align: [::c_long; 0],
        #[cfg(not(any(target_arch = "mips", target_arch = "mipsel",
                      target_arch = "arm")))]
        __align: [::c_longlong; 0],
        size: [u8; __SIZEOF_PTHREAD_MUTEX_T],
    }

    pub struct pthread_rwlock_t {
        #[cfg(any(target_arch = "mips", target_arch = "mipsel",
                  target_arch = "arm"))]
        __align: [::c_long; 0],
        #[cfg(not(any(target_arch = "mips", target_arch = "mipsel",
                      target_arch = "arm")))]
        __align: [::c_longlong; 0],
        size: [u8; __SIZEOF_PTHREAD_RWLOCK_T],
    }

    pub struct pthread_mutexattr_t {
        #[cfg(target_arch = "x86_64")]
        __align: [::c_int; 0],
        #[cfg(not(target_arch = "x86_64"))]
        __align: [::c_long; 0],
        size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T],
    }

    pub struct pthread_cond_t {
        __align: [::c_longlong; 0],
        size: [u8; __SIZEOF_PTHREAD_COND_T],
    }

    pub struct passwd {
        pub pw_name: *mut ::c_char,
        pub pw_passwd: *mut ::c_char,
        pub pw_uid: ::uid_t,
        pub pw_gid: ::gid_t,
        pub pw_gecos: *mut ::c_char,
        pub pw_dir: *mut ::c_char,
        pub pw_shell: *mut ::c_char,
    }
}

pub const BUFSIZ: ::c_uint = 8192;
pub const FILENAME_MAX: ::c_uint = 4096;
pub const FOPEN_MAX: ::c_uint = 16;
pub const L_tmpnam: ::c_uint = 20;
pub const TMP_MAX: ::c_uint = 238328;
pub const _PC_NAME_MAX: ::c_int = 3;

pub const _SC_ARG_MAX: ::c_int = 0;
pub const _SC_CHILD_MAX: ::c_int = 1;
pub const _SC_CLK_TCK: ::c_int = 2;
pub const _SC_NGROUPS_MAX: ::c_int = 3;
pub const _SC_OPEN_MAX: ::c_int = 4;
pub const _SC_STREAM_MAX: ::c_int = 5;
pub const _SC_TZNAME_MAX: ::c_int = 6;
pub const _SC_JOB_CONTROL: ::c_int = 7;
pub const _SC_SAVED_IDS: ::c_int = 8;
pub const _SC_REALTIME_SIGNALS: ::c_int = 9;
pub const _SC_PRIORITY_SCHEDULING: ::c_int = 10;
pub const _SC_TIMERS: ::c_int = 11;
pub const _SC_ASYNCHRONOUS_IO: ::c_int = 12;
pub const _SC_PRIORITIZED_IO: ::c_int = 13;
pub const _SC_SYNCHRONIZED_IO: ::c_int = 14;
pub const _SC_FSYNC: ::c_int = 15;
pub const _SC_MAPPED_FILES: ::c_int = 16;
pub const _SC_MEMLOCK: ::c_int = 17;
pub const _SC_MEMLOCK_RANGE: ::c_int = 18;
pub const _SC_MEMORY_PROTECTION: ::c_int = 19;
pub const _SC_MESSAGE_PASSING: ::c_int = 20;
pub const _SC_SEMAPHORES: ::c_int = 21;
pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 22;
pub const _SC_AIO_LISTIO_MAX: ::c_int = 23;
pub const _SC_AIO_MAX: ::c_int = 24;
pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 25;
pub const _SC_DELAYTIMER_MAX: ::c_int = 26;
pub const _SC_MQ_OPEN_MAX: ::c_int = 27;
pub const _SC_MQ_PRIO_MAX: ::c_int = 28;
pub const _SC_VERSION: ::c_int = 29;
pub const _SC_PAGESIZE: ::c_int = 30;
pub const _SC_RTSIG_MAX: ::c_int = 31;
pub const _SC_SEM_NSEMS_MAX: ::c_int = 32;
pub const _SC_SEM_VALUE_MAX: ::c_int = 33;
pub const _SC_SIGQUEUE_MAX: ::c_int = 34;
pub const _SC_TIMER_MAX: ::c_int = 35;
pub const _SC_BC_BASE_MAX: ::c_int = 36;
pub const _SC_BC_DIM_MAX: ::c_int = 37;
pub const _SC_BC_SCALE_MAX: ::c_int = 38;
pub const _SC_BC_STRING_MAX: ::c_int = 39;
pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 40;
pub const _SC_EXPR_NEST_MAX: ::c_int = 42;
pub const _SC_LINE_MAX: ::c_int = 43;
pub const _SC_RE_DUP_MAX: ::c_int = 44;
pub const _SC_2_VERSION: ::c_int = 46;
pub const _SC_2_C_BIND: ::c_int = 47;
pub const _SC_2_C_DEV: ::c_int = 48;
pub const _SC_2_FORT_DEV: ::c_int = 49;
pub const _SC_2_FORT_RUN: ::c_int = 50;
pub const _SC_2_SW_DEV: ::c_int = 51;
pub const _SC_2_LOCALEDEF: ::c_int = 52;
pub const _SC_IOV_MAX: ::c_int = 60;
pub const _SC_THREADS: ::c_int = 67;
pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 68;
pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 69;
pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 70;
pub const _SC_LOGIN_NAME_MAX: ::c_int = 71;
pub const _SC_TTY_NAME_MAX: ::c_int = 72;
pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 73;
pub const _SC_THREAD_KEYS_MAX: ::c_int = 74;
pub const _SC_THREAD_STACK_MIN: ::c_int = 75;
pub const _SC_THREAD_THREADS_MAX: ::c_int = 76;
pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 77;
pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 78;
pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 79;
pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 80;
pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 81;
pub const _SC_NPROCESSORS_ONLN: ::c_int = 84;
pub const _SC_ATEXIT_MAX: ::c_int = 87;
pub const _SC_XOPEN_VERSION: ::c_int = 89;
pub const _SC_XOPEN_XCU_VERSION: ::c_int = 90;
pub const _SC_XOPEN_UNIX: ::c_int = 91;
pub const _SC_XOPEN_CRYPT: ::c_int = 92;
pub const _SC_XOPEN_ENH_I18N: ::c_int = 93;
pub const _SC_XOPEN_SHM: ::c_int = 94;
pub const _SC_2_CHAR_TERM: ::c_int = 95;
pub const _SC_2_C_VERSION: ::c_int = 96;
pub const _SC_2_UPE: ::c_int = 97;
pub const _SC_XBS5_ILP32_OFF32: ::c_int = 125;
pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 126;
pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 128;
pub const _SC_XOPEN_LEGACY: ::c_int = 129;
pub const _SC_XOPEN_REALTIME: ::c_int = 130;
pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 131;

pub const RLIM_SAVED_MAX: ::rlim_t = RLIM_INFINITY;
pub const RLIM_SAVED_CUR: ::rlim_t = RLIM_INFINITY;

#[cfg(not(target_env = "musl"))]
pub const RUSAGE_THREAD: ::c_int = 1;

pub const GLOB_ERR: ::c_int = 1 << 0;
pub const GLOB_MARK: ::c_int = 1 << 1;
pub const GLOB_NOSORT: ::c_int = 1 << 2;
pub const GLOB_DOOFFS: ::c_int = 1 << 3;
pub const GLOB_NOCHECK: ::c_int = 1 << 4;
pub const GLOB_APPEND: ::c_int = 1 << 5;
pub const GLOB_NOESCAPE: ::c_int = 1 << 6;

pub const GLOB_NOSPACE: ::c_int = 1;
pub const GLOB_ABORTED: ::c_int = 2;
pub const GLOB_NOMATCH: ::c_int = 3;

pub const POSIX_MADV_NORMAL: ::c_int = 0;
pub const POSIX_MADV_RANDOM: ::c_int = 1;
pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2;
pub const POSIX_MADV_WILLNEED: ::c_int = 3;
pub const POSIX_MADV_DONTNEED: ::c_int = 4;

pub const S_IEXEC: mode_t = 64;
pub const S_IWRITE: mode_t = 128;
pub const S_IREAD: mode_t = 256;

pub const F_LOCK: ::c_int = 1;
pub const F_TEST: ::c_int = 3;
pub const F_TLOCK: ::c_int = 2;
pub const F_ULOCK: ::c_int = 0;

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub const MAP_32BIT: ::c_int = 0x0040;

pub const TCP_MD5SIG: ::c_int = 14;

pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t {
    __align: [],
    size: [0; __SIZEOF_PTHREAD_MUTEX_T],
};
pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t {
    __align: [],
    size: [0; __SIZEOF_PTHREAD_COND_T],
};
pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t {
    __align: [],
    size: [0; __SIZEOF_PTHREAD_RWLOCK_T],
};
pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1;
pub const __SIZEOF_PTHREAD_COND_T: usize = 48;

extern {
    pub fn shm_open(name: *const c_char, oflag: ::c_int,
                    mode: mode_t) -> ::c_int;
    #[cfg(not(target_env = "musl"))]
    pub fn sysctl(name: *mut ::c_int,
                  namelen: ::c_int,
                  oldp: *mut ::c_void,
                  oldlenp: *mut size_t,
                  newp: *mut ::c_void,
                  newlen: size_t)
                  -> ::c_int;
    pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int)
                    -> ::c_int;
    pub fn __errno_location() -> *mut ::c_int;
}

cfg_if! {
    if #[cfg(any(target_arch = "arm", target_arch = "x86",
                 target_arch = "x86_64"))] {
        pub const PTHREAD_STACK_MIN: size_t = 16384;
    } else {
        pub const PTHREAD_STACK_MIN: size_t = 131072;
    }
}

cfg_if! {
    if #[cfg(any(target_arch = "mips", target_arch = "mipsel"))] {
        mod mips;
        pub use self::mips::*;
    } else {
        mod notmips;
        pub use self::notmips::*;
    }
}
<|endoftext|>


<commit_before>use utils::data::{Dataset, SamplerIntf, RandomSampler, SequentialSampler, Sampler};
use std::slice;
use tensor::Tensor;
use torch;
use ::*;

pub type Batch<dT, tT> = (Tensor<dT>, Tensor<tT>);
pub type BatchLoader<idT: 'static, itT: 'static, edT: 'static, etT: 'static> =
    DataLoader<Batch<idT, itT>, Batch<edT, etT>>;

pub struct DataLoader<T: Clone + 'static, R: Clone + 'static> {
    pub dataset: Dataset<T, R>,
    batch_size: usize,
    num_workers: usize,
    pin_memory: bool,
    drop_last: bool,
    sampler: Sampler,
}

#[derive(Builder)]
pub struct DataLoaderArgs {
    #[builder(default="1")]
    pub batch_size: usize,
    #[builder(default="0")]
    pub num_workers: usize,
    #[builder(default="false")]
    pub pin_memory: bool,
    #[builder(default="false")]
    pub drop_last: bool,
    #[builder(default="false")]
    pub shuffle: bool,
    #[builder(default="None")]
    pub sampler: Option<Sampler>,
}

impl Default for DataLoaderArgs {
    fn default() -> Self {
        DataLoaderArgsBuilder::default().build().unwrap()
    }
}

impl<T: Clone + 'static, R: Clone + 'static> DataLoader<T, R> {
    pub fn new(dataset: Dataset<T, R>, args: DataLoaderArgs) -> Self {
        let sampler = match args.sampler {
            Some(sampler) => sampler,
            None => {
                if args.shuffle {
                    RandomSampler::new(dataset.len())
                } else {
                    SequentialSampler::new(dataset.len())
                }
            }
        };
        DataLoader {
            dataset: dataset,
            batch_size: args.batch_size,
            num_workers: args.num_workers,
            pin_memory: args.pin_memory,
            drop_last: args.drop_last,
            sampler: sampler,
        }
    }
    pub fn iter(&self) -> Box<Iterator<Item = T>> {
        self.dataset.iter()
    }
    pub fn len(&self) -> usize {
        self.dataset.len()
    }
}
<commit_msg>fix compile<commit_after>use utils::data::{Dataset, SamplerIntf, RandomSampler, SequentialSampler, Sampler};
use std::slice;
use tensor::Tensor;
use torch;
use ::*;

pub type Batch<dT, tT> = (Tensor<dT>, Tensor<tT>);
pub type BatchLoader<idT: 'static, itT: 'static, edT: 'static, etT: 'static> =
    DataLoader<Batch<idT, itT>, Batch<edT, etT>>;

pub struct DataLoader<T: Clone + 'static, R: Clone + 'static> {
    pub dataset: Dataset<T, R>,
    batch_size: usize,
    num_workers: usize,
    pin_memory: bool,
    drop_last: bool,
    sampler: Sampler,
}

#[derive(Builder)]
pub struct DataLoaderArgs {
    #[builder(default="1")]
    pub batch_size: usize,
    #[builder(default="0")]
    pub num_workers: usize,
    #[builder(default="false")]
    pub pin_memory: bool,
    #[builder(default="false")]
    pub drop_last: bool,
    #[builder(default="false")]
    pub shuffle: bool,
    #[builder(default="None")]
    pub sampler: Option<Sampler>,
}

impl Default for DataLoaderArgs {
    fn default() -> Self {
        DataLoaderArgsBuilder::default().build().unwrap()
    }
}

impl<T: Clone + 'static, R: Clone + 'static> DataLoader<T, R> {
    pub fn new(dataset: Dataset<T, R>, args: DataLoaderArgs) -> Self {
        let sampler = match args.sampler {
            Some(sampler) => sampler,
            None => {
                if args.shuffle {
                    RandomSampler::new(dataset.len())
                } else {
                    SequentialSampler::new(dataset.len())
                }
            }
        };
        DataLoader {
            dataset: dataset,
            batch_size: args.batch_size,
            num_workers: args.num_workers,
            pin_memory: args.pin_memory,
            drop_last: args.drop_last,
            sampler: sampler,
        }
    }
    pub fn iter(&self) -> Box<Iterator<Item = R>> {
        self.dataset.iter()
    }
    pub fn len(&self) -> usize {
        self.dataset.len()
    }
}
<|endoftext|>


<commit_before>use crate::attr;
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
    Data, DataEnum, DataStruct, DeriveInput, Error, Field, Fields, Ident, Index, Member, Result,
    Type,
};

pub fn derive(input: &DeriveInput) -> Result<TokenStream> {
    match &input.data {
        Data::Struct(data) => struct_error(input, data),
        Data::Enum(data) => enum_error(input, data),
        Data::Union(_) => Err(Error::new_spanned(
            input,
            "union as errors are not supported",
        )),
    }
}

fn struct_error(input: &DeriveInput, data: &DataStruct) -> Result<TokenStream> {
    let ident = &input.ident;
    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    let source = match &data.fields {
        Fields::Named(fields) => source_member(&fields.named)?,
        Fields::Unnamed(fields) => source_member(&fields.unnamed)?,
        Fields::Unit => None,
    };

    let backtrace = match &data.fields {
        Fields::Named(fields) => backtrace_member(&fields.named)?,
        Fields::Unnamed(fields) => backtrace_member(&fields.unnamed)?,
        Fields::Unit => None,
    };

    let source_method = source.map(|source| {
        quote! {
            fn source(&self) -> std::option::Option<&(dyn std::error::Error + 'static)> {
                std::option::Option::Some(&self.#source)
            }
        }
    });

    let backtrace_method = backtrace.map(|backtrace| {
        quote! {
            fn backtrace(&self) -> std::option::Option<&std::backtrace::Backtrace> {
                std::option::Option::Some(&self.#backtrace)
            }
        }
    });

    Ok(quote! {
        impl #impl_generics std::error::Error for #ident #ty_generics #where_clause {
            #source_method
            #backtrace_method
        }
    })
}

fn source_member<'a>(fields: impl IntoIterator<Item = &'a Field>) -> Result<Option<Member>> {
    for (i, field) in fields.into_iter().enumerate() {
        if attr::is_source(field)? {
            return Ok(Some(member(i, &field.ident)));
        }
    }
    Ok(None)
}

fn backtrace_member<'a>(fields: impl IntoIterator<Item = &'a Field>) -> Result<Option<Member>> {
    for (i, field) in fields.into_iter().enumerate() {
        if type_is_backtrace(&field.ty) {
            return Ok(Some(member(i, &field.ident)));
        }
    }
    Ok(None)
}

fn type_is_backtrace(ty: &Type) -> bool {
    let path = match ty {
        Type::Path(ty) => &ty.path,
        _ => return false,
    };

    let last = path.segments.last().unwrap();
    last.ident == "Backtrace" && last.arguments.is_empty()
}

fn member(i: usize, ident: &Option<Ident>) -> Member {
    match ident {
        Some(ident) => Member::Named(ident.clone()),
        None => Member::Unnamed(Index::from(i)),
    }
}

fn enum_error(input: &DeriveInput, data: &DataEnum) -> Result<TokenStream> {
    let _ = input;
    let _ = data;
    unimplemented!()
}
<commit_msg>Improve error position when cause is wrong type<commit_after>use crate::attr;
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{
    Data, DataEnum, DataStruct, DeriveInput, Error, Field, Fields, Ident, Index, Member, Result,
    Type,
};

pub fn derive(input: &DeriveInput) -> Result<TokenStream> {
    match &input.data {
        Data::Struct(data) => struct_error(input, data),
        Data::Enum(data) => enum_error(input, data),
        Data::Union(_) => Err(Error::new_spanned(
            input,
            "union as errors are not supported",
        )),
    }
}

fn struct_error(input: &DeriveInput, data: &DataStruct) -> Result<TokenStream> {
    let ident = &input.ident;
    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    let source = match &data.fields {
        Fields::Named(fields) => source_member(&fields.named)?,
        Fields::Unnamed(fields) => source_member(&fields.unnamed)?,
        Fields::Unit => None,
    };

    let backtrace = match &data.fields {
        Fields::Named(fields) => backtrace_member(&fields.named)?,
        Fields::Unnamed(fields) => backtrace_member(&fields.unnamed)?,
        Fields::Unit => None,
    };

    let source_method = source.map(|source| {
        let member = quote_spanned!(source.span()=> &self.#source);
        quote! {
            fn source(&self) -> std::option::Option<&(dyn std::error::Error + 'static)> {
                std::option::Option::Some(#member)
            }
        }
    });

    let backtrace_method = backtrace.map(|backtrace| {
        quote! {
            fn backtrace(&self) -> std::option::Option<&std::backtrace::Backtrace> {
                std::option::Option::Some(&self.#backtrace)
            }
        }
    });

    Ok(quote! {
        impl #impl_generics std::error::Error for #ident #ty_generics #where_clause {
            #source_method
            #backtrace_method
        }
    })
}

fn source_member<'a>(fields: impl IntoIterator<Item = &'a Field>) -> Result<Option<Member>> {
    for (i, field) in fields.into_iter().enumerate() {
        if attr::is_source(field)? {
            return Ok(Some(member(i, &field.ident)));
        }
    }
    Ok(None)
}

fn backtrace_member<'a>(fields: impl IntoIterator<Item = &'a Field>) -> Result<Option<Member>> {
    for (i, field) in fields.into_iter().enumerate() {
        if type_is_backtrace(&field.ty) {
            return Ok(Some(member(i, &field.ident)));
        }
    }
    Ok(None)
}

fn type_is_backtrace(ty: &Type) -> bool {
    let path = match ty {
        Type::Path(ty) => &ty.path,
        _ => return false,
    };

    let last = path.segments.last().unwrap();
    last.ident == "Backtrace" && last.arguments.is_empty()
}

fn member(i: usize, ident: &Option<Ident>) -> Member {
    match ident {
        Some(ident) => Member::Named(ident.clone()),
        None => Member::Unnamed(Index::from(i)),
    }
}

fn enum_error(input: &DeriveInput, data: &DataEnum) -> Result<TokenStream> {
    let _ = input;
    let _ = data;
    unimplemented!()
}
<|endoftext|>


<commit_before>use crate::definitions::{DefKey, DefPathData, DisambiguatedDefPathData};
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_span::crate_disambiguator::CrateDisambiguator;
use rustc_span::def_id::{DefPathHash, StableCrateId};

#[test]
fn def_path_hash_depends_on_crate_id() {
    // This test makes sure that *both* halves of a DefPathHash depend on
    // the crate-id of the defining crate. This is a desirable property
    // because the crate-id can be more easily changed than the DefPath
    // of an item, so, in the case of a crate-local DefPathHash collision,
    // the user can simply "role the dice again" for all DefPathHashes in
    // the crate by changing the crate disambiguator (e.g. via bumping the
    // crate's version number).

    let d0 = CrateDisambiguator::from(Fingerprint::new(12, 34));
    let d1 = CrateDisambiguator::from(Fingerprint::new(56, 78));

    let h0 = mk_test_hash("foo", d0);
    let h1 = mk_test_hash("foo", d1);

    assert_ne!(h0.stable_crate_id(), h1.stable_crate_id());
    assert_ne!(h0.local_hash(), h1.local_hash());

    fn mk_test_hash(crate_name: &str, crate_disambiguator: CrateDisambiguator) -> DefPathHash {
        let stable_crate_id = StableCrateId::new(crate_name, crate_disambiguator);
        let parent_hash = DefPathHash::new(stable_crate_id, 0);

        let key = DefKey {
            parent: None,
            disambiguated_data: DisambiguatedDefPathData {
                data: DefPathData::CrateRoot,
                disambiguator: 0,
            },
        };

        key.compute_stable_hash(parent_hash)
    }
}
<commit_msg>Revert "Revert "Fix test""<commit_after>use crate::definitions::{DefKey, DefPathData, DisambiguatedDefPathData};
use rustc_span::def_id::{DefPathHash, StableCrateId};

#[test]
fn def_path_hash_depends_on_crate_id() {
    // This test makes sure that *both* halves of a DefPathHash depend on
    // the crate-id of the defining crate. This is a desirable property
    // because the crate-id can be more easily changed than the DefPath
    // of an item, so, in the case of a crate-local DefPathHash collision,
    // the user can simply "role the dice again" for all DefPathHashes in
    // the crate by changing the crate disambiguator (e.g. via bumping the
    // crate's version number).

    let id0 = StableCrateId::new("foo", false, vec!["1".to_string()]);
    let id1 = StableCrateId::new("foo", false, vec!["2".to_string()]);

    let h0 = mk_test_hash(id0);
    let h1 = mk_test_hash(id1);

    assert_ne!(h0.stable_crate_id(), h1.stable_crate_id());
    assert_ne!(h0.local_hash(), h1.local_hash());

    fn mk_test_hash(stable_crate_id: StableCrateId) -> DefPathHash {
        let parent_hash = DefPathHash::new(stable_crate_id, 0);

        let key = DefKey {
            parent: None,
            disambiguated_data: DisambiguatedDefPathData {
                data: DefPathData::CrateRoot,
                disambiguator: 0,
            },
        };

        key.compute_stable_hash(parent_hash)
    }
}
<|endoftext|>


<commit_before>//! Utilities not directly related to parsing, lexing, or
//! language-manipulation.

/// Panic with a given message unless an expression evaluates to true.
///
/// ## Examples
/// ```should_fail
/// #[macro_use] use cripes::util;
/// panic_unless!(1 + 1 == 2, "Math is broken.");
/// ```
#[macro_export]
macro_rules! panic_unless {
    ($condition:expr, $($rest:expr),+) => ({ if ! $condition { panic!($($rest),+); } });
}

//#[macro_use]
//pub mod intrusive;

#[doc(hidden)]
macro_rules! impl_methods {
    ($body_macro:ident; $(,)*) => {};
    /* args: (&mut self) */
    ($body_macro:ident; $method:ident(&mut self) -> $ret:ty, $($rest: tt)*)
    => (fn $method(&mut self) -> $ret { $body_macro!($method; mut, self, ) }
        impl_methods!($body_macro; $($rest)*););

    /* args: (&mut self, ...) */
    ($body_macro:ident; $method:ident(&mut self, $($arg:ident: $typ:ty),+) -> $ret:ty, $($rest: tt)*)
        => (fn $method(&mut self, $($arg: $typ),+) -> $ret { $body_macro!($method; mut, self, $($arg),+) }
            impl_methods!($body_macro; $($rest)*););

    /* args: (&self) */
    ($body_macro:ident; $method:ident(&self) -> $ret:ty, $($rest: tt)*)
        => (fn $method(&self) -> $ret { $body_macro!($method; , self, ) }
            impl_methods!($body_macro; $($rest)*););

    /* args: (&self, ...) */
    ($body_macro:ident; $method:ident(&self, $($arg:ident: $typ:ty),+) -> $ret:ty, $($rest: tt)*)
        => (fn $method(&self, $($arg: $typ),+) -> $ret { $body_macro!($method; , self, $($arg),+) }
            impl_methods!($body_macro; $($rest)*););
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_for {
    ($tr:path, $what:path, $body_macro:ident, $($rest: tt)*) => (impl $tr for $what { impl_methods!($body_macro; $($rest)*); });
}
<commit_msg>util: fix examples on `panic_unless` macro<commit_after>//! Utilities not directly related to parsing, lexing, or
//! language-manipulation.

/// Panic with a given message unless an expression evaluates to true.
///
/// ## Examples
/// ```rust
/// # #[macro_use] extern crate cripes;
/// # fn main() {
/// panic_unless!(1 + 1 == 2, "Math is broken.");
/// # }
/// ```
///
/// ```rust,should_panic
/// # #[macro_use] extern crate cripes;
/// # fn main() {
/// panic_unless!(true == false, "I'm broken.");
/// # }
/// ```
#[macro_export]
macro_rules! panic_unless {
    ($condition:expr, $($rest:expr),+) => ({ if ! $condition { panic!($($rest),+); } });
}

//#[macro_use]
//pub mod intrusive;

#[doc(hidden)]
macro_rules! impl_methods {
    ($body_macro:ident; $(,)*) => {};
    /* args: (&mut self) */
    ($body_macro:ident; $method:ident(&mut self) -> $ret:ty, $($rest: tt)*)
    => (fn $method(&mut self) -> $ret { $body_macro!($method; mut, self, ) }
        impl_methods!($body_macro; $($rest)*););

    /* args: (&mut self, ...) */
    ($body_macro:ident; $method:ident(&mut self, $($arg:ident: $typ:ty),+) -> $ret:ty, $($rest: tt)*)
        => (fn $method(&mut self, $($arg: $typ),+) -> $ret { $body_macro!($method; mut, self, $($arg),+) }
            impl_methods!($body_macro; $($rest)*););

    /* args: (&self) */
    ($body_macro:ident; $method:ident(&self) -> $ret:ty, $($rest: tt)*)
        => (fn $method(&self) -> $ret { $body_macro!($method; , self, ) }
            impl_methods!($body_macro; $($rest)*););

    /* args: (&self, ...) */
    ($body_macro:ident; $method:ident(&self, $($arg:ident: $typ:ty),+) -> $ret:ty, $($rest: tt)*)
        => (fn $method(&self, $($arg: $typ),+) -> $ret { $body_macro!($method; , self, $($arg),+) }
            impl_methods!($body_macro; $($rest)*););
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_for {
    ($tr:path, $what:path, $body_macro:ident, $($rest: tt)*) => (impl $tr for $what { impl_methods!($body_macro; $($rest)*); });
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#[macro_export]
macro_rules! make_getter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self) -> DOMString {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            element.get_string_attribute(&Atom::from_slice($htmlname))
        }
    );
    ($attr:ident) => {
        make_getter!($attr, to_lower!(stringify!($attr)));
    }
);

#[macro_export]
macro_rules! make_bool_getter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self) -> bool {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not runtime.
            element.has_attribute(&Atom::from_slice($htmlname))
        }
    );
    ($attr:ident) => {
        make_bool_getter!($attr, to_lower!(stringify!($attr)));
    }
);

#[macro_export]
macro_rules! make_uint_getter(
    ($attr:ident, $htmlname:expr, $default:expr) => (
        fn $attr(self) -> u32 {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not runtime.
            element.get_uint_attribute(&Atom::from_slice($htmlname), $default)
        }
    );
    ($attr:ident, $htmlname:expr) => {
        make_uint_getter!($attr, $htmlname, 0);
    };
    ($attr:ident) => {
        make_uint_getter!($attr, to_lower!(stringify!($attr)));
    }
);

#[macro_export]
macro_rules! make_url_getter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self) -> DOMString {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not runtime.
            element.get_url_attribute(&Atom::from_slice($htmlname))
        }
    );
    ($attr:ident) => {
        // FIXME(pcwalton): Do this at compile time, not runtime.
        make_url_getter!($attr, to_lower!(stringify!($attr)));
    }
);

#[macro_export]
macro_rules! make_url_or_base_getter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self) -> DOMString {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use dom::window::WindowHelpers;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            let url = element.get_url_attribute(&Atom::from_slice($htmlname));
            if url.is_empty() {
                let window = window_from_node(self);
                window.r().get_url().serialize()
            } else {
                url
            }
        }
    );
    ($attr:ident) => {
        make_url_or_base_getter!($attr, to_lower!(stringify!($attr)));
    }
);

#[macro_export]
macro_rules! make_enumerated_getter(
    ( $attr:ident, $htmlname:expr, $default:expr, $(($choices: pat))|+) => (
        fn $attr(self) -> DOMString {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            use std::borrow::ToOwned;
            let element = ElementCast::from_ref(self);
            let val = element.get_string_attribute(&Atom::from_slice($htmlname))
                             .into_ascii_lowercase();
            // https://html.spec.whatwg.org/multipage/#attr-fs-method
            match &*val {
                $($choices)|+ => val,
                _ => $default.to_owned()
            }
        }
    );
    ($attr:ident, $default:expr, $(($choices: pat))|+) => {
        make_enumerated_getter!($attr, &to_lower!(stringify!($attr)), $default, $(($choices))|+);
    }
);

// concat_idents! doesn't work for function name positions, so
// we have to specify both the content name and the HTML name here
#[macro_export]
macro_rules! make_setter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self, value: DOMString) {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not at runtime.
            element.set_string_attribute(&Atom::from_slice($htmlname), value)
        }
    );
);

#[macro_export]
macro_rules! make_bool_setter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self, value: bool) {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not at runtime.
            element.set_bool_attribute(&Atom::from_slice($htmlname), value)
        }
    );
);

#[macro_export]
macro_rules! make_uint_setter(
    ($attr:ident, $htmlname:expr, $default:expr) => (
        fn $attr(self, value: u32) {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let value = if value > 2147483647 {
                $default
            } else {
                value
            };
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not at runtime.
            element.set_uint_attribute(&Atom::from_slice($htmlname), value)
        }
    );
    ($attr:ident, $htmlname:expr) => {
        make_uint_setter!($attr, $htmlname, 0);
    };
);

#[macro_export]
macro_rules! make_limited_uint_setter(
    ($attr:ident, $htmlname:expr, $default:expr) => (
        fn $attr(self, value: u32) -> $crate::dom::bindings::error::ErrorResult {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let value = if value == 0 {
                return Err($crate::dom::bindings::error::Error::IndexSize);
            } else if value > 2147483647 {
                $default
            } else {
                value
            };
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not runtime.
            element.set_uint_attribute(&Atom::from_slice($htmlname), value);
            Ok(())
        }
    );
    ($attr:ident, $htmlname:expr) => {
        make_limited_uint_setter!($attr, $htmlname, 1);
    };
    ($attr:ident) => {
        make_limited_uint_setter!($attr, to_lower!(stringify!($attr)));
    };
);

#[macro_export]
macro_rules! make_atomic_setter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self, value: DOMString) {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not at runtime.
            element.set_atomic_attribute(&Atom::from_slice($htmlname), value)
        }
    );
);

/// For use on non-jsmanaged types
/// Use #[jstraceable] on JS managed types
macro_rules! no_jsmanaged_fields(
    ($($ty:ident),+) => (
        $(
            impl $crate::dom::bindings::trace::JSTraceable for $ty {
                #[inline]
                fn trace(&self, _: *mut ::js::jsapi::JSTracer) {
                    // Do nothing
                }
            }
        )+
    );
    ($ty:ident<$($gen:ident),+>) => (
        impl<$($gen),+> $crate::dom::bindings::trace::JSTraceable for $ty<$($gen),+> {
            #[inline]
            fn trace(&self, _: *mut ::js::jsapi::JSTracer) {
                // Do nothing
            }
        }
    );
);

/// These are used to generate a event handler which has no special case.
macro_rules! define_event_handler(
    ($handler: ident, $event_type: ident, $getter: ident, $setter: ident) => (
        fn $getter(self) -> Option<::std::rc::Rc<$handler>> {
            let eventtarget = EventTargetCast::from_ref(self);
            eventtarget.get_event_handler_common(stringify!($event_type))
        }

        fn $setter(self, listener: Option<::std::rc::Rc<$handler>>) {
            let eventtarget = EventTargetCast::from_ref(self);
            eventtarget.set_event_handler_common(stringify!($event_type), listener)
        }
    )
);

macro_rules! event_handler(
    ($event_type: ident, $getter: ident, $setter: ident) => (
        define_event_handler!(EventHandlerNonNull, $event_type, $getter, $setter);
    )
);

macro_rules! error_event_handler(
    ($event_type: ident, $getter: ident, $setter: ident) => (
        define_event_handler!(OnErrorEventHandlerNonNull, $event_type, $getter, $setter);
    )
);

// https://html.spec.whatwg.org/multipage/#globaleventhandlers
// see webidls/EventHandler.webidl
// As more methods get added, just update them here.
macro_rules! global_event_handlers(
    () => (
        event_handler!(load, GetOnload, SetOnload);
        global_event_handlers!(NoOnload);

    );
    (NoOnload) => (
        event_handler!(click, GetOnclick, SetOnclick);
        event_handler!(keydown, GetOnkeydown, SetOnkeydown);
        event_handler!(keypress, GetOnkeypress, SetOnkeypress);
        event_handler!(keypress, GetOnkeyup, SetOnkeyup);
        event_handler!(input, GetOninput, SetOninput);
        event_handler!(change, GetOnchange, SetOnchange);
        event_handler!(submit, GetOnsubmit, SetOnsubmit);
    )
);
<commit_msg>fixup! Add onkey* global event handler attributes<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#[macro_export]
macro_rules! make_getter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self) -> DOMString {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            element.get_string_attribute(&Atom::from_slice($htmlname))
        }
    );
    ($attr:ident) => {
        make_getter!($attr, to_lower!(stringify!($attr)));
    }
);

#[macro_export]
macro_rules! make_bool_getter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self) -> bool {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not runtime.
            element.has_attribute(&Atom::from_slice($htmlname))
        }
    );
    ($attr:ident) => {
        make_bool_getter!($attr, to_lower!(stringify!($attr)));
    }
);

#[macro_export]
macro_rules! make_uint_getter(
    ($attr:ident, $htmlname:expr, $default:expr) => (
        fn $attr(self) -> u32 {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not runtime.
            element.get_uint_attribute(&Atom::from_slice($htmlname), $default)
        }
    );
    ($attr:ident, $htmlname:expr) => {
        make_uint_getter!($attr, $htmlname, 0);
    };
    ($attr:ident) => {
        make_uint_getter!($attr, to_lower!(stringify!($attr)));
    }
);

#[macro_export]
macro_rules! make_url_getter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self) -> DOMString {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not runtime.
            element.get_url_attribute(&Atom::from_slice($htmlname))
        }
    );
    ($attr:ident) => {
        // FIXME(pcwalton): Do this at compile time, not runtime.
        make_url_getter!($attr, to_lower!(stringify!($attr)));
    }
);

#[macro_export]
macro_rules! make_url_or_base_getter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self) -> DOMString {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use dom::window::WindowHelpers;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            let url = element.get_url_attribute(&Atom::from_slice($htmlname));
            if url.is_empty() {
                let window = window_from_node(self);
                window.r().get_url().serialize()
            } else {
                url
            }
        }
    );
    ($attr:ident) => {
        make_url_or_base_getter!($attr, to_lower!(stringify!($attr)));
    }
);

#[macro_export]
macro_rules! make_enumerated_getter(
    ( $attr:ident, $htmlname:expr, $default:expr, $(($choices: pat))|+) => (
        fn $attr(self) -> DOMString {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            use std::borrow::ToOwned;
            let element = ElementCast::from_ref(self);
            let val = element.get_string_attribute(&Atom::from_slice($htmlname))
                             .into_ascii_lowercase();
            // https://html.spec.whatwg.org/multipage/#attr-fs-method
            match &*val {
                $($choices)|+ => val,
                _ => $default.to_owned()
            }
        }
    );
    ($attr:ident, $default:expr, $(($choices: pat))|+) => {
        make_enumerated_getter!($attr, &to_lower!(stringify!($attr)), $default, $(($choices))|+);
    }
);

// concat_idents! doesn't work for function name positions, so
// we have to specify both the content name and the HTML name here
#[macro_export]
macro_rules! make_setter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self, value: DOMString) {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not at runtime.
            element.set_string_attribute(&Atom::from_slice($htmlname), value)
        }
    );
);

#[macro_export]
macro_rules! make_bool_setter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self, value: bool) {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not at runtime.
            element.set_bool_attribute(&Atom::from_slice($htmlname), value)
        }
    );
);

#[macro_export]
macro_rules! make_uint_setter(
    ($attr:ident, $htmlname:expr, $default:expr) => (
        fn $attr(self, value: u32) {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let value = if value > 2147483647 {
                $default
            } else {
                value
            };
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not at runtime.
            element.set_uint_attribute(&Atom::from_slice($htmlname), value)
        }
    );
    ($attr:ident, $htmlname:expr) => {
        make_uint_setter!($attr, $htmlname, 0);
    };
);

#[macro_export]
macro_rules! make_limited_uint_setter(
    ($attr:ident, $htmlname:expr, $default:expr) => (
        fn $attr(self, value: u32) -> $crate::dom::bindings::error::ErrorResult {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let value = if value == 0 {
                return Err($crate::dom::bindings::error::Error::IndexSize);
            } else if value > 2147483647 {
                $default
            } else {
                value
            };
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not runtime.
            element.set_uint_attribute(&Atom::from_slice($htmlname), value);
            Ok(())
        }
    );
    ($attr:ident, $htmlname:expr) => {
        make_limited_uint_setter!($attr, $htmlname, 1);
    };
    ($attr:ident) => {
        make_limited_uint_setter!($attr, to_lower!(stringify!($attr)));
    };
);

#[macro_export]
macro_rules! make_atomic_setter(
    ( $attr:ident, $htmlname:expr ) => (
        fn $attr(self, value: DOMString) {
            use dom::element::AttributeHandlers;
            use dom::bindings::codegen::InheritTypes::ElementCast;
            use string_cache::Atom;
            let element = ElementCast::from_ref(self);
            // FIXME(pcwalton): Do this at compile time, not at runtime.
            element.set_atomic_attribute(&Atom::from_slice($htmlname), value)
        }
    );
);

/// For use on non-jsmanaged types
/// Use #[jstraceable] on JS managed types
macro_rules! no_jsmanaged_fields(
    ($($ty:ident),+) => (
        $(
            impl $crate::dom::bindings::trace::JSTraceable for $ty {
                #[inline]
                fn trace(&self, _: *mut ::js::jsapi::JSTracer) {
                    // Do nothing
                }
            }
        )+
    );
    ($ty:ident<$($gen:ident),+>) => (
        impl<$($gen),+> $crate::dom::bindings::trace::JSTraceable for $ty<$($gen),+> {
            #[inline]
            fn trace(&self, _: *mut ::js::jsapi::JSTracer) {
                // Do nothing
            }
        }
    );
);

/// These are used to generate a event handler which has no special case.
macro_rules! define_event_handler(
    ($handler: ident, $event_type: ident, $getter: ident, $setter: ident) => (
        fn $getter(self) -> Option<::std::rc::Rc<$handler>> {
            let eventtarget = EventTargetCast::from_ref(self);
            eventtarget.get_event_handler_common(stringify!($event_type))
        }

        fn $setter(self, listener: Option<::std::rc::Rc<$handler>>) {
            let eventtarget = EventTargetCast::from_ref(self);
            eventtarget.set_event_handler_common(stringify!($event_type), listener)
        }
    )
);

macro_rules! event_handler(
    ($event_type: ident, $getter: ident, $setter: ident) => (
        define_event_handler!(EventHandlerNonNull, $event_type, $getter, $setter);
    )
);

macro_rules! error_event_handler(
    ($event_type: ident, $getter: ident, $setter: ident) => (
        define_event_handler!(OnErrorEventHandlerNonNull, $event_type, $getter, $setter);
    )
);

// https://html.spec.whatwg.org/multipage/#globaleventhandlers
// see webidls/EventHandler.webidl
// As more methods get added, just update them here.
macro_rules! global_event_handlers(
    () => (
        event_handler!(load, GetOnload, SetOnload);
        global_event_handlers!(NoOnload);

    );
    (NoOnload) => (
        event_handler!(click, GetOnclick, SetOnclick);
        event_handler!(keydown, GetOnkeydown, SetOnkeydown);
        event_handler!(keypress, GetOnkeypress, SetOnkeypress);
        event_handler!(keyup, GetOnkeyup, SetOnkeyup);
        event_handler!(input, GetOninput, SetOninput);
        event_handler!(change, GetOnchange, SetOnchange);
        event_handler!(submit, GetOnsubmit, SetOnsubmit);
    )
);
<|endoftext|>


<commit_before>use llvm_sys::core::LLVMDisposeMessage;
use llvm_sys::execution_engine::{LLVMGetExecutionEngineTargetData, LLVMExecutionEngineRef, LLVMRunFunction, LLVMRunFunctionAsMain, LLVMDisposeExecutionEngine, LLVMGetFunctionAddress, LLVMAddModule, LLVMFindFunction, LLVMLinkInMCJIT, LLVMLinkInInterpreter, LLVMRemoveModule, LLVMGenericValueRef, LLVMFreeMachineCodeForFunction, LLVMGetPointerToGlobal, LLVMAddGlobalMapping};

use module::Module;
use targets::TargetData;
use values::{AnyValue, AsValueRef, FunctionValue, GenericValue, GlobalValue};

use std::ffi::{CStr, CString};
use std::mem::{forget, uninitialized, zeroed};

#[derive(Debug, PartialEq, Eq)]
pub enum FunctionLookupError {
    JITNotEnabled,
    FunctionNotFound, // 404!
}

#[derive(Debug)]
pub struct ExecutionEngine {
    execution_engine: LLVMExecutionEngineRef,
    pub(crate) modules: Vec<Module>,
    target_data: Option<TargetData>,
    jit_mode: bool,
}

impl ExecutionEngine {
    pub(crate) fn new(execution_engine: LLVMExecutionEngineRef, jit_mode: bool) -> ExecutionEngine {
        assert!(!execution_engine.is_null());

        // REVIEW: Will we have to do this for LLVMGetExecutionEngineTargetMachine too?
        let target_data = unsafe {
            LLVMGetExecutionEngineTargetData(execution_engine)
        };

        ExecutionEngine {
            execution_engine: execution_engine,
            modules: vec![],
            target_data: Some(TargetData::new(target_data)),
            jit_mode: jit_mode,
        }
    }

    pub fn link_in_mc_jit() {
        unsafe {
            LLVMLinkInMCJIT()
        }
    }

    pub fn link_in_interpreter() {
        unsafe {
            LLVMLinkInInterpreter();
        }
    }

    /// Maps the specified value to an address.
    ///
    /// # Example
    /// ```
    /// use inkwell::targets::{InitializationConfig, Target};
    /// use inkwell::context::Context;
    /// use inkwell::OptimizationLevel;
    ///
    /// Target::initialize_native(&InitializationConfig::default()).unwrap();
    ///
    /// extern fn sumf(a: f64, b: f64) -> f64 {
    ///     a + b
    /// }
    ///
    /// let context = Context::create();
    /// let module = context.create_module("test");
    /// let builder = context.create_builder();
    ///
    /// let ft = context.f64_type();
    /// let fnt = ft.fn_type(&[], false);
    ///
    /// let f = module.add_function("test_fn", &fnt, None);
    /// let b = context.append_basic_block(&f, "entry");
    /// builder.position_at_end(&b);
    ///
    /// let extf = module.add_function("sumf", &ft.fn_type(&[ &ft, &ft ], false), None);
    ///
    /// let argf = ft.const_float(64.);
    /// let retv = builder.build_call(&extf, &[ &argf, &argf ], "retv", false).left().unwrap().into_float_value();
    ///
    /// builder.build_return(Some(&retv));
    ///
    /// let mut ee = module.create_jit_execution_engine(OptimizationLevel::None).unwrap();
    /// ee.add_global_mapping(&extf, sumf as *mut _);
    ///
    /// let result = unsafe { ee.run_function(&f, &[]) }.as_float(&ft);
    ///
    /// assert_eq!(result, 128.);
    /// ```
    pub fn add_global_mapping(&mut self, value: &AnyValue, addr: *const ()) {
        unsafe {
            LLVMAddGlobalMapping(self.execution_engine, value.as_value_ref(), addr as *mut _)
        }
    }

    // TODOC: EE must *own* modules and deal out references
    pub fn add_module(&mut self, module: Module) -> &Module {
        unsafe {
            LLVMAddModule(self.execution_engine, module.module)
        }

        self.modules.push(module);

        &self.modules[self.modules.len() - 1]
    }

    pub fn remove_module(&mut self, module: &Module) -> Result<Module, String> {
        let mut new_module = unsafe { uninitialized() };
        let mut err_str = unsafe { zeroed() };

        let code = unsafe {
            LLVMRemoveModule(self.execution_engine, module.module, &mut new_module, &mut err_str)
        };

        if code == 1 {
            let rust_str = unsafe {
                let rust_str = CStr::from_ptr(err_str).to_string_lossy().into_owned();

                LLVMDisposeMessage(err_str);

                rust_str
            };

            return Err(rust_str);
        }

        // REVIEW: This might end up a hashtable for better performance
        let mut index = None;

        for (i, owned_module) in self.modules.iter().enumerate() {
            if module == owned_module {
                index = Some(i);
            }
        }

        match index {
            Some(idx) => self.modules.remove(idx),
            None => return Err("Module does not belong to this ExecutionEngine".into()),
        };

        Ok(Module::new(new_module))
    }

    // FIXME: Workaround until we can think of a better API
    // Ideally, we'd provide this as a hashmap from module name to module, but this may not be
    // possible since you can create modules, ie via create_module_from_ir, which either do not
    // have a name, or at least LLVM provides no way to obtain its name. Also, possible collisions
    // depending on how loose, if at all, LLVM is with module names belonging to execution engines
    pub fn get_module_at(&self, index: usize) -> &Module {
        &self.modules[index]
    }

    /// WARNING: The returned address *will* be invalid if the EE drops first
    /// Do not attempt to transmute it to a function if the ExecutionEngine is gone
    // TODOC: Initializing a target MUST occur before creating the EE or else it will not count
    // TODOC: Can still add functions after EE has been created
    pub fn get_function_address(&self, fn_name: &str) -> Result<u64, FunctionLookupError> {
        if !self.jit_mode {
            return Err(FunctionLookupError::JITNotEnabled);
        }

        let c_string = CString::new(fn_name).expect("Conversion to CString failed unexpectedly");

        let address = unsafe {
            LLVMGetFunctionAddress(self.execution_engine, c_string.as_ptr())
        };

        // REVIEW: Can also return 0 if no targets are initialized.
        // One option might be to set a global to true if any at all of the targets have been
        // initialized (maybe we could figure out which config in particular is the trigger)
        // and if not return an "NoTargetsInitialized" error, instead of not found.
        if address == 0 {
            return Err(FunctionLookupError::FunctionNotFound);
        }

        Ok(address)
    }

    // REVIEW: Not sure if an EE's target data can change.. if so we might want to update the value
    // when making this call
    pub fn get_target_data(&self) -> &TargetData {
        self.target_data.as_ref().expect("TargetData should always exist until Drop")
    }

    // REVIEW: Can also find nothing if no targeting is initialized. Maybe best to
    // do have a global flag for anything initialized. Catch is that it must be initialized
    // before EE is created
    pub fn get_function_value(&self, fn_name: &str) -> Result<FunctionValue, FunctionLookupError> {
        if !self.jit_mode {
            return Err(FunctionLookupError::JITNotEnabled);
        }

        let c_string = CString::new(fn_name).expect("Conversion to CString failed unexpectedly");
        let mut function = unsafe { zeroed() };

        let code = unsafe {
            LLVMFindFunction(self.execution_engine, c_string.as_ptr(), &mut function)
        };

        if code == 0 {
            return FunctionValue::new(function).ok_or(FunctionLookupError::FunctionNotFound)
        };

        Err(FunctionLookupError::FunctionNotFound)
    }

    // TODOC: Marked as unsafe because input function could very well do something unsafe. It's up to the caller
    // to ensure that doesn't happen by defining their function correctly.
    pub unsafe fn run_function(&self, function: &FunctionValue, args: &[&GenericValue]) -> GenericValue {
        let mut args: Vec<LLVMGenericValueRef> = args.iter()
                                                     .map(|val| val.generic_value)
                                                     .collect();

        let value = LLVMRunFunction(self.execution_engine, function.as_value_ref(), args.len() as u32, args.as_mut_ptr()); // REVIEW: usize to u32 ok??

        GenericValue::new(value)
    }

    pub fn run_function_as_main(&self, function: &FunctionValue) {
        let args = vec![]; // TODO: Support argc, argv
        let env_p = vec![]; // REVIEW: No clue what this is

        unsafe {
            LLVMRunFunctionAsMain(self.execution_engine, function.as_value_ref(), args.len() as u32, args.as_ptr(), env_p.as_ptr()); // REVIEW: usize to u32 cast ok??
        }
    }

    pub fn free_fn_machine_code(&self, function: &FunctionValue) {
        unsafe {
            LLVMFreeMachineCodeForFunction(self.execution_engine, function.as_value_ref())
        }
    }
}

// Modules owned by the EE will be discarded by the EE so we don't
// want owned modules to drop.
impl Drop for ExecutionEngine {
    fn drop(&mut self) {
        for module in self.modules.drain(..) {
            forget(module);
        }

        forget(self.target_data.take().expect("TargetData should always exist until Drop"));

        unsafe {
            LLVMDisposeExecutionEngine(self.execution_engine);
        }
    }
}
<commit_msg>added no_run & changed raw pointer to usize for fn<commit_after>use llvm_sys::core::LLVMDisposeMessage;
use llvm_sys::execution_engine::{LLVMGetExecutionEngineTargetData, LLVMExecutionEngineRef, LLVMRunFunction, LLVMRunFunctionAsMain, LLVMDisposeExecutionEngine, LLVMGetFunctionAddress, LLVMAddModule, LLVMFindFunction, LLVMLinkInMCJIT, LLVMLinkInInterpreter, LLVMRemoveModule, LLVMGenericValueRef, LLVMFreeMachineCodeForFunction, LLVMGetPointerToGlobal, LLVMAddGlobalMapping};

use module::Module;
use targets::TargetData;
use values::{AnyValue, AsValueRef, FunctionValue, GenericValue, GlobalValue};

use std::ffi::{CStr, CString};
use std::mem::{forget, uninitialized, zeroed};

#[derive(Debug, PartialEq, Eq)]
pub enum FunctionLookupError {
    JITNotEnabled,
    FunctionNotFound, // 404!
}

#[derive(Debug)]
pub struct ExecutionEngine {
    execution_engine: LLVMExecutionEngineRef,
    pub(crate) modules: Vec<Module>,
    target_data: Option<TargetData>,
    jit_mode: bool,
}

impl ExecutionEngine {
    pub(crate) fn new(execution_engine: LLVMExecutionEngineRef, jit_mode: bool) -> ExecutionEngine {
        assert!(!execution_engine.is_null());

        // REVIEW: Will we have to do this for LLVMGetExecutionEngineTargetMachine too?
        let target_data = unsafe {
            LLVMGetExecutionEngineTargetData(execution_engine)
        };

        ExecutionEngine {
            execution_engine: execution_engine,
            modules: vec![],
            target_data: Some(TargetData::new(target_data)),
            jit_mode: jit_mode,
        }
    }

    pub fn link_in_mc_jit() {
        unsafe {
            LLVMLinkInMCJIT()
        }
    }

    pub fn link_in_interpreter() {
        unsafe {
            LLVMLinkInInterpreter();
        }
    }

    /// Maps the specified value to an address.
    ///
    /// # Example
    /// ```no_run
    /// use inkwell::targets::{InitializationConfig, Target};
    /// use inkwell::context::Context;
    /// use inkwell::OptimizationLevel;
    ///
    /// Target::initialize_native(&InitializationConfig::default()).unwrap();
    ///
    /// extern fn sumf(a: f64, b: f64) -> f64 {
    ///     a + b
    /// }
    ///
    /// let context = Context::create();
    /// let module = context.create_module("test");
    /// let builder = context.create_builder();
    ///
    /// let ft = context.f64_type();
    /// let fnt = ft.fn_type(&[], false);
    ///
    /// let f = module.add_function("test_fn", &fnt, None);
    /// let b = context.append_basic_block(&f, "entry");
    /// builder.position_at_end(&b);
    ///
    /// let extf = module.add_function("sumf", &ft.fn_type(&[ &ft, &ft ], false), None);
    ///
    /// let argf = ft.const_float(64.);
    /// let retv = builder.build_call(&extf, &[ &argf, &argf ], "retv", false).left().unwrap().into_float_value();
    ///
    /// builder.build_return(Some(&retv));
    ///
    /// let mut ee = module.create_jit_execution_engine(OptimizationLevel::None).unwrap();
    /// ee.add_global_mapping(&extf, sumf as usize);
    ///
    /// let result = unsafe { ee.run_function(&f, &[]) }.as_float(&ft);
    ///
    /// assert_eq!(result, 128.);
    /// ```
    pub fn add_global_mapping(&mut self, value: &AnyValue, addr: usize) {
        unsafe {
            LLVMAddGlobalMapping(self.execution_engine, value.as_value_ref(), addr as *mut _)
        }
    }

    // TODOC: EE must *own* modules and deal out references
    pub fn add_module(&mut self, module: Module) -> &Module {
        unsafe {
            LLVMAddModule(self.execution_engine, module.module)
        }

        self.modules.push(module);

        &self.modules[self.modules.len() - 1]
    }

    pub fn remove_module(&mut self, module: &Module) -> Result<Module, String> {
        let mut new_module = unsafe { uninitialized() };
        let mut err_str = unsafe { zeroed() };

        let code = unsafe {
            LLVMRemoveModule(self.execution_engine, module.module, &mut new_module, &mut err_str)
        };

        if code == 1 {
            let rust_str = unsafe {
                let rust_str = CStr::from_ptr(err_str).to_string_lossy().into_owned();

                LLVMDisposeMessage(err_str);

                rust_str
            };

            return Err(rust_str);
        }

        // REVIEW: This might end up a hashtable for better performance
        let mut index = None;

        for (i, owned_module) in self.modules.iter().enumerate() {
            if module == owned_module {
                index = Some(i);
            }
        }

        match index {
            Some(idx) => self.modules.remove(idx),
            None => return Err("Module does not belong to this ExecutionEngine".into()),
        };

        Ok(Module::new(new_module))
    }

    // FIXME: Workaround until we can think of a better API
    // Ideally, we'd provide this as a hashmap from module name to module, but this may not be
    // possible since you can create modules, ie via create_module_from_ir, which either do not
    // have a name, or at least LLVM provides no way to obtain its name. Also, possible collisions
    // depending on how loose, if at all, LLVM is with module names belonging to execution engines
    pub fn get_module_at(&self, index: usize) -> &Module {
        &self.modules[index]
    }

    /// WARNING: The returned address *will* be invalid if the EE drops first
    /// Do not attempt to transmute it to a function if the ExecutionEngine is gone
    // TODOC: Initializing a target MUST occur before creating the EE or else it will not count
    // TODOC: Can still add functions after EE has been created
    pub fn get_function_address(&self, fn_name: &str) -> Result<u64, FunctionLookupError> {
        if !self.jit_mode {
            return Err(FunctionLookupError::JITNotEnabled);
        }

        let c_string = CString::new(fn_name).expect("Conversion to CString failed unexpectedly");

        let address = unsafe {
            LLVMGetFunctionAddress(self.execution_engine, c_string.as_ptr())
        };

        // REVIEW: Can also return 0 if no targets are initialized.
        // One option might be to set a global to true if any at all of the targets have been
        // initialized (maybe we could figure out which config in particular is the trigger)
        // and if not return an "NoTargetsInitialized" error, instead of not found.
        if address == 0 {
            return Err(FunctionLookupError::FunctionNotFound);
        }

        Ok(address)
    }

    // REVIEW: Not sure if an EE's target data can change.. if so we might want to update the value
    // when making this call
    pub fn get_target_data(&self) -> &TargetData {
        self.target_data.as_ref().expect("TargetData should always exist until Drop")
    }

    // REVIEW: Can also find nothing if no targeting is initialized. Maybe best to
    // do have a global flag for anything initialized. Catch is that it must be initialized
    // before EE is created
    pub fn get_function_value(&self, fn_name: &str) -> Result<FunctionValue, FunctionLookupError> {
        if !self.jit_mode {
            return Err(FunctionLookupError::JITNotEnabled);
        }

        let c_string = CString::new(fn_name).expect("Conversion to CString failed unexpectedly");
        let mut function = unsafe { zeroed() };

        let code = unsafe {
            LLVMFindFunction(self.execution_engine, c_string.as_ptr(), &mut function)
        };

        if code == 0 {
            return FunctionValue::new(function).ok_or(FunctionLookupError::FunctionNotFound)
        };

        Err(FunctionLookupError::FunctionNotFound)
    }

    // TODOC: Marked as unsafe because input function could very well do something unsafe. It's up to the caller
    // to ensure that doesn't happen by defining their function correctly.
    pub unsafe fn run_function(&self, function: &FunctionValue, args: &[&GenericValue]) -> GenericValue {
        let mut args: Vec<LLVMGenericValueRef> = args.iter()
                                                     .map(|val| val.generic_value)
                                                     .collect();

        let value = LLVMRunFunction(self.execution_engine, function.as_value_ref(), args.len() as u32, args.as_mut_ptr()); // REVIEW: usize to u32 ok??

        GenericValue::new(value)
    }

    pub fn run_function_as_main(&self, function: &FunctionValue) {
        let args = vec![]; // TODO: Support argc, argv
        let env_p = vec![]; // REVIEW: No clue what this is

        unsafe {
            LLVMRunFunctionAsMain(self.execution_engine, function.as_value_ref(), args.len() as u32, args.as_ptr(), env_p.as_ptr()); // REVIEW: usize to u32 cast ok??
        }
    }

    pub fn free_fn_machine_code(&self, function: &FunctionValue) {
        unsafe {
            LLVMFreeMachineCodeForFunction(self.execution_engine, function.as_value_ref())
        }
    }
}

// Modules owned by the EE will be discarded by the EE so we don't
// want owned modules to drop.
impl Drop for ExecutionEngine {
    fn drop(&mut self) {
        for module in self.modules.drain(..) {
            forget(module);
        }

        forget(self.target_data.take().expect("TargetData should always exist until Drop"));

        unsafe {
            LLVMDisposeExecutionEngine(self.execution_engine);
        }
    }
}
<|endoftext|>


<commit_before>extern crate chrono;

use flowgger::Decoder;
use flowgger::config::Config;
use flowgger::record::{Record, Pri, StructuredData};
use self::chrono::DateTime;

#[derive(Clone)]
pub struct RFC5424;

impl Decoder for RFC5424 {
    fn new(config: &Config) -> RFC5424 {
        let _ = config;
        RFC5424
    }

    fn decode(&self, line: &str) -> Result<Record, &'static str> {
        let (bom, line) = match BOM::parse(line, "<") {
            Ok(bom_line) => bom_line,
            Err(err) => return Err(err)
        };
        let mut parts = line.splitn(7, ' ');
        let pri_version = try!(parse_pri_version(try!(parts.next().ok_or("Missing priority and version"))));
        let ts = try!(parse_ts(try!(parts.next().ok_or("Missing timestamp"))));
        let hostname = try!(parts.next().ok_or("Missing hostname"));
        let appname = try!(parts.next().ok_or("Missing application name"));
        let procid = try!(parts.next().ok_or("Missing process id"));
        let msgid = try!(parts.next().ok_or("Missing message id"));
        let (sd, msg) = try!(parse_data(try!(parts.next().ok_or("Missing message data"))));
        let record = Record {
            pri: Some(pri_version),
            ts: ts,
            hostname: hostname.to_string(),
            appname: Some(appname.to_string()),
            procid: Some(procid.to_string()),
            msgid: Some(msgid.to_string()),
            sd: sd,
            msg: msg
        };
        Ok(record)
    }
}

impl Pri {
    fn new(encoded: u8) -> Pri {
        Pri {
            facility: encoded >> 3,
            severity: encoded % 7
        }
    }
}

enum BOM {
    NONE,
    UTF8
}

impl BOM {
    fn parse<'a>(line: &'a str, sep: &str) -> Result<(BOM, &'a str), &'static str> {
        if line.starts_with("\u{feff}") {
            Ok((BOM::UTF8, &line[3..]))
        } else if line.starts_with(sep) {
            Ok((BOM::NONE, line))
        } else {
            Err("Unsupported BOM")
        }
    }
}

fn parse_pri_version(line: &str) -> Result<Pri, &'static str> {
    if ! line.starts_with("<") {
        return Err("The priority should be inside brackets")
    }
    let mut parts = line[1..].splitn(2, '>');
    let pri: u8 = try!(try!(parts.next().ok_or("Empty priority")).parse().or(Err("Invalid priority")));
    let version = try!(parts.next().ok_or("Missing version"));
    if version != "1" {
        return Err("Unsupported version");
    }
    Ok(Pri::new(pri))
}

fn rfc3339_to_unix(rfc3339: &str) -> Result<i64, &'static str> {
    match DateTime::parse_from_rfc3339(rfc3339) {
        Ok(date) => Ok(date.timestamp()),
        Err(_) => Err("Unable to parse the date")
    }
}

fn parse_ts(line: &str) -> Result<i64, &'static str> {
    rfc3339_to_unix(line)
}

fn unescape_sd_value(value: &str) -> String {
    let mut res = "".to_string();
    let mut esc = false;

    for c in value.chars() {
        match (c, esc) {
            ('\\', false) => esc = true,
            (_, false) => res.push(c),
            ('"', true) | ('\\', true) | (']', true) => {
                res.push(c);
                esc = false;
            }
            (_, true) => {
                res.push('\\');
                res.push(c);
                esc = false;
            }
        }
    }
    res
}

fn parse_msg(line: &str, offset: usize) -> Option<String> {
    if offset > line.len() {
        None
    } else {
        match line[offset..].trim() {
            "" => None,
            m @ _ => Some(m.to_string())
        }
    }
}

fn parse_data(line: &str) -> Result<(Option<StructuredData>, Option<String>), &'static str> {
    match try!(line.chars().next().ok_or("Short message")) {
        '-' => {
            return Ok((None, parse_msg(line, 1)));
        }
        '[' => { }
        _ => return Err("Short message")
    };
    let mut parts = line[1..].splitn(2, ' ');
    let sd_id = try!(parts.next().ok_or("Missing structured data id"));
    let sd = try!(parts.next().ok_or("Missing structured data"));
    let mut in_name = false;
    let mut in_value = false;
    let mut name_start = 0;
    let mut value_start = 0;
    let mut name: Option<&str> = None;
    let mut esc = false;
    let mut after_sd: Option<usize> = None;
    let mut sd_res = StructuredData::new(sd_id);

    for (i, c) in sd.chars().enumerate() {
        let is_sd_name = match c as u32 {
            32 | 34 | 61 | 93 => false,
            33 ... 126 => true,
            _ => false
        };
        match (c, esc, is_sd_name, in_name, name.is_some(), in_value) {
            (' ', false, _, false, false, _) => { /* contextless spaces */ }
            (']', false, _, false, false, _) => {
                after_sd = Some(i + 1);
                break;
            }
            (_, false, true, false, false, _) => {
                in_name = true;
                name_start = i;
            }
            (_, _, true, true, false, _) => { /* name */ }
            ('=', false, _, true, _, _) => {
                name = Some(&sd[name_start .. i]);
                in_name = false;
            }
            ('"', false, _, _, true, false) => {
                in_value = true;
                value_start = i + 1;
            }
            ('\\', false, _, _, _, true) => esc = true,
            ('"', false, _, _, _, true) => {
                in_value = false;
                let value = unescape_sd_value(&sd[value_start .. i]);
                let pair = (format!("_{}", name.unwrap()), value);
                sd_res.pairs.push(pair);
                name = None;
            }
            (_, _, _, _, _, true) => esc = false,
            _ => return Err("Format error in the structured data")
        }
    }
    match after_sd {
        None => Err("Missing ] after structured data"),
        Some(offset) => Ok((Some(sd_res), parse_msg(sd, offset)))
    }
}
<commit_msg>Add a test for the RFC5424 parser, fix severity by the way<commit_after>extern crate chrono;

use flowgger::Decoder;
use flowgger::config::Config;
use flowgger::record::{Record, Pri, StructuredData};
use self::chrono::DateTime;

#[derive(Clone)]
pub struct RFC5424;

impl Decoder for RFC5424 {
    fn new(config: &Config) -> RFC5424 {
        let _ = config;
        RFC5424
    }

    fn decode(&self, line: &str) -> Result<Record, &'static str> {
        let (bom, line) = match BOM::parse(line, "<") {
            Ok(bom_line) => bom_line,
            Err(err) => return Err(err)
        };
        let mut parts = line.splitn(7, ' ');
        let pri_version = try!(parse_pri_version(try!(parts.next().ok_or("Missing priority and version"))));
        let ts = try!(parse_ts(try!(parts.next().ok_or("Missing timestamp"))));
        let hostname = try!(parts.next().ok_or("Missing hostname"));
        let appname = try!(parts.next().ok_or("Missing application name"));
        let procid = try!(parts.next().ok_or("Missing process id"));
        let msgid = try!(parts.next().ok_or("Missing message id"));
        let (sd, msg) = try!(parse_data(try!(parts.next().ok_or("Missing message data"))));
        let record = Record {
            pri: Some(pri_version),
            ts: ts,
            hostname: hostname.to_string(),
            appname: Some(appname.to_string()),
            procid: Some(procid.to_string()),
            msgid: Some(msgid.to_string()),
            sd: sd,
            msg: msg
        };
        Ok(record)
    }
}

impl Pri {
    fn new(encoded: u8) -> Pri {
        Pri {
            facility: encoded >> 3,
            severity: encoded & 7
        }
    }
}

enum BOM {
    NONE,
    UTF8
}

impl BOM {
    fn parse<'a>(line: &'a str, sep: &str) -> Result<(BOM, &'a str), &'static str> {
        if line.starts_with("\u{feff}") {
            Ok((BOM::UTF8, &line[3..]))
        } else if line.starts_with(sep) {
            Ok((BOM::NONE, line))
        } else {
            Err("Unsupported BOM")
        }
    }
}

fn parse_pri_version(line: &str) -> Result<Pri, &'static str> {
    if ! line.starts_with("<") {
        return Err("The priority should be inside brackets")
    }
    let mut parts = line[1..].splitn(2, '>');
    let pri: u8 = try!(try!(parts.next().ok_or("Empty priority")).parse().or(Err("Invalid priority")));
    let version = try!(parts.next().ok_or("Missing version"));
    if version != "1" {
        return Err("Unsupported version");
    }
    Ok(Pri::new(pri))
}

fn rfc3339_to_unix(rfc3339: &str) -> Result<i64, &'static str> {
    match DateTime::parse_from_rfc3339(rfc3339) {
        Ok(date) => Ok(date.timestamp()),
        Err(_) => Err("Unable to parse the date")
    }
}

fn parse_ts(line: &str) -> Result<i64, &'static str> {
    rfc3339_to_unix(line)
}

fn unescape_sd_value(value: &str) -> String {
    let mut res = "".to_string();
    let mut esc = false;

    for c in value.chars() {
        match (c, esc) {
            ('\\', false) => esc = true,
            (_, false) => res.push(c),
            ('"', true) | ('\\', true) | (']', true) => {
                res.push(c);
                esc = false;
            }
            (_, true) => {
                res.push('\\');
                res.push(c);
                esc = false;
            }
        }
    }
    res
}

fn parse_msg(line: &str, offset: usize) -> Option<String> {
    if offset > line.len() {
        None
    } else {
        match line[offset..].trim() {
            "" => None,
            m @ _ => Some(m.to_string())
        }
    }
}

fn parse_data(line: &str) -> Result<(Option<StructuredData>, Option<String>), &'static str> {
    match try!(line.chars().next().ok_or("Short message")) {
        '-' => {
            return Ok((None, parse_msg(line, 1)));
        }
        '[' => { }
        _ => return Err("Short message")
    };
    let mut parts = line[1..].splitn(2, ' ');
    let sd_id = try!(parts.next().ok_or("Missing structured data id"));
    let sd = try!(parts.next().ok_or("Missing structured data"));
    let mut in_name = false;
    let mut in_value = false;
    let mut name_start = 0;
    let mut value_start = 0;
    let mut name: Option<&str> = None;
    let mut esc = false;
    let mut after_sd: Option<usize> = None;
    let mut sd_res = StructuredData::new(sd_id);

    for (i, c) in sd.chars().enumerate() {
        let is_sd_name = match c as u32 {
            32 | 34 | 61 | 93 => false,
            33 ... 126 => true,
            _ => false
        };
        match (c, esc, is_sd_name, in_name, name.is_some(), in_value) {
            (' ', false, _, false, false, _) => { /* contextless spaces */ }
            (']', false, _, false, false, _) => {
                after_sd = Some(i + 1);
                break;
            }
            (_, false, true, false, false, _) => {
                in_name = true;
                name_start = i;
            }
            (_, _, true, true, false, _) => { /* name */ }
            ('=', false, _, true, _, _) => {
                name = Some(&sd[name_start .. i]);
                in_name = false;
            }
            ('"', false, _, _, true, false) => {
                in_value = true;
                value_start = i + 1;
            }
            ('\\', false, _, _, _, true) => esc = true,
            ('"', false, _, _, _, true) => {
                in_value = false;
                let value = unescape_sd_value(&sd[value_start .. i]);
                let pair = (format!("_{}", name.unwrap()), value);
                sd_res.pairs.push(pair);
                name = None;
            }
            (_, _, _, _, _, true) => esc = false,
            _ => return Err("Format error in the structured data")
        }
    }
    match after_sd {
        None => Err("Missing ] after structured data"),
        Some(offset) => Ok((Some(sd_res), parse_msg(sd, offset)))
    }
}
/*
pub struct Record {
    pub pri: Option<Pri>,
    pub ts: i64,
    pub hostname: String,
    pub appname: Option<String>,
    pub procid: Option<String>,
    pub msgid: Option<String>,
    pub sd: Option<StructuredData>,
    pub msg: Option<String>
}
*/
#[test]
fn test_rfc5424() {
    let msg = r#"<23>1 2015-08-05T15:53:45.637824Z testhostname appname 69 42 [origin@123 software="te\st sc\"ript" swVersion="0.0.1"] test message"#;
    let res = RFC5424.decode(msg).unwrap();
    let pri = res.pri.unwrap();
    assert!(pri.facility == 2);
    assert!(pri.severity == 7);
    assert!(res.ts == 1438790025);
    assert!(res.hostname == "testhostname");
    assert!(res.appname == Some("appname".to_string()));
    assert!(res.procid == Some("69".to_string()));
    assert!(res.msgid == Some("42".to_string()));
    assert!(res.msg == Some("test message".to_string()));
    let sd = res.sd.unwrap();
    assert!(sd.sd_id == "origin@123");
    let pairs = sd.pairs;
    assert!(pairs.iter().cloned().any(|(k, v)| k == "_software" && v == "te\\st sc\"ript"));
    assert!(pairs.iter().cloned().any(|(k, v)| k == "_swVersion" && v == "0.0.1"));
}
<|endoftext|>


<commit_before>use screen::*;
use piston_window;
use conrod::{self, Widget, Frameable, Positionable, Sizeable, Labelable};
use conrod::color::Colorable;
//use gif::traits::SetParameter;

pub struct MainMenuScreen {
    ui: conrod::Ui<piston_window::Glyphs>,
}

impl MainMenuScreen {
    pub fn new(window: &piston_window::PistonWindow, context: &mut Context) -> MainMenuScreen {
        MainMenuScreen { ui: create_ui(&window, &context.assets_path) }
    }
}

impl Screen for MainMenuScreen {
    fn on_input(&mut self,
                input: &piston_window::Input,
                window: &piston_window::PistonWindow,
                context: &mut Context)
                -> InputResults {
        use piston_window::{Input, Button, MouseButton};

        let mut result = Vec::new();

        match input {
            &Input::Press(Button::Mouse(MouseButton::Left)) => {
                result.push(InputResult::PopScreen);
                result.push(InputResult::PushScreen(Box::new(BattleScreen::new(&window, context))));
            }
            _ => {}
        }

        result
    }

    fn on_draw(&mut self, args: &piston_window::RenderArgs, window: &piston_window::PistonWindow) {
        self.ui.handle_event(window);
        window.draw_2d(|context, graphics| self.ui.draw_if_changed(context, graphics));
    }

    fn on_update(&mut self, args: &piston_window::UpdateArgs) {
        self.ui.set_widgets(|ui| {
            conrod::Canvas::new()
                .frame(1.)
                .pad(30.)
                .color(conrod::color::rgb(0.2, 0.35, 0.45))
                .scroll_kids()
                .set(CANVAS, ui);

            conrod::Button::new()
                .w_h(200.0, 50.0)
                .mid_left_of(CANVAS)
                .top_left_with_margins_on(CANVAS, 0.0, 350.0)
                .rgb(0.4, 0.75, 0.6)
                .frame(1.)
                .label("New game")
                .react(|| ())
                .set(NEW_GAME_BUTTON, ui);

            conrod::Button::new()
                .w_h(200.0, 50.0)
                .mid_left_of(CANVAS)
                .down_from(NEW_GAME_BUTTON, 45.0)
                .rgb(0.4, 0.75, 0.6)
                .frame(1.)
                .label("Exit")
                .react(|| ())
                .set(EXIT_BUTTON, ui);
        });
    }
}

widget_ids! {
    CANVAS,
    TITLE,
    NEW_GAME_BUTTON,
    EXIT_BUTTON,
}

fn create_ui(window: &piston_window::PistonWindow,
             assets_path: &::std::path::Path)
             -> conrod::Ui<piston_window::Glyphs> {
    let font_path = assets_path.join("NotoSans-Regular.ttf");
    let theme = conrod::Theme::default();
    let glyph_cache = piston_window::Glyphs::new(&font_path, window.factory.borrow().clone());
    conrod::Ui::new(glyph_cache.unwrap(), theme)
}
<commit_msg>FRAME_WIDTH constant<commit_after>use screen::*;
use piston_window;
use conrod::{self, Widget, Frameable, Positionable, Sizeable, Labelable};
use conrod::color::Colorable;
//use gif::traits::SetParameter;

pub struct MainMenuScreen {
    ui: conrod::Ui<piston_window::Glyphs>,
}

impl MainMenuScreen {
    pub fn new(window: &piston_window::PistonWindow, context: &mut Context) -> MainMenuScreen {
        MainMenuScreen { ui: create_ui(&window, &context.assets_path) }
    }
}

impl Screen for MainMenuScreen {
    fn on_input(&mut self,
                input: &piston_window::Input,
                window: &piston_window::PistonWindow,
                context: &mut Context)
                -> InputResults {
        use piston_window::{Input, Button, MouseButton};

        let mut result = Vec::new();

        match input {
            &Input::Press(Button::Mouse(MouseButton::Left)) => {
                result.push(InputResult::PopScreen);
                result.push(InputResult::PushScreen(Box::new(BattleScreen::new(&window, context))));
            }
            _ => {}
        }

        result
    }

    fn on_draw(&mut self, args: &piston_window::RenderArgs, window: &piston_window::PistonWindow) {
        self.ui.handle_event(window);
        window.draw_2d(|context, graphics| self.ui.draw_if_changed(context, graphics));
    }

    fn on_update(&mut self, args: &piston_window::UpdateArgs) {
        const FRAME_WIDTH: f64 = 1.;

        self.ui.set_widgets(|ui| {
            conrod::Canvas::new()
                .frame(FRAME_WIDTH)
                .pad(30.)
                .color(conrod::color::rgb(0.2, 0.35, 0.45))
                .scroll_kids()
                .set(CANVAS, ui);

            conrod::Button::new()
                .w_h(200.0, 50.0)
                .mid_left_of(CANVAS)
                .top_left_with_margins_on(CANVAS, 0.0, 350.0)
                .rgb(0.4, 0.75, 0.6)
                .frame(FRAME_WIDTH)
                .label("New game")
                .react(|| ())
                .set(NEW_GAME_BUTTON, ui);

            conrod::Button::new()
                .w_h(200.0, 50.0)
                .mid_left_of(CANVAS)
                .down_from(NEW_GAME_BUTTON, 45.0)
                .rgb(0.4, 0.75, 0.6)
                .frame(FRAME_WIDTH)
                .label("Exit")
                .react(|| ())
                .set(EXIT_BUTTON, ui);
        });
    }
}

widget_ids! {
    CANVAS,
    TITLE,
    NEW_GAME_BUTTON,
    EXIT_BUTTON,
}

fn create_ui(window: &piston_window::PistonWindow,
             assets_path: &::std::path::Path)
             -> conrod::Ui<piston_window::Glyphs> {
    let font_path = assets_path.join("NotoSans-Regular.ttf");
    let theme = conrod::Theme::default();
    let glyph_cache = piston_window::Glyphs::new(&font_path, window.factory.borrow().clone());
    conrod::Ui::new(glyph_cache.unwrap(), theme)
}
<|endoftext|>


<commit_before>#![no_std]

extern crate alloc;

mod app;
mod pipe;
mod portal;

pub mod components;
pub mod widgets;

pub use app::App;
pub use graphics_base::types::*;
pub use graphics_base::Result;
<commit_msg>Fix non-rust_os build<commit_after>#![cfg_attr(target_os = "rust_os", no_std)]

extern crate alloc;

mod app;
mod pipe;
mod portal;

pub mod components;
pub mod widgets;

pub use app::App;
pub use graphics_base::types::*;
pub use graphics_base::Result;
<|endoftext|>