<commit_before>use select::SelectCommand;
use super::labeled_drilldown::LabeledDrilldown;
use command::{Command, Query};
use selectable::fragmentable::Fragmentable;
use command_query::CommandQuery;
use queryable::Queryable;
use commandable::Commandable;
use command_line::CommandLine;

pub struct LabeledDrilldownSequenceBuilder {
    select: SelectCommand,
    drilldowns: Vec<LabeledDrilldown>,
}

/// LabeledDrilldownSequence builder.
///
/// ## Simple usage
///
/// ```
/// use ruroonga_command::select::SelectCommand;
/// use ruroonga_command::selectable::labeled_drilldown::LabeledDrilldown;
/// use ruroonga_command::selectable::labeled_drilldown_sequence_builder as seq;
/// let select = SelectCommand::new("Memos".to_string());
/// let drilldown_label1 = LabeledDrilldown::new("label1".to_string())
///                  .table("label2".to_string())
///                  .keys(vec![("category".to_string())])
///                  .output_columns(vec![("_key".to_string()),
///                                       ("_nsubrecs".to_string())]);
/// let drilldown_label2 = LabeledDrilldown::new("label2".to_string())
///                  .keys(vec![("tag".to_string())])
///                  .output_columns(vec![("_key".to_string()),
///                                       ("_nsubrecs".to_string()),
///                                       ("category".to_string())]);
/// let mut builder =
///     seq::LabeledDrilldownSequenceBuilder::new(select,
///                                               vec![(drilldown_label1),
///                                                    (drilldown_label2)]);
/// let _ = builder.build();
/// ```
/// In more practical example, please refer to drilldown_builder examples
/// in [examples/drilldown_builder.rs]
/// (https://github.com/cosmo0920/ruroonga_command/blob/master/examples/advanced_drilldown.rs).

impl LabeledDrilldownSequenceBuilder {
    pub fn new(select: SelectCommand,
               drilldowns: Vec<LabeledDrilldown>)
               -> LabeledDrilldownSequenceBuilder {
        LabeledDrilldownSequenceBuilder {
            select: select,
            drilldowns: drilldowns,
        }
    }

    pub fn build(self) -> (Command, Query) {
        let mut query: Query = vec![];
        let (command, ordered_select, select) = self.select.to_fragment();
        for ordered in ordered_select.iter() {
            query.push(ordered.to_owned());
        }
        for (key, value) in select.iter() {
            query.push((key.to_owned(), value.to_owned()));
        }
        for drilldown in self.drilldowns.iter() {
            let (_, _, drilldown) = drilldown.clone().to_fragment();
            for (key, value) in drilldown.iter() {
                query.push((key.to_owned(), value.to_owned()));
            }
        }
        (command, query)
    }
}

impl Queryable for LabeledDrilldownSequenceBuilder {
    fn to_query(self) -> String {
        let (command, query) = self.build();
        let mut command = CommandQuery::new(command, query);
        command.encode()
    }
}

impl Commandable for LabeledDrilldownSequenceBuilder {
    fn to_command(self) -> String {
        let (command, query) = self.build();
        let mut command = CommandLine::new(command, query);
        command.encode()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use queryable::Queryable;
    use commandable::Commandable;
    use select::SelectCommand;
    use selectable::labeled_drilldown::LabeledDrilldown;

    #[test]
    fn test_to_query() {
        let select = SelectCommand::new("Entries".to_string())
                         .filter("content @ \"fast\"".to_string());
        let drilldown = LabeledDrilldown::new("label".to_string()).keys(vec![("tag".to_string())]);
        let builder = LabeledDrilldownSequenceBuilder::new(select, vec![(drilldown)]).to_query();
        let encoded = "/d/select?table=Entries&filter=%27content+%40+%22fast%22%27&drilldown%5Blab\
                       el%5D.keys=%27tag%27"
                          .to_string();
        assert_eq!(encoded, builder);
    }

    #[test]
    fn test_to_command() {
        let select = SelectCommand::new("Entries".to_string())
                         .filter("content @ \"fast\"".to_string());
        let drilldown = LabeledDrilldown::new("label".to_string()).keys(vec![("tag".to_string())]);
        let builder = LabeledDrilldownSequenceBuilder::new(select, vec![(drilldown)]).to_command();
        let encoded = "select --table Entries --filter \'content @ \"fast\"\' \
                       --drilldown[label].keys \'tag\'"
                          .to_string();
        assert_eq!(encoded, builder);
    }
}
<commit_msg>rustdoc: Fix filename<commit_after>use select::SelectCommand;
use super::labeled_drilldown::LabeledDrilldown;
use command::{Command, Query};
use selectable::fragmentable::Fragmentable;
use command_query::CommandQuery;
use queryable::Queryable;
use commandable::Commandable;
use command_line::CommandLine;

pub struct LabeledDrilldownSequenceBuilder {
    select: SelectCommand,
    drilldowns: Vec<LabeledDrilldown>,
}

/// LabeledDrilldownSequence builder.
///
/// ## Simple usage
///
/// ```
/// use ruroonga_command::select::SelectCommand;
/// use ruroonga_command::selectable::labeled_drilldown::LabeledDrilldown;
/// use ruroonga_command::selectable::labeled_drilldown_sequence_builder as seq;
/// let select = SelectCommand::new("Memos".to_string());
/// let drilldown_label1 = LabeledDrilldown::new("label1".to_string())
///                  .table("label2".to_string())
///                  .keys(vec![("category".to_string())])
///                  .output_columns(vec![("_key".to_string()),
///                                       ("_nsubrecs".to_string())]);
/// let drilldown_label2 = LabeledDrilldown::new("label2".to_string())
///                  .keys(vec![("tag".to_string())])
///                  .output_columns(vec![("_key".to_string()),
///                                       ("_nsubrecs".to_string()),
///                                       ("category".to_string())]);
/// let mut builder =
///     seq::LabeledDrilldownSequenceBuilder::new(select,
///                                               vec![(drilldown_label1),
///                                                    (drilldown_label2)]);
/// let _ = builder.build();
/// ```
/// In more practical example, please refer to drilldown_builder examples
/// in [examples/advanced_drilldown.rs]
/// (https://github.com/cosmo0920/ruroonga_command/blob/master/examples/advanced_drilldown.rs).

impl LabeledDrilldownSequenceBuilder {
    pub fn new(select: SelectCommand,
               drilldowns: Vec<LabeledDrilldown>)
               -> LabeledDrilldownSequenceBuilder {
        LabeledDrilldownSequenceBuilder {
            select: select,
            drilldowns: drilldowns,
        }
    }

    pub fn build(self) -> (Command, Query) {
        let mut query: Query = vec![];
        let (command, ordered_select, select) = self.select.to_fragment();
        for ordered in ordered_select.iter() {
            query.push(ordered.to_owned());
        }
        for (key, value) in select.iter() {
            query.push((key.to_owned(), value.to_owned()));
        }
        for drilldown in self.drilldowns.iter() {
            let (_, _, drilldown) = drilldown.clone().to_fragment();
            for (key, value) in drilldown.iter() {
                query.push((key.to_owned(), value.to_owned()));
            }
        }
        (command, query)
    }
}

impl Queryable for LabeledDrilldownSequenceBuilder {
    fn to_query(self) -> String {
        let (command, query) = self.build();
        let mut command = CommandQuery::new(command, query);
        command.encode()
    }
}

impl Commandable for LabeledDrilldownSequenceBuilder {
    fn to_command(self) -> String {
        let (command, query) = self.build();
        let mut command = CommandLine::new(command, query);
        command.encode()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use queryable::Queryable;
    use commandable::Commandable;
    use select::SelectCommand;
    use selectable::labeled_drilldown::LabeledDrilldown;

    #[test]
    fn test_to_query() {
        let select = SelectCommand::new("Entries".to_string())
                         .filter("content @ \"fast\"".to_string());
        let drilldown = LabeledDrilldown::new("label".to_string()).keys(vec![("tag".to_string())]);
        let builder = LabeledDrilldownSequenceBuilder::new(select, vec![(drilldown)]).to_query();
        let encoded = "/d/select?table=Entries&filter=%27content+%40+%22fast%22%27&drilldown%5Blab\
                       el%5D.keys=%27tag%27"
                          .to_string();
        assert_eq!(encoded, builder);
    }

    #[test]
    fn test_to_command() {
        let select = SelectCommand::new("Entries".to_string())
                         .filter("content @ \"fast\"".to_string());
        let drilldown = LabeledDrilldown::new("label".to_string()).keys(vec![("tag".to_string())]);
        let builder = LabeledDrilldownSequenceBuilder::new(select, vec![(drilldown)]).to_command();
        let encoded = "select --table Entries --filter \'content @ \"fast\"\' \
                       --drilldown[label].keys \'tag\'"
                          .to_string();
        assert_eq!(encoded, builder);
    }
}
<|endoftext|>


<commit_before>// compile-flags: -Zunleash-the-miri-inside-of-you

// ignore-test Temporarily ignored while this analysis is migrated to the new framework.

#![feature(core_intrinsics, rustc_attrs, const_raw_ptr_deref)]

use std::cell::UnsafeCell;
use std::intrinsics::rustc_peek;

#[repr(C)]
struct PartialInteriorMut {
    zst: [i32; 0],
    cell: UnsafeCell<i32>,
}

#[rustc_mir(rustc_peek_indirectly_mutable,stop_after_dataflow)]
const BOO: i32 = {
    let x = PartialInteriorMut {
        zst: [],
        cell: UnsafeCell::new(0),
    };

    let p_zst: *const _ = &x.zst ; // Doesn't cause `x` to get marked as indirectly mutable.

    let rmut_cell = unsafe {
        // Take advantage of the fact that `zst` and `cell` are at the same location in memory.
        // This trick would work with any size type if miri implemented `ptr::offset`.
        let p_cell = p_zst as *const UnsafeCell<i32>;

        let pmut_cell = (*p_cell).get();
        &mut *pmut_cell
    };

    *rmut_cell = 42;  // Mutates `x` indirectly even though `x` is not marked indirectly mutable!!!
    let val = *rmut_cell;
    unsafe { rustc_peek(x) }; //~ ERROR rustc_peek: bit not set

    val
};

fn main() {
    println!("{}", BOO);
}
<commit_msg>Remove ignore and add explanation of indirect mutation peek test<commit_after>// compile-flags: -Zunleash-the-miri-inside-of-you

// This test demonstrates a shortcoming of the `MaybeMutBorrowedLocals` analysis. It does not
// handle code that takes a reference to one field of a struct, then use pointer arithmetic to
// transform it to another field of that same struct that may have interior mutability. For now,
// this is UB, but this may change in the future. See [rust-lang/unsafe-code-guidelines#134].
//
// [rust-lang/unsafe-code-guidelines#134]: https://github.com/rust-lang/unsafe-code-guidelines/issues/134

#![feature(core_intrinsics, rustc_attrs, const_raw_ptr_deref)]

use std::cell::UnsafeCell;
use std::intrinsics::rustc_peek;

#[repr(C)]
struct PartialInteriorMut {
    zst: [i32; 0],
    cell: UnsafeCell<i32>,
}

#[rustc_mir(rustc_peek_indirectly_mutable,stop_after_dataflow)]
const BOO: i32 = {
    let x = PartialInteriorMut {
        zst: [],
        cell: UnsafeCell::new(0),
    };

    let p_zst: *const _ = &x.zst ; // Doesn't cause `x` to get marked as indirectly mutable.

    let rmut_cell = unsafe {
        // Take advantage of the fact that `zst` and `cell` are at the same location in memory.
        // This trick would work with any size type if miri implemented `ptr::offset`.
        let p_cell = p_zst as *const UnsafeCell<i32>;

        let pmut_cell = (*p_cell).get();
        &mut *pmut_cell
    };

    *rmut_cell = 42;  // Mutates `x` indirectly even though `x` is not marked indirectly mutable!!!
    let val = *rmut_cell;
    unsafe { rustc_peek(x) }; //~ ERROR rustc_peek: bit not set

    val
};

fn main() {
    println!("{}", BOO);
}
<|endoftext|>


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

//! Simple file-locking apis for each OS.
//!
//! This is not meant to be in the standard library, it does nothing with
//! green/native threading. This is just a bare-bones enough solution for
//! librustdoc, it is not production quality at all.

#![allow(non_camel_case_types)]
use std::path::Path;

pub use self::imp::Lock;

#[cfg(unix)]
mod imp {
    use std::ffi::{CString, OsStr};
    use std::os::unix::prelude::*;
    use std::path::Path;
    use std::io;
    use libc;

    #[cfg(target_os = "linux")]
    mod os {
        use libc;

        #[repr(C)]
        pub struct flock {
            pub l_type: libc::c_short,
            pub l_whence: libc::c_short,
            pub l_start: libc::off_t,
            pub l_len: libc::off_t,
            pub l_pid: libc::pid_t,

            // not actually here, but brings in line with freebsd
            pub l_sysid: libc::c_int,
        }

        pub const F_RDLCK: libc::c_short = 0;
        pub const F_WRLCK: libc::c_short = 1;
        pub const F_UNLCK: libc::c_short = 2;
        pub const F_SETLK: libc::c_int = 6;
        pub const F_SETLKW: libc::c_int = 7;
    }

    #[cfg(target_os = "freebsd")]
    mod os {
        use libc;

        #[repr(C)]
        pub struct flock {
            pub l_start: libc::off_t,
            pub l_len: libc::off_t,
            pub l_pid: libc::pid_t,
            pub l_type: libc::c_short,
            pub l_whence: libc::c_short,
            pub l_sysid: libc::c_int,
        }

        pub const F_RDLCK: libc::c_short = 1;
        pub const F_UNLCK: libc::c_short = 2;
        pub const F_WRLCK: libc::c_short = 3;
        pub const F_SETLK: libc::c_int = 12;
        pub const F_SETLKW: libc::c_int = 13;
    }

    #[cfg(any(target_os = "dragonfly",
              target_os = "bitrig",
              target_os = "netbsd",
              target_os = "openbsd"))]
    mod os {
        use libc;

        #[repr(C)]
        pub struct flock {
            pub l_start: libc::off_t,
            pub l_len: libc::off_t,
            pub l_pid: libc::pid_t,
            pub l_type: libc::c_short,
            pub l_whence: libc::c_short,

            // not actually here, but brings in line with freebsd
            pub l_sysid: libc::c_int,
        }

        pub const F_RDLCK: libc::c_short = 1;
        pub const F_UNLCK: libc::c_short = 2;
        pub const F_WRLCK: libc::c_short = 3;
        pub const F_SETLK: libc::c_int = 8;
        pub const F_SETLKW: libc::c_int = 9;
    }

    #[cfg(target_os = "haiku")]
    mod os {
        use libc;

        #[repr(C)]
        pub struct flock {
            pub l_type: libc::c_short,
            pub l_whence: libc::c_short,
            pub l_start: libc::off_t,
            pub l_len: libc::off_t,
            pub l_pid: libc::pid_t,

            // not actually here, but brings in line with freebsd
            pub l_sysid: libc::c_int,
        }

        pub const F_UNLCK: libc::c_short = 0x0200;
        pub const F_WRLCK: libc::c_short = 0x0400;
        pub const F_SETLK: libc::c_int = 0x0080;
        pub const F_SETLKW: libc::c_int = 0x0100;
    }

    #[cfg(any(target_os = "macos", target_os = "ios"))]
    mod os {
        use libc;

        #[repr(C)]
        pub struct flock {
            pub l_start: libc::off_t,
            pub l_len: libc::off_t,
            pub l_pid: libc::pid_t,
            pub l_type: libc::c_short,
            pub l_whence: libc::c_short,

            // not actually here, but brings in line with freebsd
            pub l_sysid: libc::c_int,
        }

        pub const F_RDLCK: libc::c_short = 1;
        pub const F_UNLCK: libc::c_short = 2;
        pub const F_WRLCK: libc::c_short = 3;
        pub const F_SETLK: libc::c_int = 8;
        pub const F_SETLKW: libc::c_int = 9;
    }

    #[cfg(target_os = "solaris")]
    mod os {
        use libc;

        #[repr(C)]
        pub struct flock {
            pub l_type: libc::c_short,
            pub l_whence: libc::c_short,
            pub l_start: libc::off_t,
            pub l_len: libc::off_t,
            pub l_sysid: libc::c_int,
            pub l_pid: libc::pid_t,
        }

        pub const F_RDLCK: libc::c_short = 1;
        pub const F_WRLCK: libc::c_short = 2;
        pub const F_UNLCK: libc::c_short = 3;
        pub const F_SETLK: libc::c_int = 6;
        pub const F_SETLKW: libc::c_int = 7;
    }

    #[derive(Debug)]
    pub struct Lock {
        fd: libc::c_int,
    }

    impl Lock {
        pub fn new(p: &Path,
                   wait: bool,
                   create: bool,
                   exclusive: bool)
                   -> io::Result<Lock> {
            let os: &OsStr = p.as_ref();
            let buf = CString::new(os.as_bytes()).unwrap();
            let open_flags = if create {
                libc::O_RDWR | libc::O_CREAT
            } else {
                libc::O_RDWR
            };

            let fd = unsafe {
                libc::open(buf.as_ptr(), open_flags,
                           libc::S_IRWXU as libc::c_int)
            };

            if fd < 0 {
                return Err(io::Error::last_os_error());
            }

            let lock_type = if exclusive {
                os::F_WRLCK
            } else {
                os::F_RDLCK
            };

            let flock = os::flock {
                l_start: 0,
                l_len: 0,
                l_pid: 0,
                l_whence: libc::SEEK_SET as libc::c_short,
                l_type: lock_type,
                l_sysid: 0,
            };
            let cmd = if wait { os::F_SETLKW } else { os::F_SETLK };
            let ret = unsafe {
                libc::fcntl(fd, cmd, &flock)
            };
            if ret == -1 {
                let err = io::Error::last_os_error();
                unsafe { libc::close(fd); }
                Err(err)
            } else {
                Ok(Lock { fd: fd })
            }
        }
    }

    impl Drop for Lock {
        fn drop(&mut self) {
            let flock = os::flock {
                l_start: 0,
                l_len: 0,
                l_pid: 0,
                l_whence: libc::SEEK_SET as libc::c_short,
                l_type: os::F_UNLCK,
                l_sysid: 0,
            };
            unsafe {
                libc::fcntl(self.fd, os::F_SETLK, &flock);
                libc::close(self.fd);
            }
        }
    }
}

#[cfg(windows)]
#[allow(bad_style)]
mod imp {
    use std::io;
    use std::mem;
    use std::os::windows::prelude::*;
    use std::os::windows::raw::HANDLE;
    use std::path::Path;
    use std::fs::{File, OpenOptions};
    use std::os::raw::{c_ulong, c_ulonglong, c_int};

    type DWORD = c_ulong;
    type BOOL = c_int;
    type ULONG_PTR = c_ulonglong;

    type LPOVERLAPPED = *mut OVERLAPPED;
    const LOCKFILE_EXCLUSIVE_LOCK: DWORD = 0x00000002;
    const LOCKFILE_FAIL_IMMEDIATELY: DWORD = 0x00000001;

    const FILE_SHARE_DELETE: DWORD = 0x4;
    const FILE_SHARE_READ: DWORD = 0x1;
    const FILE_SHARE_WRITE: DWORD = 0x2;

    #[repr(C)]
    struct OVERLAPPED {
        Internal: ULONG_PTR,
        InternalHigh: ULONG_PTR,
        Offset: DWORD,
        OffsetHigh: DWORD,
        hEvent: HANDLE,
    }

    extern "system" {
        fn LockFileEx(hFile: HANDLE,
                      dwFlags: DWORD,
                      dwReserved: DWORD,
                      nNumberOfBytesToLockLow: DWORD,
                      nNumberOfBytesToLockHigh: DWORD,
                      lpOverlapped: LPOVERLAPPED) -> BOOL;
    }

    #[derive(Debug)]
    pub struct Lock {
        _file: File,
    }

    impl Lock {
        pub fn new(p: &Path,
                   wait: bool,
                   create: bool,
                   exclusive: bool)
                   -> io::Result<Lock> {
            assert!(p.parent().unwrap().exists(),
                "Parent directory of lock-file must exist: {}",
                p.display());

            let share_mode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;

            let mut open_options = OpenOptions::new();
            open_options.read(true)
                        .share_mode(share_mode);

            if create {
                open_options.create(true)
                            .write(true);
            }

            debug!("Attempting to open lock file `{}`", p.display());
            let file = match open_options.open(p) {
                Ok(file) => {
                    debug!("Lock file opened successfully");
                    file
                }
                Err(err) => {
                    debug!("Error opening lock file: {}", err);
                    return Err(err)
                }
            };

            let ret = unsafe {
                let mut overlapped: OVERLAPPED = mem::zeroed();

                let mut dwFlags = 0;
                if !wait {
                    dwFlags |= LOCKFILE_FAIL_IMMEDIATELY;
                }

                if exclusive {
                    dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
                }

                debug!("Attempting to acquire lock on lock file `{}`",
                       p.display());
                LockFileEx(file.as_raw_handle(),
                           dwFlags,
                           0,
                           0xFFFF_FFFF,
                           0xFFFF_FFFF,
                           &mut overlapped)
            };
            if ret == 0 {
                let err = io::Error::last_os_error();
                debug!("Failed acquiring file lock: {}", err);
                Err(err)
            } else {
                debug!("Successfully acquired lock.");
                Ok(Lock { _file: file })
            }
        }
    }

    // Note that we don't need a Drop impl on the Windows: The file is unlocked
    // automatically when it's closed.
}

impl imp::Lock {
    pub fn panicking_new(p: &Path,
                         wait: bool,
                         create: bool,
                         exclusive: bool)
                         -> Lock {
        Lock::new(p, wait, create, exclusive).unwrap_or_else(|err| {
            panic!("could not lock `{}`: {}", p.display(), err);
        })
    }
}
<commit_msg>Allow rustc data structures compile to android<commit_after>// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Simple file-locking apis for each OS.
//!
//! This is not meant to be in the standard library, it does nothing with
//! green/native threading. This is just a bare-bones enough solution for
//! librustdoc, it is not production quality at all.

#![allow(non_camel_case_types)]
use std::path::Path;

pub use self::imp::Lock;

#[cfg(unix)]
mod imp {
    use std::ffi::{CString, OsStr};
    use std::os::unix::prelude::*;
    use std::path::Path;
    use std::io;
    use libc;

    #[cfg(any(target_os = "linux", target_os = "android"))]
    mod os {
        use libc;

        #[repr(C)]
        pub struct flock {
            pub l_type: libc::c_short,
            pub l_whence: libc::c_short,
            pub l_start: libc::off_t,
            pub l_len: libc::off_t,
            pub l_pid: libc::pid_t,

            // not actually here, but brings in line with freebsd
            pub l_sysid: libc::c_int,
        }

        pub const F_RDLCK: libc::c_short = 0;
        pub const F_WRLCK: libc::c_short = 1;
        pub const F_UNLCK: libc::c_short = 2;
        pub const F_SETLK: libc::c_int = 6;
        pub const F_SETLKW: libc::c_int = 7;
    }

    #[cfg(target_os = "freebsd")]
    mod os {
        use libc;

        #[repr(C)]
        pub struct flock {
            pub l_start: libc::off_t,
            pub l_len: libc::off_t,
            pub l_pid: libc::pid_t,
            pub l_type: libc::c_short,
            pub l_whence: libc::c_short,
            pub l_sysid: libc::c_int,
        }

        pub const F_RDLCK: libc::c_short = 1;
        pub const F_UNLCK: libc::c_short = 2;
        pub const F_WRLCK: libc::c_short = 3;
        pub const F_SETLK: libc::c_int = 12;
        pub const F_SETLKW: libc::c_int = 13;
    }

    #[cfg(any(target_os = "dragonfly",
              target_os = "bitrig",
              target_os = "netbsd",
              target_os = "openbsd"))]
    mod os {
        use libc;

        #[repr(C)]
        pub struct flock {
            pub l_start: libc::off_t,
            pub l_len: libc::off_t,
            pub l_pid: libc::pid_t,
            pub l_type: libc::c_short,
            pub l_whence: libc::c_short,

            // not actually here, but brings in line with freebsd
            pub l_sysid: libc::c_int,
        }

        pub const F_RDLCK: libc::c_short = 1;
        pub const F_UNLCK: libc::c_short = 2;
        pub const F_WRLCK: libc::c_short = 3;
        pub const F_SETLK: libc::c_int = 8;
        pub const F_SETLKW: libc::c_int = 9;
    }

    #[cfg(target_os = "haiku")]
    mod os {
        use libc;

        #[repr(C)]
        pub struct flock {
            pub l_type: libc::c_short,
            pub l_whence: libc::c_short,
            pub l_start: libc::off_t,
            pub l_len: libc::off_t,
            pub l_pid: libc::pid_t,

            // not actually here, but brings in line with freebsd
            pub l_sysid: libc::c_int,
        }

        pub const F_UNLCK: libc::c_short = 0x0200;
        pub const F_WRLCK: libc::c_short = 0x0400;
        pub const F_SETLK: libc::c_int = 0x0080;
        pub const F_SETLKW: libc::c_int = 0x0100;
    }

    #[cfg(any(target_os = "macos", target_os = "ios"))]
    mod os {
        use libc;

        #[repr(C)]
        pub struct flock {
            pub l_start: libc::off_t,
            pub l_len: libc::off_t,
            pub l_pid: libc::pid_t,
            pub l_type: libc::c_short,
            pub l_whence: libc::c_short,

            // not actually here, but brings in line with freebsd
            pub l_sysid: libc::c_int,
        }

        pub const F_RDLCK: libc::c_short = 1;
        pub const F_UNLCK: libc::c_short = 2;
        pub const F_WRLCK: libc::c_short = 3;
        pub const F_SETLK: libc::c_int = 8;
        pub const F_SETLKW: libc::c_int = 9;
    }

    #[cfg(target_os = "solaris")]
    mod os {
        use libc;

        #[repr(C)]
        pub struct flock {
            pub l_type: libc::c_short,
            pub l_whence: libc::c_short,
            pub l_start: libc::off_t,
            pub l_len: libc::off_t,
            pub l_sysid: libc::c_int,
            pub l_pid: libc::pid_t,
        }

        pub const F_RDLCK: libc::c_short = 1;
        pub const F_WRLCK: libc::c_short = 2;
        pub const F_UNLCK: libc::c_short = 3;
        pub const F_SETLK: libc::c_int = 6;
        pub const F_SETLKW: libc::c_int = 7;
    }

    #[derive(Debug)]
    pub struct Lock {
        fd: libc::c_int,
    }

    impl Lock {
        pub fn new(p: &Path,
                   wait: bool,
                   create: bool,
                   exclusive: bool)
                   -> io::Result<Lock> {
            let os: &OsStr = p.as_ref();
            let buf = CString::new(os.as_bytes()).unwrap();
            let open_flags = if create {
                libc::O_RDWR | libc::O_CREAT
            } else {
                libc::O_RDWR
            };

            let fd = unsafe {
                libc::open(buf.as_ptr(), open_flags,
                           libc::S_IRWXU as libc::c_int)
            };

            if fd < 0 {
                return Err(io::Error::last_os_error());
            }

            let lock_type = if exclusive {
                os::F_WRLCK
            } else {
                os::F_RDLCK
            };

            let flock = os::flock {
                l_start: 0,
                l_len: 0,
                l_pid: 0,
                l_whence: libc::SEEK_SET as libc::c_short,
                l_type: lock_type,
                l_sysid: 0,
            };
            let cmd = if wait { os::F_SETLKW } else { os::F_SETLK };
            let ret = unsafe {
                libc::fcntl(fd, cmd, &flock)
            };
            if ret == -1 {
                let err = io::Error::last_os_error();
                unsafe { libc::close(fd); }
                Err(err)
            } else {
                Ok(Lock { fd: fd })
            }
        }
    }

    impl Drop for Lock {
        fn drop(&mut self) {
            let flock = os::flock {
                l_start: 0,
                l_len: 0,
                l_pid: 0,
                l_whence: libc::SEEK_SET as libc::c_short,
                l_type: os::F_UNLCK,
                l_sysid: 0,
            };
            unsafe {
                libc::fcntl(self.fd, os::F_SETLK, &flock);
                libc::close(self.fd);
            }
        }
    }
}

#[cfg(windows)]
#[allow(bad_style)]
mod imp {
    use std::io;
    use std::mem;
    use std::os::windows::prelude::*;
    use std::os::windows::raw::HANDLE;
    use std::path::Path;
    use std::fs::{File, OpenOptions};
    use std::os::raw::{c_ulong, c_ulonglong, c_int};

    type DWORD = c_ulong;
    type BOOL = c_int;
    type ULONG_PTR = c_ulonglong;

    type LPOVERLAPPED = *mut OVERLAPPED;
    const LOCKFILE_EXCLUSIVE_LOCK: DWORD = 0x00000002;
    const LOCKFILE_FAIL_IMMEDIATELY: DWORD = 0x00000001;

    const FILE_SHARE_DELETE: DWORD = 0x4;
    const FILE_SHARE_READ: DWORD = 0x1;
    const FILE_SHARE_WRITE: DWORD = 0x2;

    #[repr(C)]
    struct OVERLAPPED {
        Internal: ULONG_PTR,
        InternalHigh: ULONG_PTR,
        Offset: DWORD,
        OffsetHigh: DWORD,
        hEvent: HANDLE,
    }

    extern "system" {
        fn LockFileEx(hFile: HANDLE,
                      dwFlags: DWORD,
                      dwReserved: DWORD,
                      nNumberOfBytesToLockLow: DWORD,
                      nNumberOfBytesToLockHigh: DWORD,
                      lpOverlapped: LPOVERLAPPED) -> BOOL;
    }

    #[derive(Debug)]
    pub struct Lock {
        _file: File,
    }

    impl Lock {
        pub fn new(p: &Path,
                   wait: bool,
                   create: bool,
                   exclusive: bool)
                   -> io::Result<Lock> {
            assert!(p.parent().unwrap().exists(),
                "Parent directory of lock-file must exist: {}",
                p.display());

            let share_mode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;

            let mut open_options = OpenOptions::new();
            open_options.read(true)
                        .share_mode(share_mode);

            if create {
                open_options.create(true)
                            .write(true);
            }

            debug!("Attempting to open lock file `{}`", p.display());
            let file = match open_options.open(p) {
                Ok(file) => {
                    debug!("Lock file opened successfully");
                    file
                }
                Err(err) => {
                    debug!("Error opening lock file: {}", err);
                    return Err(err)
                }
            };

            let ret = unsafe {
                let mut overlapped: OVERLAPPED = mem::zeroed();

                let mut dwFlags = 0;
                if !wait {
                    dwFlags |= LOCKFILE_FAIL_IMMEDIATELY;
                }

                if exclusive {
                    dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
                }

                debug!("Attempting to acquire lock on lock file `{}`",
                       p.display());
                LockFileEx(file.as_raw_handle(),
                           dwFlags,
                           0,
                           0xFFFF_FFFF,
                           0xFFFF_FFFF,
                           &mut overlapped)
            };
            if ret == 0 {
                let err = io::Error::last_os_error();
                debug!("Failed acquiring file lock: {}", err);
                Err(err)
            } else {
                debug!("Successfully acquired lock.");
                Ok(Lock { _file: file })
            }
        }
    }

    // Note that we don't need a Drop impl on the Windows: The file is unlocked
    // automatically when it's closed.
}

impl imp::Lock {
    pub fn panicking_new(p: &Path,
                         wait: bool,
                         create: bool,
                         exclusive: bool)
                         -> Lock {
        Lock::new(p, wait, create, exclusive).unwrap_or_else(|err| {
            panic!("could not lock `{}`: {}", p.display(), err);
        })
    }
}
<|endoftext|>


<commit_before>//! Simple file-locking apis for each OS.
//!
//! This is not meant to be in the standard library, it does nothing with
//! green/native threading. This is just a bare-bones enough solution for
//! librustdoc, it is not production quality at all.

#![allow(non_camel_case_types)]
#![allow(nonstandard_style)]

use std::io;
use std::path::Path;

cfg_if! {
    if #[cfg(unix)] {
        use std::ffi::{CString, OsStr};
        use std::os::unix::prelude::*;

        #[cfg(any(target_os = "linux", target_os = "android"))]
        mod os {
            #[repr(C)]
            pub struct flock {
                pub l_type: libc::c_short,
                pub l_whence: libc::c_short,
                pub l_start: libc::off_t,
                pub l_len: libc::off_t,
                pub l_pid: libc::pid_t,

                // not actually here, but brings in line with freebsd
                pub l_sysid: libc::c_int,
            }
        }

        #[cfg(target_os = "freebsd")]
        mod os {
            #[repr(C)]
            pub struct flock {
                pub l_start: libc::off_t,
                pub l_len: libc::off_t,
                pub l_pid: libc::pid_t,
                pub l_type: libc::c_short,
                pub l_whence: libc::c_short,
                pub l_sysid: libc::c_int,
            }
        }

        #[cfg(any(target_os = "dragonfly",
                  target_os = "netbsd",
                  target_os = "openbsd"))]
        mod os {
            #[repr(C)]
            pub struct flock {
                pub l_start: libc::off_t,
                pub l_len: libc::off_t,
                pub l_pid: libc::pid_t,
                pub l_type: libc::c_short,
                pub l_whence: libc::c_short,

                // not actually here, but brings in line with freebsd
                pub l_sysid: libc::c_int,
            }
        }

        #[cfg(target_os = "haiku")]
        mod os {
            #[repr(C)]
            pub struct flock {
                pub l_type: libc::c_short,
                pub l_whence: libc::c_short,
                pub l_start: libc::off_t,
                pub l_len: libc::off_t,
                pub l_pid: libc::pid_t,

                // not actually here, but brings in line with freebsd
                pub l_sysid: libc::c_int,
            }
        }

        #[cfg(any(target_os = "macos", target_os = "ios"))]
        mod os {
            #[repr(C)]
            pub struct flock {
                pub l_start: libc::off_t,
                pub l_len: libc::off_t,
                pub l_pid: libc::pid_t,
                pub l_type: libc::c_short,
                pub l_whence: libc::c_short,

                // not actually here, but brings in line with freebsd
                pub l_sysid: libc::c_int,
            }
        }

        #[cfg(target_os = "solaris")]
        mod os {
            #[repr(C)]
            pub struct flock {
                pub l_type: libc::c_short,
                pub l_whence: libc::c_short,
                pub l_start: libc::off_t,
                pub l_len: libc::off_t,
                pub l_sysid: libc::c_int,
                pub l_pid: libc::pid_t,
            }
        }

        #[derive(Debug)]
        pub struct Lock {
            fd: libc::c_int,
        }

        impl Lock {
            pub fn new(p: &Path,
                       wait: bool,
                       create: bool,
                       exclusive: bool)
                       -> io::Result<Lock> {
                let os: &OsStr = p.as_ref();
                let buf = CString::new(os.as_bytes()).unwrap();
                let open_flags = if create {
                    libc::O_RDWR | libc::O_CREAT
                } else {
                    libc::O_RDWR
                };

                let fd = unsafe {
                    libc::open(buf.as_ptr(), open_flags,
                               libc::S_IRWXU as libc::c_int)
                };

                if fd < 0 {
                    return Err(io::Error::last_os_error());
                }

                let lock_type = if exclusive {
                    libc::F_WRLCK as libc::c_short
                } else {
                    libc::F_RDLCK as libc::c_short
                };

                let flock = os::flock {
                    l_start: 0,
                    l_len: 0,
                    l_pid: 0,
                    l_whence: libc::SEEK_SET as libc::c_short,
                    l_type: lock_type,
                    l_sysid: 0,
                };
                let cmd = if wait { libc::F_SETLKW } else { libc::F_SETLK };
                let ret = unsafe {
                    libc::fcntl(fd, cmd, &flock)
                };
                if ret == -1 {
                    let err = io::Error::last_os_error();
                    unsafe { libc::close(fd); }
                    Err(err)
                } else {
                    Ok(Lock { fd })
                }
            }
        }

        impl Drop for Lock {
            fn drop(&mut self) {
                let flock = os::flock {
                    l_start: 0,
                    l_len: 0,
                    l_pid: 0,
                    l_whence: libc::SEEK_SET as libc::c_short,
                    l_type: libc::F_UNLCK as libc::c_short,
                    l_sysid: 0,
                };
                unsafe {
                    libc::fcntl(self.fd, libc::F_SETLK, &flock);
                    libc::close(self.fd);
                }
            }
        }
    } else if #[cfg(windows)] {
        use std::mem;
        use std::os::windows::prelude::*;
        use std::os::windows::raw::HANDLE;
        use std::fs::{File, OpenOptions};
        use std::os::raw::{c_ulong, c_int};

        type DWORD = c_ulong;
        type BOOL = c_int;
        type ULONG_PTR = usize;

        type LPOVERLAPPED = *mut OVERLAPPED;
        const LOCKFILE_EXCLUSIVE_LOCK: DWORD = 0x0000_0002;
        const LOCKFILE_FAIL_IMMEDIATELY: DWORD = 0x0000_0001;

        const FILE_SHARE_DELETE: DWORD = 0x4;
        const FILE_SHARE_READ: DWORD = 0x1;
        const FILE_SHARE_WRITE: DWORD = 0x2;

        #[repr(C)]
        struct OVERLAPPED {
            Internal: ULONG_PTR,
            InternalHigh: ULONG_PTR,
            Offset: DWORD,
            OffsetHigh: DWORD,
            hEvent: HANDLE,
        }

        extern "system" {
            fn LockFileEx(hFile: HANDLE,
                          dwFlags: DWORD,
                          dwReserved: DWORD,
                          nNumberOfBytesToLockLow: DWORD,
                          nNumberOfBytesToLockHigh: DWORD,
                          lpOverlapped: LPOVERLAPPED) -> BOOL;
        }

        #[derive(Debug)]
        pub struct Lock {
            _file: File,
        }

        impl Lock {
            pub fn new(p: &Path,
                       wait: bool,
                       create: bool,
                       exclusive: bool)
                       -> io::Result<Lock> {
                assert!(p.parent().unwrap().exists(),
                    "Parent directory of lock-file must exist: {}",
                    p.display());

                let share_mode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;

                let mut open_options = OpenOptions::new();
                open_options.read(true)
                            .share_mode(share_mode);

                if create {
                    open_options.create(true)
                                .write(true);
                }

                debug!("attempting to open lock file `{}`", p.display());
                let file = match open_options.open(p) {
                    Ok(file) => {
                        debug!("lock file opened successfully");
                        file
                    }
                    Err(err) => {
                        debug!("error opening lock file: {}", err);
                        return Err(err)
                    }
                };

                let ret = unsafe {
                    let mut overlapped: OVERLAPPED = mem::zeroed();

                    let mut dwFlags = 0;
                    if !wait {
                        dwFlags |= LOCKFILE_FAIL_IMMEDIATELY;
                    }

                    if exclusive {
                        dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
                    }

                    debug!("attempting to acquire lock on lock file `{}`",
                           p.display());
                    LockFileEx(file.as_raw_handle(),
                               dwFlags,
                               0,
                               0xFFFF_FFFF,
                               0xFFFF_FFFF,
                               &mut overlapped)
                };
                if ret == 0 {
                    let err = io::Error::last_os_error();
                    debug!("failed acquiring file lock: {}", err);
                    Err(err)
                } else {
                    debug!("successfully acquired lock");
                    Ok(Lock { _file: file })
                }
            }
        }

        // Note that we don't need a Drop impl on the Windows: The file is unlocked
        // automatically when it's closed.
    } else {
        #[derive(Debug)]
        pub struct Lock(());

        impl Lock {
            pub fn new(_p: &Path, _wait: bool, _create: bool, _exclusive: bool)
                -> io::Result<Lock>
            {
                let msg = "file locks not supported on this platform";
                Err(io::Error::new(io::ErrorKind::Other, msg))
            }
        }
    }
}
<commit_msg>remove bespoke flock bindings<commit_after>//! Simple file-locking apis for each OS.
//!
//! This is not meant to be in the standard library, it does nothing with
//! green/native threading. This is just a bare-bones enough solution for
//! librustdoc, it is not production quality at all.

#![allow(non_camel_case_types)]
#![allow(nonstandard_style)]

use std::io;
use std::path::Path;

cfg_if! {
    if #[cfg(unix)] {
        use std::ffi::{CString, OsStr};
        use std::mem;
        use std::os::unix::prelude::*;

        #[derive(Debug)]
        pub struct Lock {
            fd: libc::c_int,
        }

        impl Lock {
            pub fn new(p: &Path,
                       wait: bool,
                       create: bool,
                       exclusive: bool)
                       -> io::Result<Lock> {
                let os: &OsStr = p.as_ref();
                let buf = CString::new(os.as_bytes()).unwrap();
                let open_flags = if create {
                    libc::O_RDWR | libc::O_CREAT
                } else {
                    libc::O_RDWR
                };

                let fd = unsafe {
                    libc::open(buf.as_ptr(), open_flags,
                               libc::S_IRWXU as libc::c_int)
                };

                if fd < 0 {
                    return Err(io::Error::last_os_error());
                }

                let lock_type = if exclusive {
                    libc::F_WRLCK
                } else {
                    libc::F_RDLCK
                };

                let mut flock: libc::flock = unsafe { mem::zeroed() };
                flock.l_type = lock_type as libc::c_short;
                flock.l_whence = libc::SEEK_SET as libc::c_short;
                flock.l_start = 0;
                flock.l_len = 0;

                let cmd = if wait { libc::F_SETLKW } else { libc::F_SETLK };
                let ret = unsafe {
                    libc::fcntl(fd, cmd, &flock)
                };
                if ret == -1 {
                    let err = io::Error::last_os_error();
                    unsafe { libc::close(fd); }
                    Err(err)
                } else {
                    Ok(Lock { fd })
                }
            }
        }

        impl Drop for Lock {
            fn drop(&mut self) {
                let mut flock: libc::flock = unsafe { mem::zeroed() };
                flock.l_type = libc::F_UNLCK as libc::c_short;
                flock.l_whence = libc::SEEK_SET as libc::c_short;
                flock.l_start = 0;
                flock.l_len = 0;

                unsafe {
                    libc::fcntl(self.fd, libc::F_SETLK, &flock);
                    libc::close(self.fd);
                }
            }
        }
    } else if #[cfg(windows)] {
        use std::mem;
        use std::os::windows::prelude::*;
        use std::os::windows::raw::HANDLE;
        use std::fs::{File, OpenOptions};
        use std::os::raw::{c_ulong, c_int};

        type DWORD = c_ulong;
        type BOOL = c_int;
        type ULONG_PTR = usize;

        type LPOVERLAPPED = *mut OVERLAPPED;
        const LOCKFILE_EXCLUSIVE_LOCK: DWORD = 0x0000_0002;
        const LOCKFILE_FAIL_IMMEDIATELY: DWORD = 0x0000_0001;

        const FILE_SHARE_DELETE: DWORD = 0x4;
        const FILE_SHARE_READ: DWORD = 0x1;
        const FILE_SHARE_WRITE: DWORD = 0x2;

        #[repr(C)]
        struct OVERLAPPED {
            Internal: ULONG_PTR,
            InternalHigh: ULONG_PTR,
            Offset: DWORD,
            OffsetHigh: DWORD,
            hEvent: HANDLE,
        }

        extern "system" {
            fn LockFileEx(hFile: HANDLE,
                          dwFlags: DWORD,
                          dwReserved: DWORD,
                          nNumberOfBytesToLockLow: DWORD,
                          nNumberOfBytesToLockHigh: DWORD,
                          lpOverlapped: LPOVERLAPPED) -> BOOL;
        }

        #[derive(Debug)]
        pub struct Lock {
            _file: File,
        }

        impl Lock {
            pub fn new(p: &Path,
                       wait: bool,
                       create: bool,
                       exclusive: bool)
                       -> io::Result<Lock> {
                assert!(p.parent().unwrap().exists(),
                    "Parent directory of lock-file must exist: {}",
                    p.display());

                let share_mode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;

                let mut open_options = OpenOptions::new();
                open_options.read(true)
                            .share_mode(share_mode);

                if create {
                    open_options.create(true)
                                .write(true);
                }

                debug!("attempting to open lock file `{}`", p.display());
                let file = match open_options.open(p) {
                    Ok(file) => {
                        debug!("lock file opened successfully");
                        file
                    }
                    Err(err) => {
                        debug!("error opening lock file: {}", err);
                        return Err(err)
                    }
                };

                let ret = unsafe {
                    let mut overlapped: OVERLAPPED = mem::zeroed();

                    let mut dwFlags = 0;
                    if !wait {
                        dwFlags |= LOCKFILE_FAIL_IMMEDIATELY;
                    }

                    if exclusive {
                        dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
                    }

                    debug!("attempting to acquire lock on lock file `{}`",
                           p.display());
                    LockFileEx(file.as_raw_handle(),
                               dwFlags,
                               0,
                               0xFFFF_FFFF,
                               0xFFFF_FFFF,
                               &mut overlapped)
                };
                if ret == 0 {
                    let err = io::Error::last_os_error();
                    debug!("failed acquiring file lock: {}", err);
                    Err(err)
                } else {
                    debug!("successfully acquired lock");
                    Ok(Lock { _file: file })
                }
            }
        }

        // Note that we don't need a Drop impl on the Windows: The file is unlocked
        // automatically when it's closed.
    } else {
        #[derive(Debug)]
        pub struct Lock(());

        impl Lock {
            pub fn new(_p: &Path, _wait: bool, _create: bool, _exclusive: bool)
                -> io::Result<Lock>
            {
                let msg = "file locks not supported on this platform";
                Err(io::Error::new(io::ErrorKind::Other, msg))
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add a small encode benchmark for the display wrapper<commit_after><|endoftext|>


<commit_before>use crate::definitions::{Clamp, Image};
use crate::drawing::Canvas;
use conv::ValueInto;
use image::{GenericImage, ImageBuffer, Pixel};
use std::f32;
use std::i32;

use crate::pixelops::weighted_sum;
use rusttype::{point, Font, PositionedGlyph, Rect, Scale};
use std::cmp::max;

fn layout_glyphs(
    scale: Scale,
    font: &Font,
    text: &str,
    mut f: impl FnMut(PositionedGlyph, Rect<i32>),
) -> (i32, i32) {
    let v_metrics = font.v_metrics(scale);

    let (mut w, mut h) = (0, 0);

    for g in font.layout(text, scale, point(0.0, v_metrics.ascent)) {
        if let Some(bb) = g.pixel_bounding_box() {
            w = max(w, bb.max.x);
            h = max(h, bb.max.y);
            f(g, bb);
        }
    }

    (w, h)
}

/// Get the width and height of the given text, rendered with the given font and scale. Note that this function *does not* support newlines, you must do this manually.
pub fn text_size(scale: Scale, font: &Font, text: &str) -> (i32, i32) {
    layout_glyphs(scale, font, text, |_, _| {})
}

/// Draws colored text on an image in place. `scale` is augmented font scaling on both the x and y axis (in pixels). Note that this function *does not* support newlines, you must do this manually.
pub fn draw_text_mut<'a, C>(
    canvas: &'a mut C,
    color: C::Pixel,
    x: u32,
    y: u32,
    scale: Scale,
    font: &'a Font<'a>,
    text: &'a str,
) where
    C: Canvas,
    <C::Pixel as Pixel>::Subpixel: ValueInto<f32> + Clamp<f32>,
{
    let image_width = canvas.width() as i32;
    let image_height = canvas.height() as i32;

    layout_glyphs(scale, font, text, |g, bb| {
        g.draw(|gx, gy, gv| {
            let gx = gx as i32 + bb.min.x;
            let gy = gy as i32 + bb.min.y;

            let image_x = gx + x as i32;
            let image_y = gy + y as i32;

            if (0..image_width).contains(&image_x) && (0..image_height).contains(&image_y) {
                let pixel = canvas.get_pixel(image_x as u32, image_y as u32);
                let weighted_color = weighted_sum(pixel, color, 1.0 - gv, gv);
                canvas.draw_pixel(image_x as u32, image_y as u32, weighted_color);
            }
        })
    });
}

/// Draws colored text on an image in place. `scale` is augmented font scaling on both the x and y axis (in pixels). Note that this function *does not* support newlines, you must do this manually.
pub fn draw_text<'a, I>(
    image: &'a mut I,
    color: I::Pixel,
    x: u32,
    y: u32,
    scale: Scale,
    font: &'a Font<'a>,
    text: &'a str,
) -> Image<I::Pixel>
where
    I: GenericImage,
    <I::Pixel as Pixel>::Subpixel: ValueInto<f32> + Clamp<f32>,
    I::Pixel: 'static,
{
    let mut out = ImageBuffer::new(image.width(), image.height());
    out.copy_from(image, 0, 0).unwrap();
    draw_text_mut(&mut out, color, x, y, scale, font, text);
    out
}
<commit_msg>Allowed negative values for the draw_text_mut position x/y (#464)<commit_after>use crate::definitions::{Clamp, Image};
use crate::drawing::Canvas;
use conv::ValueInto;
use image::{GenericImage, ImageBuffer, Pixel};
use std::f32;
use std::i32;

use crate::pixelops::weighted_sum;
use rusttype::{point, Font, PositionedGlyph, Rect, Scale};
use std::cmp::max;

fn layout_glyphs(
    scale: Scale,
    font: &Font,
    text: &str,
    mut f: impl FnMut(PositionedGlyph, Rect<i32>),
) -> (i32, i32) {
    let v_metrics = font.v_metrics(scale);

    let (mut w, mut h) = (0, 0);

    for g in font.layout(text, scale, point(0.0, v_metrics.ascent)) {
        if let Some(bb) = g.pixel_bounding_box() {
            w = max(w, bb.max.x);
            h = max(h, bb.max.y);
            f(g, bb);
        }
    }

    (w, h)
}

/// Get the width and height of the given text, rendered with the given font and scale. Note that this function *does not* support newlines, you must do this manually.
pub fn text_size(scale: Scale, font: &Font, text: &str) -> (i32, i32) {
    layout_glyphs(scale, font, text, |_, _| {})
}

/// Draws colored text on an image in place. `scale` is augmented font scaling on both the x and y axis (in pixels). Note that this function *does not* support newlines, you must do this manually.
pub fn draw_text_mut<'a, C>(
    canvas: &'a mut C,
    color: C::Pixel,
    x: i32,
    y: i32,
    scale: Scale,
    font: &'a Font<'a>,
    text: &'a str,
) where
    C: Canvas,
    <C::Pixel as Pixel>::Subpixel: ValueInto<f32> + Clamp<f32>,
{
    let image_width = canvas.width() as i32;
    let image_height = canvas.height() as i32;

    layout_glyphs(scale, font, text, |g, bb| {
        g.draw(|gx, gy, gv| {
            let gx = gx as i32 + bb.min.x;
            let gy = gy as i32 + bb.min.y;

            let image_x = gx + x;
            let image_y = gy + y;

            if (0..image_width).contains(&image_x) && (0..image_height).contains(&image_y) {
                let pixel = canvas.get_pixel(image_x as u32, image_y as u32);
                let weighted_color = weighted_sum(pixel, color, 1.0 - gv, gv);
                canvas.draw_pixel(image_x as u32, image_y as u32, weighted_color);
            }
        })
    });
}

/// Draws colored text on an image in place. `scale` is augmented font scaling on both the x and y axis (in pixels). Note that this function *does not* support newlines, you must do this manually.
pub fn draw_text<'a, I>(
    image: &'a mut I,
    color: I::Pixel,
    x: i32,
    y: i32,
    scale: Scale,
    font: &'a Font<'a>,
    text: &'a str,
) -> Image<I::Pixel>
where
    I: GenericImage,
    <I::Pixel as Pixel>::Subpixel: ValueInto<f32> + Clamp<f32>,
    I::Pixel: 'static,
{
    let mut out = ImageBuffer::new(image.width(), image.height());
    out.copy_from(image, 0, 0).unwrap();
    draw_text_mut(&mut out, color, x, y, scale, font, text);
    out
}
<|endoftext|>


<commit_before>use std::fmt::Formatter;
use std::fmt;
use std::fmt::Display;
use std::mem;
use std::ffi::{CStr, CString};
use std::str;

use cassandra_sys::CASS_OK;
use cassandra_sys::CassUuid as _Uuid;
use cassandra_sys::CassUuidGen as _UuidGen;
use cassandra_sys::cass_uuid_gen_new;
use cassandra_sys::cass_uuid_gen_free;
use cassandra_sys::cass_uuid_gen_time;
use cassandra_sys::cass_uuid_gen_new_with_node;
use cassandra_sys::cass_uuid_gen_random;
use cassandra_sys::cass_uuid_gen_from_time;
use cassandra_sys::cass_uuid_min_from_time;
use cassandra_sys::cass_uuid_max_from_time;
use cassandra_sys::cass_uuid_timestamp;
use cassandra_sys::cass_uuid_version;
use cassandra::util::Protected;

use cassandra_sys::cass_uuid_string;
// use cassandra_sys::raw2utf8;
use cassandra_sys::cass_uuid_from_string;

use cassandra::error::CassError;

// const CASS_UUID_STRING_LENGTH: usize = 37;

#[derive(Copy,Clone)]
///Version 1 (time-based) or version 4 (random) UUID.
pub struct Uuid(_Uuid);

impl Protected<_Uuid> for Uuid {
    fn inner(&self) -> _Uuid {
        self.0
    }
    fn build(inner: _Uuid) -> Self {
        Uuid(inner)
    }
}

impl Default for Uuid {
    fn default() -> Uuid {
        unsafe { ::std::mem::zeroed() }
    }
}

///A UUID generator object.
///
///Instances of the UUID generator object are thread-safe to generate UUIDs.
pub struct UuidGen(*mut _UuidGen);
unsafe impl Sync for UuidGen {}
unsafe impl Send for UuidGen {}

impl Drop for UuidGen {
    fn drop(&mut self) {
        unsafe { cass_uuid_gen_free(self.0) }
    }
}

// impl Debug for Uuid {
//    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
//        write!(f, "{:?}", self.to_string())
//    }
// }

// FIXME!!!!!!!
impl Display for Uuid {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        unsafe {
            let mut string = mem::zeroed();
            cass_uuid_string(self.0, &mut string);
            let slice = CStr::from_ptr(&string);
            write!(f, "{}", str::from_utf8(slice.to_bytes()).unwrap())
        }
    }
}

impl Uuid {
    /// Generates a V1 (time) UUID for the specified time.
    pub fn min_from_time(&mut self, time: u64) {
        unsafe { cass_uuid_min_from_time(time, &mut self.0) }
    }

    ///Sets the UUID to the minimum V1 (time) value for the specified tim
    pub fn max_from_time(&mut self, time: u64) {
        unsafe { cass_uuid_max_from_time(time, &mut self.0) }
    }

    ///Gets the timestamp for a V1 UUID
    pub fn timestamp(&self) -> u64 {
        unsafe { cass_uuid_timestamp(self.0) }
    }

    ///Gets the version for a UUID
    pub fn version(&self) -> u8 {
        unsafe { cass_uuid_version(self.0) }
    }
}

impl str::FromStr for Uuid {
    type Err = CassError;
    fn from_str(str: &str) -> Result<Uuid, CassError> {
        unsafe {
            let mut uuid = mem::zeroed();
            match cass_uuid_from_string(CString::new(str).unwrap().as_ptr(), &mut uuid) {
                CASS_OK => Ok(Uuid(uuid)),
                err => Err(CassError::build(err)),
            }
        }
    }
}

impl UuidGen {
    ///Creates a new thread-safe UUID generator
    pub fn new() -> Self {
        unsafe { UuidGen(cass_uuid_gen_new()) }
    }

    ///Creates a new UUID generator with custom node information.
    ///Note: This object is thread-safe. It is best practice to create and reuse
    ///a single object per application.
    pub fn new_with_node(node: u64) -> UuidGen {
        unsafe { UuidGen(cass_uuid_gen_new_with_node(node)) }
    }

    ///Generates a V1 (time) UUID.
    pub fn gen_time(&self) -> Uuid {
        unsafe {
            let mut output: _Uuid = mem::zeroed();
            cass_uuid_gen_time(self.0, &mut output);
            Uuid(output)
        }
    }

    ///Generates a new V4 (random) UUID
    pub fn gen_random(&self) -> Uuid {
        unsafe {
            let mut output: _Uuid = mem::zeroed();
            cass_uuid_gen_random(self.0, &mut output);
            Uuid(output)
        }
    }

    ///Generates a V1 (time) UUID for the specified time.
    pub fn gen_from_time(&self, timestamp: u64) -> Uuid {
        unsafe {
            let mut output: _Uuid = mem::zeroed();
            cass_uuid_gen_from_time(self.0, timestamp, &mut output);
            Uuid(output)
        }
    }
}
<commit_msg>Fix Display trait implementation and add Debug trait for Uuid along with tests for both. Add example and doctest to UuidGen::gen_from_time.<commit_after>use std::fmt::Formatter;
use std::fmt;
use std::fmt::{Debug, Display};
use std::mem;
use std::ffi::CString;
use std::str;

use cassandra_sys::CASS_OK;
use cassandra_sys::CassUuid as _Uuid;
use cassandra_sys::CassUuidGen as _UuidGen;
use cassandra_sys::cass_uuid_gen_new;
use cassandra_sys::cass_uuid_gen_free;
use cassandra_sys::cass_uuid_gen_time;
use cassandra_sys::cass_uuid_gen_new_with_node;
use cassandra_sys::cass_uuid_gen_random;
use cassandra_sys::cass_uuid_gen_from_time;
use cassandra_sys::cass_uuid_min_from_time;
use cassandra_sys::cass_uuid_max_from_time;
use cassandra_sys::cass_uuid_timestamp;
use cassandra_sys::cass_uuid_version;
use cassandra::util::Protected;

use cassandra_sys::cass_uuid_string;
use cassandra_sys::cass_uuid_from_string;

use cassandra::error::CassError;

const CASS_UUID_STRING_LENGTH: usize = 37;

#[derive(Copy,Clone)]
///Version 1 (time-based) or version 4 (random) UUID.
pub struct Uuid(_Uuid);

impl Protected<_Uuid> for Uuid {
    fn inner(&self) -> _Uuid {
        self.0
    }
    fn build(inner: _Uuid) -> Self {
        Uuid(inner)
    }
}

impl Default for Uuid {
    fn default() -> Uuid {
        unsafe { ::std::mem::zeroed() }
    }
}

///A UUID generator object.
///
///Instances of the UUID generator object are thread-safe to generate UUIDs.
pub struct UuidGen(*mut _UuidGen);
unsafe impl Sync for UuidGen {}
unsafe impl Send for UuidGen {}

impl Drop for UuidGen {
    fn drop(&mut self) {
        unsafe { cass_uuid_gen_free(self.0) }
    }
}

impl Debug for Uuid {
   fn fmt(&self, f: &mut Formatter) -> fmt::Result {
       fmt::Display::fmt(self, f)
   }
}

impl Display for Uuid {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        unsafe {
            // Allocate a CString large enough for cass_uuid_string to write to.
            let mut buf = CString::from_vec_unchecked(vec!(0u8; CASS_UUID_STRING_LENGTH));
            let cstr = buf.into_raw(); // Convert to *mut c_char
            cass_uuid_string(self.0, cstr); // Write the UUID to *c_char
            buf = CString::from_raw(cstr); // Convert from *c_char back to a CString.
            let str = match buf.into_string() {
              Ok(s) => s,
              Err(_) => return Err(fmt::Error)
            };
            fmt::Display::fmt(&str, f)
        }
    }
}

impl Uuid {
    /// Generates a V1 (time) UUID for the specified time.
    pub fn min_from_time(&mut self, time: u64) {
        unsafe { cass_uuid_min_from_time(time, &mut self.0) }
    }

    ///Sets the UUID to the minimum V1 (time) value for the specified tim
    pub fn max_from_time(&mut self, time: u64) {
        unsafe { cass_uuid_max_from_time(time, &mut self.0) }
    }

    ///Gets the timestamp for a V1 UUID
    pub fn timestamp(&self) -> u64 {
        unsafe { cass_uuid_timestamp(self.0) }
    }

    ///Gets the version for a UUID
    pub fn version(&self) -> u8 {
        unsafe { cass_uuid_version(self.0) }
    }
}

impl str::FromStr for Uuid {
    type Err = CassError;
    fn from_str(str: &str) -> Result<Uuid, CassError> {
        unsafe {
            let mut uuid = mem::zeroed();
            match cass_uuid_from_string(CString::new(str).unwrap().as_ptr(), &mut uuid) {
                CASS_OK => Ok(Uuid(uuid)),
                err => Err(CassError::build(err)),
            }
        }
    }
}

impl UuidGen {
    ///Creates a new thread-safe UUID generator
    pub fn new() -> Self {
        unsafe { UuidGen(cass_uuid_gen_new()) }
    }

    ///Creates a new UUID generator with custom node information.
    ///Note: This object is thread-safe. It is best practice to create and reuse
    ///a single object per application.
    pub fn new_with_node(node: u64) -> UuidGen {
        unsafe { UuidGen(cass_uuid_gen_new_with_node(node)) }
    }

    ///Generates a V1 (time) UUID.
    pub fn gen_time(&self) -> Uuid {
        unsafe {
            let mut output: _Uuid = mem::zeroed();
            cass_uuid_gen_time(self.0, &mut output);
            Uuid(output)
        }
    }

    ///Generates a new V4 (random) UUID
    pub fn gen_random(&self) -> Uuid {
        unsafe {
            let mut output: _Uuid = mem::zeroed();
            cass_uuid_gen_random(self.0, &mut output);
            Uuid(output)
        }
    }

    ///Generates a V1 (time) UUID for the specified time.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cassandra::{UuidGen, Uuid};
    /// # #[allow(dead_code)]
    /// # fn example() -> Uuid {
    /// let generator = UuidGen::new();
    /// let uuid = generator.gen_from_time(1457486866742u64);
    /// # uuid
    /// # }
    /// ```
    pub fn gen_from_time(&self, timestamp: u64) -> Uuid {
        unsafe {
            let mut output: _Uuid = mem::zeroed();
            cass_uuid_gen_from_time(self.0, timestamp, &mut output);
            Uuid(output)
        }
    }
}

#[test]
#[allow(unused_variables)]
fn test_uuid_display_gentime() {
    let generator = UuidGen::new();
    let uuid = generator.gen_from_time(1457486866742u64);
    assert_eq!(uuid.timestamp(), 1457486866742u64);
    let uuidstr = format!("{}", uuid); // Test Display trait
}

#[test]
#[allow(unused_variables)]
fn test_uuid_debug_genrand() {
    let generator = UuidGen::new();
    let uuid = generator.gen_random();
    let uuidstr = format!("{:?}", uuid); // Test Debug trait
}<|endoftext|>


<commit_before>//! Compiles the profiler part of the `compiler-rt` library.
//!
//! See the build.rs for libcompiler_builtins crate for details.

use std::env;
use std::path::Path;

fn main() {
    let target = env::var("TARGET").expect("TARGET was not set");
    let cfg = &mut cc::Build::new();

    // FIXME: `rerun-if-changed` directives are not currently emitted and the build script
    // will not rerun on changes in these source files or headers included into them.
    let mut profile_sources = vec![
        "GCDAProfiling.c",
        "InstrProfiling.c",
        "InstrProfilingBuffer.c",
        "InstrProfilingFile.c",
        "InstrProfilingMerge.c",
        "InstrProfilingMergeFile.c",
        "InstrProfilingNameVar.c",
        "InstrProfilingPlatformDarwin.c",
        "InstrProfilingPlatformFuchsia.c",
        "InstrProfilingPlatformLinux.c",
        "InstrProfilingPlatformOther.c",
        "InstrProfilingPlatformWindows.c",
        "InstrProfilingUtil.c",
        "InstrProfilingValue.c",
        "InstrProfilingWriter.c",
        // This file was renamed in LLVM 10.
        "InstrProfilingRuntime.cc",
        "InstrProfilingRuntime.cpp",
        // These files were added in LLVM 11.
        "InstrProfilingInternal.c",
        "InstrProfilingBiasVar.c",
    ];

    if target.contains("msvc") {
        // Don't pull in extra libraries on MSVC
        cfg.flag("/Zl");
        profile_sources.push("WindowsMMap.c");
        cfg.define("strdup", Some("_strdup"));
        cfg.define("open", Some("_open"));
        cfg.define("fdopen", Some("_fdopen"));
        cfg.define("getpid", Some("_getpid"));
        cfg.define("fileno", Some("_fileno"));
    } else {
        // Turn off various features of gcc and such, mostly copying
        // compiler-rt's build system already
        cfg.flag("-fno-builtin");
        cfg.flag("-fvisibility=hidden");
        cfg.flag("-fomit-frame-pointer");
        cfg.define("VISIBILITY_HIDDEN", None);
        if !target.contains("windows") {
            cfg.define("COMPILER_RT_HAS_UNAME", Some("1"));
        } else {
            profile_sources.push("WindowsMMap.c");
        }
    }

    // Assume that the Unixes we are building this for have fnctl() available
    if env::var_os("CARGO_CFG_UNIX").is_some() {
        cfg.define("COMPILER_RT_HAS_FCNTL_LCK", Some("1"));
    }

    // This should be a pretty good heuristic for when to set
    // COMPILER_RT_HAS_ATOMICS
    if env::var_os("CARGO_CFG_TARGET_HAS_ATOMIC")
        .map(|features| features.to_string_lossy().to_lowercase().contains("ptr"))
        .unwrap_or(false)
    {
        cfg.define("COMPILER_RT_HAS_ATOMICS", Some("1"));
    }

    // Note that this should exist if we're going to run (otherwise we just
    // don't build profiler builtins at all).
    let root = Path::new("../../src/llvm-project/compiler-rt");

    let src_root = root.join("lib").join("profile");
    for src in profile_sources {
        let path = src_root.join(src);
        if path.exists() {
            cfg.file(path);
        }
    }

    cfg.include(root.join("include"));
    cfg.warnings(false);
    cfg.compile("profiler-rt");
}
<commit_msg>Fix warning whe building profiler_builtins crate<commit_after>//! Compiles the profiler part of the `compiler-rt` library.
//!
//! See the build.rs for libcompiler_builtins crate for details.

use std::env;
use std::path::Path;

fn main() {
    let target = env::var("TARGET").expect("TARGET was not set");
    let cfg = &mut cc::Build::new();

    // FIXME: `rerun-if-changed` directives are not currently emitted and the build script
    // will not rerun on changes in these source files or headers included into them.
    let mut profile_sources = vec![
        "GCDAProfiling.c",
        "InstrProfiling.c",
        "InstrProfilingBuffer.c",
        "InstrProfilingFile.c",
        "InstrProfilingMerge.c",
        "InstrProfilingMergeFile.c",
        "InstrProfilingNameVar.c",
        "InstrProfilingPlatformDarwin.c",
        "InstrProfilingPlatformFuchsia.c",
        "InstrProfilingPlatformLinux.c",
        "InstrProfilingPlatformOther.c",
        "InstrProfilingPlatformWindows.c",
        "InstrProfilingUtil.c",
        "InstrProfilingValue.c",
        "InstrProfilingWriter.c",
        // This file was renamed in LLVM 10.
        "InstrProfilingRuntime.cc",
        "InstrProfilingRuntime.cpp",
        // These files were added in LLVM 11.
        "InstrProfilingInternal.c",
        "InstrProfilingBiasVar.c",
    ];

    if target.contains("msvc") {
        // Don't pull in extra libraries on MSVC
        cfg.flag("/Zl");
        profile_sources.push("WindowsMMap.c");
        cfg.define("strdup", Some("_strdup"));
        cfg.define("open", Some("_open"));
        cfg.define("fdopen", Some("_fdopen"));
        cfg.define("getpid", Some("_getpid"));
        cfg.define("fileno", Some("_fileno"));
    } else {
        // Turn off various features of gcc and such, mostly copying
        // compiler-rt's build system already
        cfg.flag("-fno-builtin");
        cfg.flag("-fomit-frame-pointer");
        cfg.define("VISIBILITY_HIDDEN", None);
        if !target.contains("windows") {
            cfg.flag("-fvisibility=hidden");
            cfg.define("COMPILER_RT_HAS_UNAME", Some("1"));
        } else {
            profile_sources.push("WindowsMMap.c");
        }
    }

    // Assume that the Unixes we are building this for have fnctl() available
    if env::var_os("CARGO_CFG_UNIX").is_some() {
        cfg.define("COMPILER_RT_HAS_FCNTL_LCK", Some("1"));
    }

    // This should be a pretty good heuristic for when to set
    // COMPILER_RT_HAS_ATOMICS
    if env::var_os("CARGO_CFG_TARGET_HAS_ATOMIC")
        .map(|features| features.to_string_lossy().to_lowercase().contains("ptr"))
        .unwrap_or(false)
    {
        cfg.define("COMPILER_RT_HAS_ATOMICS", Some("1"));
    }

    // Note that this should exist if we're going to run (otherwise we just
    // don't build profiler builtins at all).
    let root = Path::new("../../src/llvm-project/compiler-rt");

    let src_root = root.join("lib").join("profile");
    for src in profile_sources {
        let path = src_root.join(src);
        if path.exists() {
            cfg.file(path);
        }
    }

    cfg.include(root.join("include"));
    cfg.warnings(false);
    cfg.compile("profiler-rt");
}
<|endoftext|>


<commit_before>use std::iter;

use super::{LinkerFlavor, PanicStrategy, Target, TargetOptions};

pub fn target() -> Result<Target, String> {
    const PRE_LINK_ARGS: &[&str] = &[
        "-Wl,--as-needed",
        "-Wl,-z,noexecstack",
        "-m64",
        "-fuse-ld=gold",
        "-nostdlib",
        "-shared",
        "-Wl,-e,sgx_entry",
        "-Wl,-Bstatic",
        "-Wl,--gc-sections",
        "-Wl,-z,text",
        "-Wl,-z,norelro",
        "-Wl,--rosegment",
        "-Wl,--no-undefined",
        "-Wl,--error-unresolved-symbols",
        "-Wl,--no-undefined-version",
        "-Wl,-Bsymbolic",
        "-Wl,--export-dynamic",
        // The following symbols are needed by libunwind, which is linked after
        // libstd. Make sure they're included in the link.
        "-Wl,-u,__rust_abort",
        "-Wl,-u,__rust_c_alloc",
        "-Wl,-u,__rust_c_dealloc",
        "-Wl,-u,__rust_print_err",
        "-Wl,-u,__rust_rwlock_rdlock",
        "-Wl,-u,__rust_rwlock_unlock",
        "-Wl,-u,__rust_rwlock_wrlock",
    ];

    const EXPORT_SYMBOLS: &[&str] = &[
        "sgx_entry",
        "HEAP_BASE",
        "HEAP_SIZE",
        "RELA",
        "RELACOUNT",
        "ENCLAVE_SIZE",
        "CFGDATA_BASE",
        "DEBUG",
        "EH_FRM_HDR_BASE",
        "EH_FRM_HDR_SIZE",
        "TEXT_BASE",
        "TEXT_SIZE",
    ];
    let opts = TargetOptions {
        dynamic_linking: false,
        executables: true,
        linker_is_gnu: true,
        max_atomic_width: Some(64),
        panic_strategy: PanicStrategy::Unwind,
        cpu: "x86-64".into(),
        features: "+rdrnd,+rdseed".into(),
        position_independent_executables: true,
        pre_link_args: iter::once((
            LinkerFlavor::Gcc,
            PRE_LINK_ARGS.iter().cloned().map(String::from).collect(),
        ))
        .collect(),
        post_link_objects: vec!["libunwind.a".into()],
        override_export_symbols: Some(EXPORT_SYMBOLS.iter().cloned().map(String::from).collect()),
        ..Default::default()
    };
    Ok(Target {
        llvm_target: "x86_64-unknown-linux-gnu".into(),
        target_endian: "little".into(),
        target_pointer_width: "64".into(),
        target_c_int_width: "32".into(),
        target_os: "unknown".into(),
        target_env: "sgx".into(),
        target_vendor: "fortanix".into(),
        data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".into(),
        arch: "x86_64".into(),
        linker_flavor: LinkerFlavor::Gcc,
        options: opts,
    })
}
<commit_msg>Rollup merge of #62698 - jethrogb:jb/sgx-llvm-target, r=alexcrichton<commit_after>use std::iter;

use super::{LinkerFlavor, PanicStrategy, Target, TargetOptions};

pub fn target() -> Result<Target, String> {
    const PRE_LINK_ARGS: &[&str] = &[
        "-Wl,--as-needed",
        "-Wl,-z,noexecstack",
        "-m64",
        "-fuse-ld=gold",
        "-nostdlib",
        "-shared",
        "-Wl,-e,sgx_entry",
        "-Wl,-Bstatic",
        "-Wl,--gc-sections",
        "-Wl,-z,text",
        "-Wl,-z,norelro",
        "-Wl,--rosegment",
        "-Wl,--no-undefined",
        "-Wl,--error-unresolved-symbols",
        "-Wl,--no-undefined-version",
        "-Wl,-Bsymbolic",
        "-Wl,--export-dynamic",
        // The following symbols are needed by libunwind, which is linked after
        // libstd. Make sure they're included in the link.
        "-Wl,-u,__rust_abort",
        "-Wl,-u,__rust_c_alloc",
        "-Wl,-u,__rust_c_dealloc",
        "-Wl,-u,__rust_print_err",
        "-Wl,-u,__rust_rwlock_rdlock",
        "-Wl,-u,__rust_rwlock_unlock",
        "-Wl,-u,__rust_rwlock_wrlock",
    ];

    const EXPORT_SYMBOLS: &[&str] = &[
        "sgx_entry",
        "HEAP_BASE",
        "HEAP_SIZE",
        "RELA",
        "RELACOUNT",
        "ENCLAVE_SIZE",
        "CFGDATA_BASE",
        "DEBUG",
        "EH_FRM_HDR_BASE",
        "EH_FRM_HDR_SIZE",
        "TEXT_BASE",
        "TEXT_SIZE",
    ];
    let opts = TargetOptions {
        dynamic_linking: false,
        executables: true,
        linker_is_gnu: true,
        max_atomic_width: Some(64),
        panic_strategy: PanicStrategy::Unwind,
        cpu: "x86-64".into(),
        features: "+rdrnd,+rdseed".into(),
        position_independent_executables: true,
        pre_link_args: iter::once((
            LinkerFlavor::Gcc,
            PRE_LINK_ARGS.iter().cloned().map(String::from).collect(),
        ))
        .collect(),
        post_link_objects: vec!["libunwind.a".into()],
        override_export_symbols: Some(EXPORT_SYMBOLS.iter().cloned().map(String::from).collect()),
        ..Default::default()
    };
    Ok(Target {
        llvm_target: "x86_64-elf".into(),
        target_endian: "little".into(),
        target_pointer_width: "64".into(),
        target_c_int_width: "32".into(),
        target_os: "unknown".into(),
        target_env: "sgx".into(),
        target_vendor: "fortanix".into(),
        data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".into(),
        arch: "x86_64".into(),
        linker_flavor: LinkerFlavor::Gcc,
        options: opts,
    })
}
<|endoftext|>


<commit_before>mod static_string_indexing;
mod instructions_template;

use static_string_indexing::index_static_strings;
use instructions_template::generate_instructions_rs;

use std::env;
use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::{self, Command};

fn find_prolog_files(libraries: &mut File, prefix: &str, current_dir: &Path) {
    let entries = match current_dir.read_dir() {
        Ok(entries) => entries,
        Err(_) => return,
    };

    for entry in entries.filter_map(Result::ok).map(|e| e.path()) {
        if entry.is_dir() {
            if let Some(file_name) = entry.file_name() {
                let new_prefix = prefix.to_owned() + file_name.to_str().unwrap() + "/";
                find_prolog_files(libraries, &new_prefix, &entry);
            }
        } else if entry.is_file() {
            let ext = std::ffi::OsStr::new("pl");
            if entry.extension() == Some(ext) {
                let contain = String::from_utf8(fs::read(&entry).unwrap()).unwrap();
                let name = entry.file_stem().unwrap().to_str().unwrap();

                let line = format!(
                    "        m.insert(\"{}\",\n{:?});\n",
                    prefix.to_owned() + name,
                    contain
                );

                libraries.write_all(line.as_bytes()).unwrap();
            }
        }
    }
}

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("libraries.rs");

    let mut libraries = File::create(&dest_path).unwrap();
    let lib_path = Path::new("src/lib");

    libraries
        .write_all(
            b"ref_thread_local::ref_thread_local! {
    pub(crate) static managed LIBRARIES: IndexMap<&'static str, &'static str> = {
        let mut m = IndexMap::new();\n",
        )
        .unwrap();

    find_prolog_files(&mut libraries, "", &lib_path);
    libraries.write_all(b"\n        m\n    };\n}\n").unwrap();

    let instructions_path = Path::new(&out_dir).join("instructions.rs");
    let mut instructions_file = File::create(&instructions_path).unwrap();

    let quoted_output = generate_instructions_rs();

    instructions_file
        .write_all(quoted_output.to_string().as_bytes())
        .unwrap();

    format_generated_file(instructions_path.as_path());

    let static_atoms_path = Path::new(&out_dir).join("static_atoms.rs");
    let mut static_atoms_file = File::create(&static_atoms_path).unwrap();

    let quoted_output = index_static_strings(&instructions_path);

    static_atoms_file
        .write_all(quoted_output.to_string().as_bytes())
        .unwrap();

    format_generated_file(static_atoms_path.as_path());

    println!("cargo:rerun-if-changed=src/");
}

fn format_generated_file(path: &Path) {
    Command::new("rustfmt")
        .arg(path.as_os_str())
        .spawn()
        .unwrap_or_else(|err| {
            eprintln!(
                "{}: rustfmt (https://github.com/rust-lang/rustfmt) \
                is required build time dependency and must be available \
                in the environment's PATH variable.",
                err
            );
            process::exit(1);
        })
        .wait()
        .unwrap();
}
<commit_msg>make rustfmt optional<commit_after>mod instructions_template;
mod static_string_indexing;

use instructions_template::generate_instructions_rs;
use static_string_indexing::index_static_strings;

use std::env;
use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::{self, Command, Stdio};

fn find_prolog_files(libraries: &mut File, prefix: &str, current_dir: &Path) {
    let entries = match current_dir.read_dir() {
        Ok(entries) => entries,
        Err(_) => return,
    };

    for entry in entries.filter_map(Result::ok).map(|e| e.path()) {
        if entry.is_dir() {
            if let Some(file_name) = entry.file_name() {
                let new_prefix = prefix.to_owned() + file_name.to_str().unwrap() + "/";
                find_prolog_files(libraries, &new_prefix, &entry);
            }
        } else if entry.is_file() {
            let ext = std::ffi::OsStr::new("pl");
            if entry.extension() == Some(ext) {
                let contain = String::from_utf8(fs::read(&entry).unwrap()).unwrap();
                let name = entry.file_stem().unwrap().to_str().unwrap();

                let line = format!(
                    "        m.insert(\"{}\",\n{:?});\n",
                    prefix.to_owned() + name,
                    contain
                );

                libraries.write_all(line.as_bytes()).unwrap();
            }
        }
    }
}

fn main() {
    let has_rustfmt = Command::new("rustfmt")
        .arg("--version")
        .stdin(Stdio::inherit())
        .status()
        .is_ok();

    if !has_rustfmt {
        println!("Failed to run rustfmt, will skip formatting generated files.")
    }

    let out_dir = env::var("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("libraries.rs");

    let mut libraries = File::create(&dest_path).unwrap();
    let lib_path = Path::new("src/lib");

    libraries
        .write_all(
            b"ref_thread_local::ref_thread_local! {
    pub(crate) static managed LIBRARIES: IndexMap<&'static str, &'static str> = {
        let mut m = IndexMap::new();\n",
        )
        .unwrap();

    find_prolog_files(&mut libraries, "", &lib_path);
    libraries.write_all(b"\n        m\n    };\n}\n").unwrap();

    let instructions_path = Path::new(&out_dir).join("instructions.rs");
    let mut instructions_file = File::create(&instructions_path).unwrap();

    let quoted_output = generate_instructions_rs();

    instructions_file
        .write_all(quoted_output.to_string().as_bytes())
        .unwrap();

    if has_rustfmt {
        format_generated_file(instructions_path.as_path());
    }

    let static_atoms_path = Path::new(&out_dir).join("static_atoms.rs");
    let mut static_atoms_file = File::create(&static_atoms_path).unwrap();

    let quoted_output = index_static_strings(&instructions_path);

    static_atoms_file
        .write_all(quoted_output.to_string().as_bytes())
        .unwrap();

    if has_rustfmt {
        format_generated_file(static_atoms_path.as_path());
    }

    println!("cargo:rerun-if-changed=src/");
}

fn format_generated_file(path: &Path) {
    Command::new("rustfmt")
        .arg(path.as_os_str())
        .spawn()
        .unwrap_or_else(|err| {
            eprintln!(
                "{}: rustfmt (https://github.com/rust-lang/rustfmt) \
                is required build time dependency and must be available \
                in the environment's PATH variable.",
                err
            );
            process::exit(1);
        })
        .wait()
        .unwrap();
}
<|endoftext|>