text:
//! Support for Unix domain socket clients and servers.
#![warn(missing_docs)]
#![doc(html_root_url="https://doc.rust-lang.org/unix-socket/doc/v0.5.0")]

extern crate libc;

use std::ascii;
use std::cmp::Ordering;
use std::convert::AsRef;
use std::ffi::OsStr;
use std::fmt;
use std::io;
use std::iter::IntoIterator;
use std::mem;
use std::net::Shutdown;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::io::{RawFd, AsRawFd, FromRawFd, IntoRawFd};
use std::path::Path;
use std::time::Duration;

fn sun_path_offset() -> usize {
    unsafe {
        // Work with an actual instance of the type since using a null pointer is UB
        let addr: libc::sockaddr_un = mem::uninitialized();
        let base = &addr as *const _ as usize;
        let path = &addr.sun_path as *const _ as usize;
        path - base
    }
}

fn cvt(v: libc::c_int) -> io::Result<libc::c_int> {
    if v < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(v)
    }
}

fn cvt_s(v: libc::ssize_t) -> io::Result<libc::ssize_t> {
    if v < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(v)
    }
}

struct Inner(RawFd);

impl Drop for Inner {
    fn drop(&mut self) {
        unsafe {
            libc::close(self.0);
        }
    }
}

impl Inner {
    fn new(kind: libc::c_int) -> io::Result<Inner> {
        unsafe { cvt(libc::socket(libc::AF_UNIX, kind, 0)).map(Inner) }
    }

    fn new_pair(kind: libc::c_int) -> io::Result<(Inner, Inner)> {
        unsafe {
            let mut fds = [0, 0];
            try!(cvt(libc::socketpair(libc::AF_UNIX, kind, 0, fds.as_mut_ptr())));
            Ok((Inner(fds[0]), Inner(fds[1])))
        }
    }

    fn try_clone(&self) -> io::Result<Inner> {
        unsafe { cvt(libc::dup(self.0)).map(Inner) }
    }

    fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        let how = match how {
            Shutdown::Read => libc::SHUT_RD,
            Shutdown::Write => libc::SHUT_WR,
            Shutdown::Both => libc::SHUT_RDWR,
        };

        unsafe { cvt(libc::shutdown(self.0, how)).map(|_| ()) }
    }

    fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
        let timeout = unsafe {
            let mut timeout: libc::timeval = mem::zeroed();
            let mut size = mem::size_of::<libc::timeval>() as libc::socklen_t;
            try!(cvt(libc::getsockopt(self.0,
                                      libc::SOL_SOCKET,
                                      kind,
                                      &mut timeout as *mut _ as *mut _,
                                      &mut size as *mut _ as *mut _)));
            timeout
        };

        if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
            Ok(None)
        } else {
            Ok(Some(Duration::new(timeout.tv_sec as u64, (timeout.tv_usec as u32) * 1000)))
        }
    }

    fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
        let timeout = match dur {
            Some(dur) => {
                if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
                    return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                              "cannot set a 0 duration timeout"));
                }

                let (secs, usecs) = if dur.as_secs() > libc::time_t::max_value() as u64 {
                    (libc::time_t::max_value(), 999_999)
                } else {
                    (dur.as_secs() as libc::time_t,
                     (dur.subsec_nanos() / 1000) as libc::suseconds_t)
                };
                let mut timeout = libc::timeval {
                    tv_sec: secs,
                    tv_usec: usecs,
                };
                if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
                    timeout.tv_usec = 1;
                }
                timeout
            }
            None => {
                libc::timeval {
                    tv_sec: 0,
                    tv_usec: 0,
                }
            }
        };

        unsafe {
            cvt(libc::setsockopt(self.0,
                                 libc::SOL_SOCKET,
                                 kind,
                                 &timeout as *const _ as *const _,
                                 mem::size_of::<libc::timeval>() as libc::socklen_t))
                .map(|_| ())
        }
    }

    fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        let mut nonblocking = nonblocking as libc::c_ulong;
        unsafe { cvt(libc::ioctl(self.0, libc::FIONBIO, &mut nonblocking)).map(|_| ()) }
    }

    fn take_error(&self) -> io::Result<Option<io::Error>> {
        let mut errno: libc::c_int = 0;

        unsafe {
            try!(cvt(libc::getsockopt(self.0,
                                      libc::SOL_SOCKET,
                                      libc::SO_ERROR,
                                      &mut errno as *mut _ as *mut _,
                                      &mut mem::size_of_val(&errno) as *mut _ as *mut _)));
        }

        if errno == 0 {
            Ok(None)
        } else {
            Ok(Some(io::Error::from_raw_os_error(errno)))
        }
    }
}

unsafe fn sockaddr_un<P: AsRef<Path>>(path: P) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
    let mut addr: libc::sockaddr_un = mem::zeroed();
    addr.sun_family = libc::AF_UNIX as libc::sa_family_t;

    let bytes = path.as_ref().as_os_str().as_bytes();

    match (bytes.get(0), bytes.len().cmp(&addr.sun_path.len())) {
        // Abstract paths don't need a null terminator
        (Some(&0), Ordering::Greater) => {
            return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                      "path must be no longer than SUN_LEN"));
        }
        (Some(&0), _) => {},
        (_, Ordering::Greater) | (_, Ordering::Equal) => {
            return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                      "path must be shorter than SUN_LEN"));
        }
        _ => {}
    }
    for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) {
        *dst = *src as libc::c_char;
    }
    // null byte for pathname addresses is already there because we zeroed the
    // struct

    let mut len = sun_path_offset() + bytes.len();
    match bytes.get(0) {
        Some(&0) | None => {}
        Some(_) => len += 1,
    }
    Ok((addr, len as libc::socklen_t))
}

enum AddressKind<'a> {
    Unnamed,
    Pathname(&'a Path),
    Abstract(&'a [u8]),
}

/// An address associated with a Unix socket.
#[derive(Clone)]
pub struct SocketAddr {
    addr: libc::sockaddr_un,
    len: libc::socklen_t,
}

impl SocketAddr {
    fn new<F>(f: F) -> io::Result<SocketAddr>
        where F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int
    {
        unsafe {
            let mut addr: libc::sockaddr_un = mem::zeroed();
            let mut len = mem::size_of::<libc::sockaddr_un>() as libc::socklen_t;
            try!(cvt(f(&mut addr as *mut _ as *mut _, &mut len)));

            if len == 0 {
                // When there is a datagram from unnamed unix socket
                // linux returns zero bytes of address
                len = sun_path_offset() as libc::socklen_t;  // i.e. zero-length address
            } else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t {
                return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                          "file descriptor did not correspond to a Unix socket"));
            }

            Ok(SocketAddr {
                addr: addr,
                len: len,
            })
        }
    }

    /// Returns true iff the address is unnamed.
    pub fn is_unnamed(&self) -> bool {
        if let AddressKind::Unnamed = self.address() {
            true
        } else {
            false
        }
    }

    /// Returns the contents of this address if it is a `pathname` address.
    pub fn as_pathname(&self) -> Option<&Path> {
        if let AddressKind::Pathname(path) = self.address() {
            Some(path)
        } else {
            None
        }
    }

    fn address<'a>(&'a self) -> AddressKind<'a> {
        let len = self.len as usize - sun_path_offset();
        let path = unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&self.addr.sun_path) };

        // OSX seems to return a len of 16 and a zeroed sun_path for unnamed addresses
        if len == 0 || (cfg!(not(target_os = "linux")) && self.addr.sun_path[0] == 0) {
            AddressKind::Unnamed
        } else if self.addr.sun_path[0] == 0 {
            AddressKind::Abstract(&path[1..len])
        } else {
            AddressKind::Pathname(OsStr::from_bytes(&path[..len - 1]).as_ref())
        }
    }
}

impl fmt::Debug for SocketAddr {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self.address() {
            AddressKind::Unnamed => write!(fmt, "(unnamed)"),
            AddressKind::Abstract(name) => write!(fmt, "{} (abstract)", AsciiEscaped(name)),
            AddressKind::Pathname(path) => write!(fmt, "{:?} (pathname)", path),
        }
    }
}

struct AsciiEscaped<'a>(&'a [u8]);

impl<'a> fmt::Display for AsciiEscaped<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(fmt, "\""));
        for byte in self.0.iter().cloned().flat_map(ascii::escape_default) {
            try!(write!(fmt, "{}", byte as char));
        }
        write!(fmt, "\"")
    }
}

/// OS specific extension traits.
pub mod os {
    /// Linux specific extension traits.
    #[cfg(target_os = "linux")]
    pub mod linux {
        use {AddressKind, SocketAddr};

        /// Linux specific extensions for the `SocketAddr` type.
        pub trait SocketAddrExt {
            /// Returns the contents of this address (without the leading
            /// null byte) if it is an `abstract` address.
            fn as_abstract(&self) -> Option<&[u8]>;
        }

        impl SocketAddrExt for SocketAddr {
            fn as_abstract(&self) -> Option<&[u8]> {
                if let AddressKind::Abstract(path) = self.address() {
                    Some(path)
                } else {
                    None
                }
            }
        }
    }
}

/// A Unix stream socket.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
/// use std::io::prelude::*;
///
/// let mut stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// stream.write_all(b"hello world").unwrap();
/// let mut response = String::new();
/// stream.read_to_string(&mut response).unwrap();
/// println!("{}", response);
/// ```
pub struct UnixStream {
    inner: Inner,
}

impl fmt::Debug for UnixStream {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let mut builder = fmt.debug_struct("UnixStream");
        builder.field("fd", &self.inner.0);
        if let Ok(addr) = self.local_addr() {
            builder.field("local", &addr);
        }
        if let Ok(addr) = self.peer_addr() {
            builder.field("peer", &addr);
        }
        builder.finish()
    }
}

impl UnixStream {
    /// Connects to the socket named by `path`.
    ///
    /// Linux provides, as a nonportable extension, a separate "abstract"
    /// address namespace as opposed to filesystem-based addressing. If `path`
    /// begins with a null byte, it will be interpreted as an "abstract"
    /// address. Otherwise, it will be interpreted as a "pathname" address,
    /// corresponding to a path on the filesystem.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixStream;
    ///
    /// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
    /// ```
    pub fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
        unsafe {
            let inner = try!(Inner::new(libc::SOCK_STREAM));
            let (addr, len) = try!(sockaddr_un(path));

            let ret = libc::connect(inner.0, &addr as *const _ as *const _, len);
            if ret < 0 {
                Err(io::Error::last_os_error())
            } else {
                Ok(UnixStream { inner: inner })
            }
        }
    }

    /// Creates an unnamed pair of connected sockets.
    ///
    /// Returns two `UnixStream`s which are connected to each other.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixStream;
    ///
    /// let (stream1, stream2) = UnixStream::pair().unwrap();
    /// ```
    pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
        let (i1, i2) = try!(Inner::new_pair(libc::SOCK_STREAM));
        Ok((UnixStream { inner: i1 }, UnixStream { inner: i2 }))
    }

    /// Creates a new independently owned handle to the underlying socket.
    ///
    /// The returned `UnixStream` is a reference to the same stream that this
    /// object references. Both handles will read and write the same stream of
    /// data, and options set on one stream will be propogated to the other
    /// stream.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixStream;
    ///
    /// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
    /// let copy = stream.try_clone().unwrap();
    /// ```
    pub fn try_clone(&self) -> io::Result<UnixStream> {
        Ok(UnixStream { inner: try!(self.inner.try_clone()) })
    }

    /// Returns the socket address of the local half of this connection.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixStream;
    ///
    /// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
    /// println!("{}", match stream.local_addr() {
    ///     Ok(addr) => format!("local address: {:?}", addr),
    ///     Err(_) => "no local address".to_owned(),
    /// });
    /// ```
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        SocketAddr::new(|addr, len| unsafe { libc::getsockname(self.inner.0, addr, len) })
    }

    /// Returns the socket address of the remote half of this connection.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixStream;
    ///
    /// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
    /// println!("{}", match stream.peer_addr() {
    ///     Ok(addr) => format!("peer address: {:?}", addr),
    ///     Err(_) => "no peer address".to_owned(),
    /// });
    /// ```
    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
        SocketAddr::new(|addr, len| unsafe { libc::getpeername(self.inner.0, addr, len) })
    }

    /// Sets the read timeout for the socket.
    ///
    /// If the provided value is `None`, then `read` calls will block
    /// indefinitely. It is an error to pass the zero `Duration` to this
    /// method.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixStream;
    /// use std::time::Duration;
    ///
    /// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
    /// stream.set_read_timeout(Some(Duration::from_millis(1500))).unwrap();
    /// ```
    pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
        self.inner.set_timeout(timeout, libc::SO_RCVTIMEO)
    }

    /// Sets the write timeout for the socket.
    ///
    /// If the provided value is `None`, then `write` calls will block
    /// indefinitely. It is an error to pass the zero `Duration` to this
    /// method.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixStream;
    /// use std::time::Duration;
    ///
    /// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
    /// stream.set_write_timeout(Some(Duration::from_millis(1500))).unwrap();
    /// ```
    pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
        self.inner.set_timeout(timeout, libc::SO_SNDTIMEO)
    }

    /// Returns the read timeout of this socket.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixStream;
    ///
    /// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
    /// println!("{}", match stream.read_timeout() {
    ///     Ok(timeout) => format!("read timeout: {:?}", timeout),
    ///     Err(_) => "error".to_owned(),
    /// });
    /// ```
    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.timeout(libc::SO_RCVTIMEO)
    }

    /// Returns the write timeout of this socket.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixStream;
    ///
    /// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
    /// println!("{}", match stream.write_timeout() {
    ///     Ok(timeout) => format!("write timeout: {:?}", timeout),
    ///     Err(_) => "error".to_owned(),
    /// });
    /// ```
    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.timeout(libc::SO_SNDTIMEO)
    }

    /// Moves the socket into or out of nonblocking mode.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixStream;
    ///
    /// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
    /// stream.set_nonblocking(true).unwrap();
    /// ```
    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        self.inner.set_nonblocking(nonblocking)
    }

    /// Returns the value of the `SO_ERROR` option.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixStream;
    ///
    /// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
    /// println!("{}", match stream.take_error() {
    ///     Ok(ret) => format!("error: {:?}", ret),
    ///     Err(_) => "error".to_owned(),
    /// });
    /// ```
    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        self.inner.take_error()
    }

    /// Shuts down the read, write, or both halves of this connection.
    ///
    /// This function will cause all pending and future I/O calls on the
    /// specified portions to immediately return with an appropriate value
    /// (see the documentation of `Shutdown`).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use std::net::Shutdown;
    /// use unix_socket::UnixStream;
    ///
    /// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
    /// stream.shutdown(Shutdown::Both).unwrap();
    /// ```
    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        self.inner.shutdown(how)
    }
}

impl io::Read for UnixStream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        io::Read::read(&mut &*self, buf)
    }
}

impl<'a> io::Read for &'a UnixStream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        unsafe {
            cvt_s(libc::recv(self.inner.0, buf.as_mut_ptr() as *mut _, buf.len(), 0))
                .map(|r| r as usize)
        }
    }
}

impl io::Write for UnixStream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        io::Write::write(&mut &*self, buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        io::Write::flush(&mut &*self)
    }
}

impl<'a> io::Write for &'a UnixStream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        unsafe {
            cvt_s(libc::send(self.inner.0, buf.as_ptr() as *const _, buf.len(), 0))
                .map(|r| r as usize)
        }
    }

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

impl AsRawFd for UnixStream {
    fn as_raw_fd(&self) -> RawFd {
        self.inner.0
    }
}

impl FromRawFd for UnixStream {
    unsafe fn from_raw_fd(fd: RawFd) -> UnixStream {
        UnixStream { inner: Inner(fd) }
    }
}

impl IntoRawFd for UnixStream {
    fn into_raw_fd(self) -> RawFd {
        let fd = self.inner.0;
        mem::forget(self);
        fd
    }
}

/// A structure representing a Unix domain socket server.
///
/// # Examples
///
/// ```rust,no_run
/// use std::thread;
/// use unix_socket::{UnixStream, UnixListener};
///
/// fn handle_client(stream: UnixStream) {
///     // ...
/// }
///
/// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
///
/// // accept connections and process them, spawning a new thread for each one
/// for stream in listener.incoming() {
///     match stream {
///         Ok(stream) => {
///             /* connection succeeded */
///             thread::spawn(|| handle_client(stream));
///         }
///         Err(err) => {
///             /* connection failed */
///             break;
///         }
///     }
/// }
///
/// // close the listener socket
/// drop(listener);
/// ```
pub struct UnixListener {
    inner: Inner,
}

impl fmt::Debug for UnixListener {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let mut builder = fmt.debug_struct("UnixListener");
        builder.field("fd", &self.inner.0);
        if let Ok(addr) = self.local_addr() {
            builder.field("local", &addr);
        }
        builder.finish()
    }
}

impl UnixListener {
    /// Creates a new `UnixListener` bound to the specified socket.
    ///
    /// Linux provides, as a nonportable extension, a separate "abstract"
    /// address namespace as opposed to filesystem-based addressing. If `path`
    /// begins with a null byte, it will be interpreted as an "abstract"
    /// address. Otherwise, it will be interpreted as a "pathname" address,
    /// corresponding to a path on the filesystem.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixListener;
    ///
    /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
    /// ```
    pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
        unsafe {
            let inner = try!(Inner::new(libc::SOCK_STREAM));
            let (addr, len) = try!(sockaddr_un(path));

            try!(cvt(libc::bind(inner.0, &addr as *const _ as *const _, len)));
            try!(cvt(libc::listen(inner.0, 128)));

            Ok(UnixListener { inner: inner })
        }
    }

    /// Accepts a new incoming connection to this listener.
    ///
    /// This function will block the calling thread until a new Unix connection
    /// is established. When established, the corersponding `UnixStream` and
    /// the remote peer's address will be returned.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixListener;
    ///
    /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
    /// let (client_stream, addr) = listener.accept().unwrap();
    /// ```
    pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
        unsafe {
            let mut fd = 0;
            let addr = try!(SocketAddr::new(|addr, len| {
                fd = libc::accept(self.inner.0, addr, len);
                fd
            }));

            Ok((UnixStream { inner: Inner(fd) }, addr))
        }
    }

    /// Creates a new independently owned handle to the underlying socket.
    ///
    /// The returned `UnixListener` is a reference to the same socket that this
    /// object references. Both handles can be used to accept incoming
    /// connections and options set on one listener will affect the other.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixListener;
    ///
    /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
    /// let copy = listener.try_clone().unwrap();
    /// ```
    pub fn try_clone(&self) -> io::Result<UnixListener> {
        Ok(UnixListener { inner: try!(self.inner.try_clone()) })
    }

    /// Returns the local socket address of this listener.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixListener;
    ///
    /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
    /// println!("{}", match listener.local_addr() {
    ///     Ok(addr) => format!("local address: {:?}", addr),
    ///     Err(_) => "no local address".to_owned(),
    /// });
    /// ```
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        SocketAddr::new(|addr, len| unsafe { libc::getsockname(self.inner.0, addr, len) })
    }

    /// Moves the socket into or out of nonblocking mode.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixListener;
    ///
    /// let mut listener = UnixListener::bind("/path/to/the/socket").unwrap();
    /// listener.set_nonblocking(true).unwrap();
    /// ```
    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        self.inner.set_nonblocking(nonblocking)
    }

    /// Returns the value of the `SO_ERROR` option.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixListener;
    ///
    /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
    /// println!("{}", match listener.take_error() {
    ///     Ok(ret) => format!("error: {:?}", ret),
    ///     Err(_) => "error".to_owned(),
    /// });
    /// ```
    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        self.inner.take_error()
    }

    /// Returns an iterator over incoming connections.
    ///
    /// The iterator will never return `None` and will also not yield the
    /// peer's `SocketAddr` structure.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use std::thread;
    /// use unix_socket::{UnixStream, UnixListener};
    ///
    /// fn handle_client(stream: UnixStream) {
    ///     // ...
    /// }
    ///
    /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
    ///
    /// // accept connections and process them, spawning a new thread for each one
    /// for stream in listener.incoming() {
    ///     match stream {
    ///         Ok(stream) => {
    ///             /* connection succeeded */
    ///             println!("incoming connection succeeded!");
    ///             thread::spawn(|| handle_client(stream));
    ///         }
    ///         Err(err) => {
    ///             /* connection failed */
    ///             println!("incoming connection failed...");
    ///         }
    ///     }
    /// }
    /// ```
    pub fn incoming<'a>(&'a self) -> Incoming<'a> {
        Incoming { listener: self }
    }
}

impl AsRawFd for UnixListener {
    fn as_raw_fd(&self) -> RawFd {
        self.inner.0
    }
}

impl FromRawFd for UnixListener {
    unsafe fn from_raw_fd(fd: RawFd) -> UnixListener {
        UnixListener { inner: Inner(fd) }
    }
}

impl IntoRawFd for UnixListener {
    fn into_raw_fd(self) -> RawFd {
        let fd = self.inner.0;
        mem::forget(self);
        fd
    }
}

impl<'a> IntoIterator for &'a UnixListener {
    type Item = io::Result<UnixStream>;
    type IntoIter = Incoming<'a>;

    fn into_iter(self) -> Incoming<'a> {
        self.incoming()
    }
}

/// An iterator over incoming connections to a `UnixListener`.
///
/// It will never return `None`.
#[derive(Debug)]
pub struct Incoming<'a> {
    listener: &'a UnixListener,
}

impl<'a> Iterator for Incoming<'a> {
    type Item = io::Result<UnixStream>;

    fn next(&mut self) -> Option<io::Result<UnixStream>> {
        Some(self.listener.accept().map(|s| s.0))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (usize::max_value(), None)
    }
}

/// A Unix datagram socket.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// socket.send_to(b"hello world", "/path/to/other/socket").unwrap();
/// let mut buf = [0; 100];
/// let (count, address) = socket.recv_from(&mut buf).unwrap();
/// println!("socket {:?} sent us {:?}", address, &buf[..count]);
/// ```
pub struct UnixDatagram {
    inner: Inner,
}

impl fmt::Debug for UnixDatagram {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let mut builder = fmt.debug_struct("UnixDatagram");
        builder.field("fd", &self.inner.0);
        if let Ok(addr) = self.local_addr() {
            builder.field("local", &addr);
        }
        if let Ok(addr) = self.peer_addr() {
            builder.field("peer", &addr);
        }
        builder.finish()
    }
}

impl UnixDatagram {
    /// Creates a Unix datagram socket bound to the given path.
    ///
    /// Linux provides, as a nonportable extension, a separate "abstract"
    /// address namespace as opposed to filesystem-based addressing. If `path`
    /// begins with a null byte, it will be interpreted as an "abstract"
    /// address. Otherwise, it will be interpreted as a "pathname" address,
    /// corresponding to a path on the filesystem.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
    /// ```
    pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
        unsafe {
            let inner = try!(Inner::new(libc::SOCK_DGRAM));
            let (addr, len) = try!(sockaddr_un(path));

            try!(cvt(libc::bind(inner.0, &addr as *const _ as *const _, len)));

            Ok(UnixDatagram { inner: inner })
        }
    }

    /// Creates a Unix Datagram socket which is not bound to any address.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::unbound().unwrap();
    /// ```
    pub fn unbound() -> io::Result<UnixDatagram> {
        let inner = try!(Inner::new(libc::SOCK_DGRAM));
        Ok(UnixDatagram { inner: inner })
    }

    /// Create an unnamed pair of connected sockets.
    ///
    /// Returns two `UnixDatagrams`s which are connected to each other.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let (socket1, socket2) = UnixDatagram::pair().unwrap();
    /// ```
    pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
        let (i1, i2) = try!(Inner::new_pair(libc::SOCK_DGRAM));
        Ok((UnixDatagram { inner: i1 }, UnixDatagram { inner: i2 }))
    }

    /// Connects the socket to the specified address.
    ///
    /// The `send` method may be used to send data to the specified address.
    /// `recv` and `recv_from` will only receive data from that address.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
    /// socket.connect("/path/to/other/socket").unwrap();
    /// ```
    pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
        unsafe {
            let (addr, len) = try!(sockaddr_un(path));

            try!(cvt(libc::connect(self.inner.0, &addr as *const _ as *const _, len)));

            Ok(())
        }
    }

    /// Creates a new independently owned handle to the underlying socket.
    ///
    /// The returned `UnixListener` is a reference to the same socket that this
    /// object references. Both handles can be used to accept incoming
    /// connections and options set on one listener will affect the other.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::unbound().unwrap();
    /// let copy = socket.try_clone().unwrap();
    /// ```
    pub fn try_clone(&self) -> io::Result<UnixDatagram> {
        Ok(UnixDatagram { inner: try!(self.inner.try_clone()) })
    }

    /// Returns the address of this socket.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/the/socket").unwrap();
    /// println!("{}", match socket.local_addr() {
    ///     Ok(addr) => format!("local address: {:?}", addr),
    ///     Err(_) => "no local address".to_owned(),
    /// });
    /// ```
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        SocketAddr::new(|addr, len| unsafe { libc::getsockname(self.inner.0, addr, len) })
    }

    /// Returns the address of this socket's peer.
    ///
    /// The `connect` method will connect the socket to a peer.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/the/socket").unwrap();
    /// println!("{}", match socket.peer_addr() {
    ///     Ok(addr) => format!("peer address: {:?}", addr),
    ///     Err(_) => "no peer address".to_owned(),
    /// });
    /// ```
    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
        SocketAddr::new(|addr, len| unsafe { libc::getpeername(self.inner.0, addr, len) })
    }

    /// Receives data from the socket.
    ///
    /// On success, returns the number of bytes read and the address from
    /// whence the data came.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
    /// let mut buf = [0; 100];
    /// let (count, address) = socket.recv_from(&mut buf).unwrap();
    /// println!("socket {:?} sent us {:?}", address, &buf[..count]);
    /// ```
    pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
        let mut count = 0;
        let addr = try!(SocketAddr::new(|addr, len| {
            unsafe {
                count = libc::recvfrom(self.inner.0,
                                       buf.as_mut_ptr() as *mut _,
                                       buf.len(),
                                       0,
                                       addr,
                                       len);
                if count > 0 {
                    1
                } else if count == 0 {
                    0
                } else {
                    -1
                }
            }
        }));

        Ok((count as usize, addr))
    }

    /// Receives data from the socket.
    ///
    /// On success, returns the number of bytes read.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
    /// socket.connect("/path/to/other/socket").unwrap();
    /// let mut buf = [0; 100];
    /// let count = socket.recv(&mut buf).unwrap();
    /// println!("we received {:?}", &buf[..count]);
    /// ```
    pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
        unsafe {
            let count = try!(cvt_s(libc::recv(self.inner.0,
                                              buf.as_mut_ptr() as *mut _,
                                              buf.len(),
                                              0)));
            Ok(count as usize)
        }
    }

    /// Sends data on the socket to the specified address.
    ///
    /// On success, returns the number of bytes written.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
    ///
    /// let mut data = b"hello world";
    /// let mut sent = 0;
    /// while sent < data.len() {
    ///     match socket.send_to(&data[sent..(data.len() - sent)], "/path/to/other/socket") {
    ///         Ok(data_sent) => { sent += data_sent; }
    ///         Err(_) => {
    ///             println!("an error occured while sending data...");
    ///             break;
    ///         }
    ///     }
    /// }
    /// ```
    pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
        unsafe {
            let (addr, len) = try!(sockaddr_un(path));

            let count = try!(cvt_s(libc::sendto(self.inner.0,
                                                buf.as_ptr() as *const _,
                                                buf.len(),
                                                0,
                                                &addr as *const _ as *const _,
                                                len)));
            Ok(count as usize)
        }
    }

    /// Sends data on the socket to the socket's peer.
    ///
    /// The peer address may be set by the `connect` method, and this method
    /// will return an error if the socket has not already been connected.
    ///
    /// On success, returns the number of bytes written.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
    /// socket.connect("/path/to/other/socket").unwrap();
    ///
    /// let mut data = b"hello world";
    /// let mut sent = 0;
    /// while sent < data.len() {
    ///     match socket.send(&data[sent..(data.len() - sent)]) {
    ///         Ok(data_sent) => { sent += data_sent; }
    ///         Err(_) => {
    ///             println!("an error occured while sending data...");
    ///             break;
    ///         }
    ///     }
    /// }
    /// ```
    pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
        unsafe {
            let count = try!(cvt_s(libc::send(self.inner.0,
                                              buf.as_ptr() as *const _,
                                              buf.len(),
                                              0)));
            Ok(count as usize)
        }
    }

    /// Sets the read timeout for the socket.
    ///
    /// If the provided value is `None`, then `recv` and `recv_from` calls will
    /// block indefinitely. It is an error to pass the zero `Duration` to this
    /// method.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    /// use std::time::Duration;
    ///
    /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
    /// socket.set_read_timeout(Some(Duration::from_millis(1500))).unwrap();
    /// ```
    pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
        self.inner.set_timeout(timeout, libc::SO_RCVTIMEO)
    }

    /// Sets the write timeout for the socket.
    ///
    /// If the provided value is `None`, then `send` and `send_to` calls will
    /// block indefinitely. It is an error to pass the zero `Duration` to this
    /// method.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    /// use std::time::Duration;
    ///
    /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
    /// socket.set_write_timeout(Some(Duration::from_millis(1500))).unwrap();
    /// ```
    pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
        self.inner.set_timeout(timeout, libc::SO_SNDTIMEO)
    }

    /// Returns the read timeout of this socket.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
    /// println!("{}", match socket.read_timeout() {
    ///     Ok(timeout) => format!("read timeout: {:?}", timeout),
    ///     Err(_) => "error".to_owned(),
    /// });
    /// ```
    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.timeout(libc::SO_RCVTIMEO)
    }

    /// Returns the write timeout of this socket.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
    /// println!("{}", match socket.write_timeout() {
    ///     Ok(timeout) => format!("write timeout: {:?}", timeout),
    ///     Err(_) => "error".to_owned(),
    /// });
    /// ```
    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.timeout(libc::SO_SNDTIMEO)
    }

    /// Moves the socket into or out of nonblocking mode.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
    /// socket.set_nonblocking(true).unwrap();
    /// ```
    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        self.inner.set_nonblocking(nonblocking)
    }

    /// Returns the value of the `SO_ERROR` option.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/the/socket").unwrap();
    /// println!("{}", match socket.take_error() {
    ///     Ok(ret) => format!("error: {:?}", ret),
    ///     Err(_) => "error".to_owned(),
    /// });
    /// ```
    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        self.inner.take_error()
    }

    /// Shut down the read, write, or both halves of this connection.
    ///
    /// This function will cause all pending and future I/O calls on the
    /// specified portions to immediately return with an appropriate value
    /// (see the documentation of `Shutdown`).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use std::net::Shutdown;
    /// use unix_socket::UnixDatagram;
    ///
    /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
    /// socket.connect("/path/to/other/socket").unwrap();
    /// socket.shutdown(Shutdown::Both).unwrap();
    /// ```
    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        self.inner.shutdown(how)
    }
}

impl AsRawFd for UnixDatagram {
    fn as_raw_fd(&self) -> RawFd {
        self.inner.0
    }
}

impl FromRawFd for UnixDatagram {
    unsafe fn from_raw_fd(fd: RawFd) -> UnixDatagram {
        UnixDatagram { inner: Inner(fd) }
    }
}

impl IntoRawFd for UnixDatagram {
    fn into_raw_fd(self) -> RawFd {
        let fd = self.inner.0;
        mem::forget(self);
        fd
    }
}

#[cfg(test)]
mod test {
    extern crate tempdir;
    extern crate libc;

    use std::thread;
    use std::io;
    use std::io::prelude::*;
    use std::time::Duration;
    use self::tempdir::TempDir;
    use std::net::Shutdown;

    use super::*;

    macro_rules! or_panic {
        ($e:expr) => {
            match $e {
                Ok(e) => e,
                Err(e) => panic!("{}", e),
            }
        }
    }

    #[test]
    fn basic() {
        let dir = or_panic!(TempDir::new("unix_socket"));
        let socket_path = dir.path().join("sock");
        let msg1 = b"hello";
        let msg2 = b"world!";

        let listener = or_panic!(UnixListener::bind(&socket_path));
        let thread = thread::spawn(move || {
            let mut stream = or_panic!(listener.accept()).0;
            let mut buf = [0; 5];
            or_panic!(stream.read(&mut buf));
            assert_eq!(&msg1[..], &buf[..]);
            or_panic!(stream.write_all(msg2));
        });

        let mut stream = or_panic!(UnixStream::connect(&socket_path));
        assert_eq!(Some(&*socket_path),
                   stream.peer_addr().unwrap().as_pathname());
        or_panic!(stream.write_all(msg1));
        let mut buf = vec![];
        or_panic!(stream.read_to_end(&mut buf));
        assert_eq!(&msg2[..], &buf[..]);
        drop(stream);

        thread.join().unwrap();
    }

    #[test]
    fn pair() {
        let msg1 = b"hello";
        let msg2 = b"world!";

        let (mut s1, mut s2) = or_panic!(UnixStream::pair());
        let thread = thread::spawn(move || {
            // s1 must be moved in or the test will hang!
            let mut buf = [0; 5];
            or_panic!(s1.read(&mut buf));
            assert_eq!(&msg1[..], &buf[..]);
            or_panic!(s1.write_all(msg2));
        });

        or_panic!(s2.write_all(msg1));
        let mut buf = vec![];
        or_panic!(s2.read_to_end(&mut buf));
        assert_eq!(&msg2[..], &buf[..]);
        drop(s2);

        thread.join().unwrap();
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn abstract_address() {
        use os::linux::SocketAddrExt;

        let socket_path = "\0the path";
        let msg1 = b"hello";
        let msg2 = b"world!";

        let listener = or_panic!(UnixListener::bind(&socket_path));
        let thread = thread::spawn(move || {
            let mut stream = or_panic!(listener.accept()).0;
            let mut buf = [0; 5];
            or_panic!(stream.read(&mut buf));
            assert_eq!(&msg1[..], &buf[..]);
            or_panic!(stream.write_all(msg2));
        });

        let mut stream = or_panic!(UnixStream::connect(&socket_path));
        assert_eq!(Some(&b"the path"[..]),
                   stream.peer_addr().unwrap().as_abstract());
        or_panic!(stream.write_all(msg1));
        let mut buf = vec![];
        or_panic!(stream.read_to_end(&mut buf));
        assert_eq!(&msg2[..], &buf[..]);
        drop(stream);

        thread.join().unwrap();
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn abstract_address_max_len() {
        use os::linux::SocketAddrExt;
        use std::ffi::OsStr;
        use std::io::Write;
        use std::mem;
        use std::os::unix::ffi::OsStrExt;

        let len = unsafe {
            let addr: libc::sockaddr_un = mem::zeroed();
            addr.sun_path.len()
        };

        let mut socket_path = vec![0; len];
        (&mut socket_path[1..9]).write_all(b"the path").unwrap();
        let socket_path: &OsStr = OsStr::from_bytes(&socket_path).into();

        let msg1 = b"hello";
        let msg2 = b"world!";

        let listener = or_panic!(UnixListener::bind(&socket_path));
        let thread = thread::spawn(move || {
            let mut stream = or_panic!(listener.accept()).0;
            let mut buf = [0; 5];
            or_panic!(stream.read(&mut buf));
            assert_eq!(&msg1[..], &buf[..]);
            or_panic!(stream.write_all(msg2));
        });

        let mut stream = or_panic!(UnixStream::connect(&socket_path));
        assert_eq!(Some(&socket_path.as_bytes()[1..]),
                   stream.peer_addr().unwrap().as_abstract());
        or_panic!(stream.write_all(msg1));
        let mut buf = vec![];
        or_panic!(stream.read_to_end(&mut buf));
        assert_eq!(&msg2[..], &buf[..]);
        drop(stream);

        thread.join().unwrap();
    }

    #[test]
    fn try_clone() {
        let dir = or_panic!(TempDir::new("unix_socket"));
        let socket_path = dir.path().join("sock");
        let msg1 = b"hello";
        let msg2 = b"world";

        let listener = or_panic!(UnixListener::bind(&socket_path));
        let thread = thread::spawn(move || {
            let mut stream = or_panic!(listener.accept()).0;
            or_panic!(stream.write_all(msg1));
            or_panic!(stream.write_all(msg2));
        });

        let mut stream = or_panic!(UnixStream::connect(&socket_path));
        let mut stream2 = or_panic!(stream.try_clone());

        let mut buf = [0; 5];
        or_panic!(stream.read(&mut buf));
        assert_eq!(&msg1[..], &buf[..]);
        or_panic!(stream2.read(&mut buf));
        assert_eq!(&msg2[..], &buf[..]);

        thread.join().unwrap();
    }

    #[test]
    fn iter() {
        let dir = or_panic!(TempDir::new("unix_socket"));
        let socket_path = dir.path().join("sock");

        let listener = or_panic!(UnixListener::bind(&socket_path));
        let thread = thread::spawn(move || {
            for stream in listener.incoming().take(2) {
                let mut stream = or_panic!(stream);
                let mut buf = [0];
                or_panic!(stream.read(&mut buf));
            }
        });

        for _ in 0..2 {
            let mut stream = or_panic!(UnixStream::connect(&socket_path));
            or_panic!(stream.write_all(&[0]));
        }

        thread.join().unwrap();
    }

    #[test]
    fn long_path() {
        let dir = or_panic!(TempDir::new("unix_socket"));
        let socket_path = dir.path()
                             .join("asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfa\
                                    sasdfasdfasdasdfasdfasdfadfasdfasdfasdfasdfasdf");
        match UnixStream::connect(&socket_path) {
            Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
            Err(e) => panic!("unexpected error {}", e),
            Ok(_) => panic!("unexpected success"),
        }

        match UnixListener::bind(&socket_path) {
            Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
            Err(e) => panic!("unexpected error {}", e),
            Ok(_) => panic!("unexpected success"),
        }

        match UnixDatagram::bind(&socket_path) {
            Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
            Err(e) => panic!("unexpected error {}", e),
            Ok(_) => panic!("unexpected success"),
        }
    }

    #[test]
    fn timeouts() {
        let dir = or_panic!(TempDir::new("unix_socket"));
        let socket_path = dir.path().join("sock");

        let _listener = or_panic!(UnixListener::bind(&socket_path));

        let stream = or_panic!(UnixStream::connect(&socket_path));
        let dur = Duration::new(15410, 0);

        assert_eq!(None, or_panic!(stream.read_timeout()));

        or_panic!(stream.set_read_timeout(Some(dur)));
        assert_eq!(Some(dur), or_panic!(stream.read_timeout()));

        assert_eq!(None, or_panic!(stream.write_timeout()));

        or_panic!(stream.set_write_timeout(Some(dur)));
        assert_eq!(Some(dur), or_panic!(stream.write_timeout()));

        or_panic!(stream.set_read_timeout(None));
        assert_eq!(None, or_panic!(stream.read_timeout()));

        or_panic!(stream.set_write_timeout(None));
        assert_eq!(None, or_panic!(stream.write_timeout()));
    }

    #[test]
    fn test_read_timeout() {
        let dir = or_panic!(TempDir::new("unix_socket"));
        let socket_path = dir.path().join("sock");

        let _listener = or_panic!(UnixListener::bind(&socket_path));

        let mut stream = or_panic!(UnixStream::connect(&socket_path));
        or_panic!(stream.set_read_timeout(Some(Duration::from_millis(1000))));

        let mut buf = [0; 10];
        let kind = stream.read(&mut buf).err().expect("expected error").kind();
        assert!(kind == io::ErrorKind::WouldBlock || kind == io::ErrorKind::TimedOut);
    }

    #[test]
    fn test_read_with_timeout() {
        let dir = or_panic!(TempDir::new("unix_socket"));
        let socket_path = dir.path().join("sock");

        let listener = or_panic!(UnixListener::bind(&socket_path));

        let mut stream = or_panic!(UnixStream::connect(&socket_path));
        or_panic!(stream.set_read_timeout(Some(Duration::from_millis(1000))));

        let mut other_end = or_panic!(listener.accept()).0;
        or_panic!(other_end.write_all(b"hello world"));

        let mut buf = [0; 11];
        or_panic!(stream.read(&mut buf));
        assert_eq!(b"hello world", &buf[..]);

        let kind = stream.read(&mut buf).err().expect("expected error").kind();
        assert!(kind == io::ErrorKind::WouldBlock || kind == io::ErrorKind::TimedOut);
    }

    #[test]
    fn test_unix_datagram() {
        let dir = or_panic!(TempDir::new("unix_socket"));
        let path1 = dir.path().join("sock1");
        let path2 = dir.path().join("sock2");

        let sock1 = or_panic!(UnixDatagram::bind(&path1));
        let sock2 = or_panic!(UnixDatagram::bind(&path2));

        let msg = b"hello world";
        or_panic!(sock1.send_to(msg, &path2));
        let mut buf = [0; 11];
        or_panic!(sock2.recv_from(&mut buf));
        assert_eq!(msg, &buf[..]);
    }

    #[test]
    fn test_unnamed_unix_datagram() {
        let dir = or_panic!(TempDir::new("unix_socket"));
        let path1 = dir.path().join("sock1");

        let sock1 = or_panic!(UnixDatagram::bind(&path1));
        let sock2 = or_panic!(UnixDatagram::unbound());

        let msg = b"hello world";
        or_panic!(sock2.send_to(msg, &path1));
        let mut buf = [0; 11];
        let (usize, addr) = or_panic!(sock1.recv_from(&mut buf));
        assert_eq!(usize, 11);
        assert!(addr.is_unnamed());
        assert_eq!(msg, &buf[..]);
    }

    #[test]
    fn test_connect_unix_datagram() {
        let dir = or_panic!(TempDir::new("unix_socket"));
        let path1 = dir.path().join("sock1");
        let path2 = dir.path().join("sock2");

        let bsock1 = or_panic!(UnixDatagram::bind(&path1));
        let bsock2 = or_panic!(UnixDatagram::bind(&path2));
        let sock = or_panic!(UnixDatagram::unbound());
        or_panic!(sock.connect(&path1));

        // Check send()
        let msg = b"hello there";
        or_panic!(sock.send(msg));
        let mut buf = [0; 11];
        let (usize, addr) = or_panic!(bsock1.recv_from(&mut buf));
        assert_eq!(usize, 11);
        assert!(addr.is_unnamed());
        assert_eq!(msg, &buf[..]);

        // Changing default socket works too
        or_panic!(sock.connect(&path2));
        or_panic!(sock.send(msg));
        or_panic!(bsock2.recv_from(&mut buf));
    }

    #[test]
    fn test_unix_datagram_recv() {
        let dir = or_panic!(TempDir::new("unix_socket"));
        let path1 = dir.path().join("sock1");

        let sock1 = or_panic!(UnixDatagram::bind(&path1));
        let sock2 = or_panic!(UnixDatagram::unbound());
        or_panic!(sock2.connect(&path1));

        let msg = b"hello world";
        or_panic!(sock2.send(msg));
        let mut buf = [0; 11];
        let size = or_panic!(sock1.recv(&mut buf));
        assert_eq!(size, 11);
        assert_eq!(msg, &buf[..]);
    }

    #[test]
    fn datagram_pair() {
        let msg1 = b"hello";
        let msg2 = b"world!";

        let (s1, s2) = or_panic!(UnixDatagram::pair());
        let thread = thread::spawn(move || {
            // s1 must be moved in or the test will hang!
            let mut buf = [0; 5];
            or_panic!(s1.recv(&mut buf));
            assert_eq!(&msg1[..], &buf[..]);
            or_panic!(s1.send(msg2));
        });

        or_panic!(s2.send(msg1));
        let mut buf = [0; 6];
        or_panic!(s2.recv(&mut buf));
        assert_eq!(&msg2[..], &buf[..]);
        drop(s2);

        thread.join().unwrap();
    }

    #[test]
    fn datagram_shutdown() {
        let s1 = UnixDatagram::unbound().unwrap();
        let s2 = s1.try_clone().unwrap();

        let thread = thread::spawn(move || {
            let mut buf = [0; 1];
            assert_eq!(0, s1.recv_from(&mut buf).unwrap().0);
        });

        thread::sleep(Duration::from_millis(100));
        s2.shutdown(Shutdown::Read).unwrap();;

        thread.join().unwrap();
    }
}


text:
class Initiatives::GatewaysController < StateController

  before_action :set_initiative
  before_action :set_gateway, except: %i[index new create]

  respond_to :html

  after_action :verify_authorized, except: %i[index]
  after_action :verify_policy_scoped, only: %i[index]

  def index
    @gateways = policy_scope(Gateway).where(initiative: @initiative)
  end

  def new
    @gateway = @initiative.gateways.new
    authorize @gateway
    module_names = @initiative.gateways.map(&:module_name)
    @gateways = @initiative.available_gateways
    respond_with @gateway
  end

  def create
    @gateway = @initiative.gateways.new(gateway_params)
    @gateways = @initiative.available_gateways
    authorize @gateway
    @gateway.save
    respond_with @gateway, location: -> { initiative_gateways_path(@initiative.id) }
  end

  def edit
    authorize @gateway
    @gateway.disable_fallback
  end

  def update
    authorize @gateway
    @gateway.update(gateway_params)
    respond_with @gateway, location: -> { initiative_gateways_path(@initiative.id) }
  end

  def use_production
    transition_state(:use_production)
  end

  def use_sandbox
    transition_state(:use_sandbox)
  end

  def revert_to_draft
    transition_state(:revert_to_draft)
  end

  private

  def set_initiative
    @initiative = Initiative.find(params[:initiative_id])
  end

  def set_gateway
    @gateway = @initiative.gateways.find(params[:id])
  end

  def gateway_params
    params.require(:gateway).permit(*policy(@gateway || Gateway.new).permitted_attributes)
  end

  def transition_state(transition)
    super(@gateway, transition, initiative_gateways_path(@initiative.id))
  end

  def allow_default_locales?
    set_initiative
    policy(@initiative).update?
  end

end

redpajama_set_name: RedPajamaGithub


text:
package org.hisp.dhis.android.dashboard.api.persistence.converters;

import com.raizlabs.android.dbflow.converter.TypeConverter;

import org.joda.time.DateTime;

/**
 * This class is used to automatically convert DateTime object to String
 * and backwards during read/write operations to database
 */
@SuppressWarnings("unused")
@com.raizlabs.android.dbflow.annotation.TypeConverter
public final class DateTimeConverter extends TypeConverter<String, DateTime> {

    @Override
    public String getDBValue(DateTime model) {
        if (model != null) {
            return model.toString();
        }

        return null;
    }

    @Override
    public DateTime getModelValue(String data) {
        if (data != null) {
            return DateTime.parse(data);
        }

        return null;
    }
}


text:
package io.dindinw.algo;

import static org.junit.Assert.assertArrayEquals;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

import org.junit.Test;
/**
 *  1. Big O Notation .
 *  O(n^2) means that if input is 2 then, algorithm takes 2^2 -> 4 times longer to run. so it
 *  means a bad algorithm in most case.
 *
 *  2. DualPivotQuicksort
 *  A Quicksort algorithm by Vladimir Yaroslavskiy, Jon Bentley, and Josh Bloch.
 *  @see
 *  http://permalink.gmane.org/gmane.comp.java.openjdk.core-libs.devel/2628
 *  http://programmingisterrible.com/post/41512566174/engineering-quicksort
 *  http://java.dzone.com/articles/algorithm-week-quicksort-three
 *  https://github.com/arunma/DataStructuresAlgorithms/tree/master/src/basics/sorting/quick
 *
 * @author yidwu
 *
 */
public class SortTest {

    /**
     * in Arrays.sort() use DualPivotQuicksort
     */
    @Test
    public void sortInts() {
        final int[] numbers = {-3, -5, 1, 7, 4, -2};
        final int[] expected = {-5, -3, -2, 1, 4, 7};
        Arrays.sort(numbers);
        assertArrayEquals(expected, numbers);
    }
    /**
     * Inside the Collections.sort() method, also use Arrays.sort()
     *  Object[] a = list.toArray();
        Arrays.sort(a);
        ListIterator<T> i = list.listIterator();
        for (int j=0; j<a.length; j++) {
            i.next();
            i.set((T)a[j]);
        }
     */
    @Test
    public void sortIntList() {
        final String[] strings = {"z", "x", "y", "abc", "zzz", "zazzy"};
        final String[] expected = {"abc", "x", "y", "z", "zazzy", "zzz"};

        List<String> list = Arrays.asList(strings);
        Collections.sort(list);

        ListIterator<String> i = list.listIterator();
        for (int j=0; j<strings.length; j++){
            strings[j] = i.next();
        }

        assertArrayEquals(expected, strings);
    }

    /**
     *
     */
    @Test
    public void sortObjects() {
        final String[] strings = {"z", "x", "y", "abc", "zzz", "zazzy"};
        final String[] expected = {"abc", "x", "y", "z", "zazzy", "zzz"};
        Arrays.sort(strings);
        assertArrayEquals(expected, strings);
    }

}


text:
title:  Misjonsfortelling
date:   13/07/2018
---

#### Å elske to pastorer

_Hee-Sook Kim (64) Sør-Korea_

To andre litteraturevanglister og jeg banket på hos et pastorpar som hadde annonsert en tilstelning for pastorstudenter. Det viste seg at de kjente vårt forlag. Mannen spurte: "Hvorfor går dere i kirke på lørdag?"

Jeg gjenga skapelsesberetningen og sa at Gud helliget sabbaten, og lovte et brevkurs neste gang vi kom. Men så sa han at han hadde vært pastor i 30 år og hans kone i ti år. Derfor ga jeg dem ikke et brevkurs, men hele Alfa og Omega-serien neste gang jeg kom.

Pastoren var spesielt interessert i Daniels bok, så neste gang hadde jeg med kommentarer til Daniel og Åpenbaringen.

Etter en tid fikk jeg en SMS fra ham der han ba om å få besøke kirken vår. Han kom noen ganger, men så ble han borte. Når jeg ringte, kom han med unnskyldninger. Senere fant jeg ut at hans kone hadde nektet ham å gå. Men jeg ba ham likevel komme.

Sju år senere ringte jeg og ba ham komme til helseseminarer. Der ville man lære om juice som kunne rense kroppen. "Det er nok best du snakker med min kone om dette," sa han. Så jeg ringte til henne, og hun kom sammen med sin mann.

Senere takket de ja til en møteserie om bibelske emner. Mannen virket overbevist, men var usikker. Så jeg inviterte dem til enda en serie. Det gjorde utslaget.

I 2017, åtte år etter vårt første møte, ble mann og kone døpt i Adventistkirken. Gud ord og helsebudskapet forvandler menneskers liv!

_Hee-Sook Kim ( 64) er litteraturevangelist på heltid. Neste uke skal vi lese hennes manns beretning._

- Sør-Korea har 715 kirker og 247 000 medlemmer.
- Over 50 % av koreanerne tilhører ingen religion. 28 % er kristne og 16 % er buddhister.
- I storbyområdet Seoul bor det over 25 mill. mennesker. Dette er verdens tredje største by.


text:
import numpy as np
from pyquil import Program
from pyquil.api import QuantumComputer, get_qc

from grove.alpha.jordan_gradient.gradient_utils import (binary_float_to_decimal_float,
                                                        measurements_to_bf)
from grove.alpha.phaseestimation.phase_estimation import phase_estimation

def gradient_program(f_h: float, precision: int) -> Program:
    """
    Gradient estimation via Jordan's algorithm (10.1103/PhysRevLett.95.050501).

    :param f_h: Oracle output at perturbation h.
    :param precision: Bit precision of gradient.
    :return: Quil program to estimate gradient of f.
    """

    # encode oracle values into phase
    phase_factor = np.exp(1.0j * 2 * np.pi * abs(f_h))
    U = np.array([[phase_factor, 0],
                  [0, phase_factor]])
    p_gradient = phase_estimation(U, precision)

    return p_gradient

def estimate_gradient(f_h: float, precision: int,
                      gradient_max: int = 1,
                      n_measurements: int = 50,
                      qc: QuantumComputer = None) -> float:
    """
    Estimate the gradient using function evaluation at perturbation, h.

    :param f_h: Oracle output at perturbation h.
    :param precision: Bit precision of gradient.
    :param gradient_max: OOM estimate of largest gradient value.
    :param n_measurements: Number of times to measure system.
    :param qc: The QuantumComputer object.
    :return: Decimal estimate of gradient.
    """

    # scale f_h by range of values gradient can take on
    f_h *= 1. / gradient_max

    # generate gradient program
    perturbation_sign = np.sign(f_h)
    p_gradient = gradient_program(f_h, precision)

    # run gradient program
    if qc is None:
        qc = get_qc(f"{len(p_gradient.get_qubits())}q-qvm")

    p_gradient.wrap_in_numshots_loop(n_measurements)
    executable = qc.compiler.native_quil_to_executable(p_gradient)
    measurements = qc.run(executable)

    # summarize measurements
    bf_estimate = perturbation_sign * measurements_to_bf(measurements)
    bf_explicit = '{0:.16f}'.format(bf_estimate)
    deci_estimate = binary_float_to_decimal_float(bf_explicit)

    # rescale gradient
    deci_estimate *= gradient_max

    return deci_estimate


text:
import { cloneDeep } from 'lodash';

import { LoadingState, VariableType } from '@grafana/data';

import { reducerTester } from '../../../../test/core/redux/reducerTester';
import { variableAdapters } from '../adapters';
import { createConstantVariableAdapter } from '../constant/adapter';
import { initialConstantVariableModelState } from '../constant/reducer';
import { ALL_VARIABLE_TEXT, ALL_VARIABLE_VALUE } from '../constants';
import { changeVariableNameSucceeded } from '../editor/reducer';
import { createQueryVariableAdapter } from '../query/adapter';
import { initialQueryVariableModelState } from '../query/reducer';
import { ConstantVariableModel, QueryVariableModel, VariableHide, VariableOption } from '../types';
import { toVariablePayload } from '../utils';

import { getVariableState, getVariableTestContext } from './helpers';
import {
  addVariable,
  changeVariableOrder,
  changeVariableProp,
  changeVariableType,
  duplicateVariable,
  removeVariable,
  setCurrentVariableValue,
  sharedReducer,
  variableStateCompleted,
  variableStateFailed,
  variableStateFetching,
  variableStateNotStarted,
} from './sharedReducer';
import { initialVariablesState, KeyedVariableIdentifier, VariablesState } from './types';

variableAdapters.setInit(() => [createQueryVariableAdapter(), createConstantVariableAdapter()]);

describe('sharedReducer', () => {
  describe('when addVariable is dispatched', () => {
    it('then state should be correct', () => {
      const model: any = {
        name: 'name from model',
        type: 'type from model',
        current: undefined,
      };

      const expected: QueryVariableModel = {
        ...initialQueryVariableModelState,
        id: 'name from model',
        global: true,
        index: 0,
        name: 'name from model',
        type: 'type from model' as unknown as VariableType,
        current: {} as unknown as VariableOption,
      };

      const payload = toVariablePayload({ id: 'name from model', type: 'query' }, { global: true, index: 0, model });

      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, { ...initialVariablesState })
        .whenActionIsDispatched(addVariable(payload))
        .thenStateShouldEqual({
          ['name from model']: expected,
        });
    });
  });

  describe('when addVariable is dispatched for a constant model', () => {
    it('then state should be correct', () => {
      const model: any = {
        name: 'constant',
        type: 'constant',
        query: 'a constant',
        current: { selected: true, text: 'A', value: 'A' },
        options: [{ selected: true, text: 'A', value: 'A' }],
      };

      const expected: ConstantVariableModel = {
        ...initialConstantVariableModelState,
        id: 'constant',
        global: true,
        index: 0,
        name: 'constant',
        type: 'constant',
        query: 'a constant',
        current: { selected: true, text: 'a constant', value: 'a constant' },
        options: [{ selected: true, text: 'a constant', value: 'a constant' }],
      };

      const payload = toVariablePayload({ id: 'constant', type: 'constant' }, { global: true, index: 0, model });

      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, { ...initialVariablesState })
        .whenActionIsDispatched(addVariable(payload))
        .thenStateShouldEqual({
          ['constant']: expected,
        });
    });
  });

  describe('when removeVariable is dispatched and reIndex is true', () => {
    it('then state should be correct', () => {
      const initialState: VariablesState = getVariableState(3);
      const payload = toVariablePayload({ id: '1', type: 'query' }, { reIndex: true });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, initialState)
        .whenActionIsDispatched(removeVariable(payload))
        .thenStateShouldEqual({
          '0': {
            id: '0',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-0',
            hide: VariableHide.dontHide,
            index: 0,
            label: 'Label-0',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
          '2': {
            id: '2',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-2',
            hide: VariableHide.dontHide,
            index: 1,
            label: 'Label-2',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
        });
    });
  });

  describe('when removeVariable is dispatched and reIndex is false', () => {
    it('then state should be correct', () => {
      const initialState: VariablesState = getVariableState(3);
      const payload = toVariablePayload({ id: '1', type: 'query' }, { reIndex: false });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, initialState)
        .whenActionIsDispatched(removeVariable(payload))
        .thenStateShouldEqual({
          '0': {
            id: '0',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-0',
            hide: VariableHide.dontHide,
            index: 0,
            label: 'Label-0',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
          '2': {
            id: '2',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-2',
            hide: VariableHide.dontHide,
            index: 2,
            label: 'Label-2',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
        });
    });
  });

  describe('when duplicateVariable is dispatched', () => {
    it('then state should be correct', () => {
      const initialState: VariablesState = getVariableState(3, -1, false, true);
      const payload = toVariablePayload({ id: '1', type: 'query' }, { newId: '11' });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, initialState)
        .whenActionIsDispatched(duplicateVariable(payload))
        .thenStateShouldEqual({
          ...initialState,
          '0': {
            id: '0',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-0',
            hide: VariableHide.dontHide,
            index: 0,
            label: 'Label-0',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
          '1': {
            id: '1',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-1',
            hide: VariableHide.dontHide,
            index: 1,
            label: 'Label-1',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
          '2': {
            id: '2',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-2',
            hide: VariableHide.dontHide,
            index: 2,
            label: 'Label-2',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
          '11': {
            ...initialQueryVariableModelState,
            id: '11',
            rootStateKey: 'key',
            name: 'copy_of_Name-1',
            index: 3,
            label: 'Label-1',
          },
        });
    });
  });

  describe('when changeVariableOrder is dispatched', () => {
    it('then state should be correct', () => {
      const initialState: VariablesState = getVariableState(3);
      const payload = toVariablePayload({ id: '2', type: 'query' }, { fromIndex: 2, toIndex: 0 });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, initialState)
        .whenActionIsDispatched(changeVariableOrder(payload))
        .thenStateShouldEqual({
          '0': {
            id: '0',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-0',
            hide: VariableHide.dontHide,
            index: 1,
            label: 'Label-0',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
          '1': {
            id: '1',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-1',
            hide: VariableHide.dontHide,
            index: 2,
            label: 'Label-1',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
          '2': {
            id: '2',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-2',
            hide: VariableHide.dontHide,
            index: 0,
            label: 'Label-2',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
        });
    });

    it('then state should be correct', () => {
      const initialState: VariablesState = getVariableState(3);
      const payload = toVariablePayload({ id: '0', type: 'query' }, { fromIndex: 0, toIndex: 2 });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, initialState)
        .whenActionIsDispatched(changeVariableOrder(payload))
        .thenStateShouldEqual({
          '0': {
            id: '0',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-0',
            hide: VariableHide.dontHide,
            index: 2,
            label: 'Label-0',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
          '1': {
            id: '1',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-1',
            hide: VariableHide.dontHide,
            index: 0,
            label: 'Label-1',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
          '2': {
            id: '2',
            rootStateKey: 'key',
            type: 'query',
            name: 'Name-2',
            hide: VariableHide.dontHide,
            index: 1,
            label: 'Label-2',
            skipUrlSync: false,
            global: false,
            state: LoadingState.NotStarted,
            error: null,
            description: null,
          },
        });
    });
  });

  describe('when setCurrentVariableValue is dispatched and current.text is an Array with values', () => {
    it('then state should be correct', () => {
      const adapter = createQueryVariableAdapter();
      const { initialState } = getVariableTestContext(adapter, {
        options: [
          { text: 'All', value: '$__all', selected: false },
          { text: 'A', value: 'A', selected: false },
          { text: 'B', value: 'B', selected: false },
        ],
      });
      const current = { text: ['A', 'B'], selected: true, value: ['A', 'B'] };
      const payload = toVariablePayload({ id: '0', type: 'query' }, { option: current });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, cloneDeep(initialState))
        .whenActionIsDispatched(setCurrentVariableValue(payload))
        .thenStateShouldEqual({
          ...initialState,
          '0': {
            ...initialState[0],
            options: [
              { selected: false, text: 'All', value: '$__all' },
              { selected: true, text: 'A', value: 'A' },
              { selected: true, text: 'B', value: 'B' },
            ],
            current: { selected: true, text: ['A', 'B'], value: ['A', 'B'] },
          } as unknown as QueryVariableModel,
        });
    });
  });

  describe('when setCurrentVariableValue is dispatched and current.value is an Array with values except All value', () => {
    it('then state should be correct', () => {
      const adapter = createQueryVariableAdapter();
      const { initialState } = getVariableTestContext(adapter, {
        options: [
          { text: 'All', value: '$__all', selected: false },
          { text: 'A', value: 'A', selected: false },
          { text: 'B', value: 'B', selected: false },
        ],
      });
      const current = { text: 'A + B', selected: true, value: ['A', 'B'] };
      const payload = toVariablePayload({ id: '0', type: 'query' }, { option: current });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, cloneDeep(initialState))
        .whenActionIsDispatched(setCurrentVariableValue(payload))
        .thenStateShouldEqual({
          ...initialState,
          '0': {
            ...initialState[0],
            options: [
              { selected: false, text: 'All', value: '$__all' },
              { selected: true, text: 'A', value: 'A' },
              { selected: true, text: 'B', value: 'B' },
            ],
            current: { selected: true, text: 'A + B', value: ['A', 'B'] },
          } as unknown as QueryVariableModel,
        });
    });
  });

  describe('when setCurrentVariableValue is dispatched and current.value is an Array with values containing All value', () => {
    it('then state should be correct', () => {
      const adapter = createQueryVariableAdapter();
      const { initialState } = getVariableTestContext(adapter, {
        options: [
          { text: 'All', value: '$__all', selected: false },
          { text: 'A', value: 'A', selected: false },
          { text: 'B', value: 'B', selected: false },
        ],
      });
      const current = { text: ALL_VARIABLE_TEXT, selected: true, value: [ALL_VARIABLE_VALUE] };
      const payload = toVariablePayload({ id: '0', type: 'query' }, { option: current });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, cloneDeep(initialState))
        .whenActionIsDispatched(setCurrentVariableValue(payload))
        .thenStateShouldEqual({
          ...initialState,
          '0': {
            ...initialState[0],
            options: [
              { selected: true, text: 'All', value: '$__all' },
              { selected: false, text: 'A', value: 'A' },
              { selected: false, text: 'B', value: 'B' },
            ],
            current: { selected: true, text: 'All', value: ['$__all'] },
          } as unknown as QueryVariableModel,
        });
    });
  });

  describe('when variableStateNotStarted is dispatched', () => {
    it('then state should be correct', () => {
      const adapter = createQueryVariableAdapter();
      const { initialState } = getVariableTestContext(adapter, {
        state: LoadingState.Done,
        error: 'Some error',
      });
      const payload = toVariablePayload({ id: '0', type: 'query' });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, cloneDeep(initialState))
        .whenActionIsDispatched(variableStateNotStarted(payload))
        .thenStateShouldEqual({
          ...initialState,
          '0': {
            ...initialState[0],
            state: LoadingState.NotStarted,
            error: null,
          } as unknown as QueryVariableModel,
        });
    });
  });

  describe('when variableStateFetching is dispatched', () => {
    it('then state should be correct', () => {
      const adapter = createQueryVariableAdapter();
      const { initialState } = getVariableTestContext(adapter, {
        state: LoadingState.Done,
        error: 'Some error',
      });
      const payload = toVariablePayload({ id: '0', type: 'query' });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, cloneDeep(initialState))
        .whenActionIsDispatched(variableStateFetching(payload))
        .thenStateShouldEqual({
          ...initialState,
          '0': {
            ...initialState[0],
            state: LoadingState.Loading,
            error: null,
          } as unknown as QueryVariableModel,
        });
    });
  });

  describe('when variableStateCompleted is dispatched', () => {
    it('then state should be correct', () => {
      const adapter = createQueryVariableAdapter();
      const { initialState } = getVariableTestContext(adapter, {
        state: LoadingState.Loading,
        error: 'Some error',
      });
      const payload = toVariablePayload({ id: '0', type: 'query' });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, cloneDeep(initialState))
        .whenActionIsDispatched(variableStateCompleted(payload))
        .thenStateShouldEqual({
          ...initialState,
          '0': {
            ...initialState[0],
            state: LoadingState.Done,
            error: null,
          } as unknown as QueryVariableModel,
        });
    });
  });

  describe('when variableStateFailed is dispatched', () => {
    it('then state should be correct', () => {
      const adapter = createQueryVariableAdapter();
      const { initialState } = getVariableTestContext(adapter, { state: LoadingState.Loading });
      const payload = toVariablePayload({ id: '0', type: 'query' }, { error: 'Some error' });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, cloneDeep(initialState))
        .whenActionIsDispatched(variableStateFailed(payload))
        .thenStateShouldEqual({
          ...initialState,
          '0': {
            ...initialState[0],
            state: LoadingState.Error,
            error: 'Some error',
          } as unknown as QueryVariableModel,
        });
    });
  });

  describe('when changeVariableProp is dispatched', () => {
    it('then state should be correct', () => {
      const adapter = createQueryVariableAdapter();
      const { initialState } = getVariableTestContext(adapter);
      const propName = 'label';
      const propValue = 'Updated label';
      const payload = toVariablePayload({ id: '0', type: 'query' }, { propName, propValue });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, cloneDeep(initialState))
        .whenActionIsDispatched(changeVariableProp(payload))
        .thenStateShouldEqual({
          ...initialState,
          '0': {
            ...initialState[0],
            label: 'Updated label',
          },
        });
    });
  });

  describe('when changeVariableNameSucceeded is dispatched', () => {
    it('then state should be correct', () => {
      const adapter = createQueryVariableAdapter();
      const { initialState } = getVariableTestContext(adapter);
      const newName = 'A new name';
      const payload = toVariablePayload({ id: '0', type: 'query' }, { newName });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, cloneDeep(initialState))
        .whenActionIsDispatched(changeVariableNameSucceeded(payload))
        .thenStateShouldEqual({
          ...initialState,
          '0': {
            ...initialState[0],
            name: 'A new name',
          },
        });
    });
  });

  describe('when changeVariableType is dispatched', () => {
    it('then state should be correct', () => {
      const queryAdapter = createQueryVariableAdapter();
      const { initialState: queryAdapterState } = getVariableTestContext(queryAdapter);
      const constantAdapter = createConstantVariableAdapter();
      const { initialState: constantAdapterState } = getVariableTestContext(constantAdapter);
      const newType = 'constant' as VariableType;
      const identifier: KeyedVariableIdentifier = { id: '0', type: 'query', rootStateKey: 'key' };
      const payload = toVariablePayload(identifier, { newType });
      reducerTester<VariablesState>()
        .givenReducer(sharedReducer, cloneDeep(queryAdapterState))
        .whenActionIsDispatched(changeVariableNameSucceeded(toVariablePayload(identifier, { newName: 'test' })))
        .whenActionIsDispatched(
          changeVariableProp(toVariablePayload(identifier, { propName: 'description', propValue: 'new description' }))
        )
        .whenActionIsDispatched(
          changeVariableProp(toVariablePayload(identifier, { propName: 'label', propValue: 'new label' }))
        )
        .whenActionIsDispatched(changeVariableType(payload))
        .thenStateShouldEqual({
          ...constantAdapterState,
          '0': {
            ...constantAdapterState[0],
            rootStateKey: 'key',
            name: 'test',
            description: 'new description',
            label: 'new label',
            type: 'constant',
          },
        });
    });
  });
});


text:
using System.ComponentModel;
using System.IO;
using System.Xml.Serialization;

namespace EasyLOB.Library
{
    public static class BindingListExtensions
    {
        /// <summary>
        /// Read BindingList from XML.
        /// </summary>
        /// <param name="list">List</param>
        /// <param name="xml">XML</param>
        public static object FromXml<T>(this BindingList<T> list, string xml)
        {
            var serializer = new XmlSerializer(list.GetType());
            MemoryStream stream = new MemoryStream(xml.ToBinary());

            return serializer.Deserialize(stream);
        }

        /// <summary>
        /// Write BindingList to XML.
        /// </summary>
        /// <param name="list">Binding List</param>
        /// <returns>XML</returns>
        public static string ToXml<T>(this BindingList<T> list)
        {
            var serializer = new XmlSerializer(list.GetType());
            MemoryStream stream = new MemoryStream();
            serializer.Serialize(stream, list);

            return stream.ToString();
        }
    }
}


text:
package com.hubspot.singularity.runner.base.shared;

import java.util.Collections;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;
import com.hubspot.singularity.runner.base.config.MissingConfigException;
import com.hubspot.singularity.runner.base.sentry.SingularityRunnerExceptionNotifier;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

public class SingularityRunner {

  private static final Logger LOG = LoggerFactory.getLogger(SingularityDriver.class);

  @SuppressFBWarnings("DM_EXIT")
  public void run(Iterable<? extends Module> modules) {
    final Injector injector = Guice.createInjector(Stage.PRODUCTION, modules);

    final SingularityRunnerExceptionNotifier exceptionNotifier = injector.getInstance(SingularityRunnerExceptionNotifier.class);

    final SingularityDriver driver = injector.getInstance(SingularityDriver.class);

    Runtime.getRuntime().addShutdownHook(new Thread("SingularityRunnerGracefulShutdown") {

      @Override
      public void run() {
        driver.shutdown();
      }

    });

    try {
      driver.startAndWait();

      LOG.info("Exiting normally");

      System.exit(0);
    } catch (MissingConfigException mce) {
      LOG.error("Missing required configuration, exiting", mce);
      System.exit(1);
    } catch (Throwable t) {
      LOG.error("Caught unexpected exception, exiting", t);
      exceptionNotifier.notify(String.format("Unexpected exception in runner (%s)", t.getMessage()), t, Collections.<String, String>emptyMap());
      System.exit(1);
    }

  }
}


text:
package com.loginbox.app.acceptance.tests;

import com.loginbox.app.acceptance.framework.DslTestCase;
import org.junit.Test;

public class SetupTest extends DslTestCase {
    @Test
    public void landingPageRedirectsToSetup() {
        webUi.open();
        webUi.setupPage.ensureWelcomeShown();
    }

    @Test
    public void canSetupApp() {
        webUi.open();
        webUi.setupPage.enterUsername();
        webUi.setupPage.enterContactEmail();
        webUi.setupPage.enterPassword();
        webUi.setupPage.confirmPassword();
        webUi.setupPage.clickCompleteSetup();
        webUi.adminPage.ensureAdminShown();
    }

    @Test
    public void setupRequiresUsername() throws Exception {
        webUi.open();
        /* skip: webUi.setupPage.enterUsername(); */
        webUi.setupPage.enterContactEmail();
        webUi.setupPage.enterPassword();
        webUi.setupPage.confirmPassword();
        webUi.setupPage.clickCompleteSetup();
        webUi.errorPage.ensure("code: 400", "message: HTTP 400 Bad Request");
    }

    @Test
    public void setupRequiresContactEmail() throws Exception {
        webUi.open();
        webUi.setupPage.enterUsername();
        /* skip: webUi.setupPage.enterContactEmail(); */
        webUi.setupPage.enterPassword();
        webUi.setupPage.confirmPassword();
        webUi.setupPage.clickCompleteSetup();
        webUi.errorPage.ensure("code: 400", "message: HTTP 400 Bad Request");
    }

    @Test
    public void setupRequiresPassword() throws Exception {
        webUi.open();
        webUi.setupPage.enterUsername();
        webUi.setupPage.enterContactEmail();
        /* skip: webUi.setupPage.enterPassword(); */
        /* skip: webUi.setupPage.confirmPassword(); */
        webUi.setupPage.clickCompleteSetup();
        webUi.errorPage.ensure("code: 400", "message: HTTP 400 Bad Request");
    }

    @Test
    public void setupRequiresMatchingPasswords() throws Exception {
        webUi.open();
        webUi.setupPage.enterUsername();
        webUi.setupPage.enterContactEmail();
        webUi.setupPage.enterPassword("password-a");
        webUi.setupPage.confirmPassword("password-b");
        webUi.setupPage.clickCompleteSetup();
        webUi.errorPage.ensure("code: 400", "message: HTTP 400 Bad Request");
    }

    @Test
    public void normalUiAfterSetupCompleted() {
        webUi.open();
        webUi.setupApp();
        webUi.close();

        webUi.open();
        webUi.landingPage.ensureLandingPageShown();
    }
}


text:
package funpep.server
package util

private[util] trait Types {

  // type Email = javax.mail.internet.InternetAddress

}


text:
/*****************************************************************************\
*              efs - General purpose Embedded Filesystem library              *
*          ---------------------------------------------------------          *
*                                                                             *
* Filename :  linuxfile.h                                                     *
* Description : Headerfile for linuxfile.c                                    *
*                                                                             *
* This program is free software; you can redistribute it and/or               *
* modify it under the terms of the GNU General Public License                 *
* as published by the Free Software Foundation; version 2                     *
* of the License.                                                             *
                                                                              *
* This program is distributed in the hope that it will be useful,             *
* but WITHOUT ANY WARRANTY; without even the implied warranty of              *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               *
* GNU General Public License for more details.                                *
*                                                                             *
* As a special exception, if other files instantiate templates or             *
* use macros or inline functions from this file, or you compile this          *
* file and link it with other works to produce a work based on this file,     *
* this file does not by itself cause the resulting work to be covered         *
* by the GNU General Public License. However the source code for this         *
* file must still be made available in accordance with section (3) of         *
* the GNU General Public License.                                             *
*                                                                             *
* This exception does not invalidate any other reasons why a work based       *
* on this file might be covered by the GNU General Public License.            *
*                                                                             *
*                                                    (c)2006 Lennart Yseboodt *
*                                                    (c)2006 Michael De Nil   *
\*****************************************************************************/

#ifndef __LINUXFILE_H__
#define __LINUXFILE_H__

/*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "helper.h"
#include "../debug.h"
#include "../types.h"
#include "config.h"
/*****************************************************************************/

#define _LARGEFILE_SOURCE
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64

/*************************************************************\
              hwInterface
               ----------
* FILE* 	imagefile		File emulation of hw interface.
* long		sectorCount		Number of sectors on the file.
\*************************************************************/
struct hwInterface{
	FILE 	*imageFile;
	eint32 	sectorCount;
	euint32 readCount,writeCount;
};
typedef struct hwInterface hwInterface;

esint8 if_initInterface(hwInterface* file,eint8* fileName);
esint8 if_readBuf(hwInterface* file,euint32 address,euint8* buf);
esint8 if_writeBuf(hwInterface* file,euint32 address,euint8* buf);
esint8 if_setPos(hwInterface* file,euint32 address);

#endif


text:
namespace CGAL
{
namespace Mesh_2
{
  template<typename CDT,
           typename SizingField
           = Uniform_sizing_field_2<typename CDT::Geom_traits> >
  class Lloyd_move_2
  {
    typedef typename CDT::Vertex_handle          Vertex_handle;
    typedef typename CDT::Geom_traits::Point_2   Point_2;
    typedef typename CDT::Geom_traits::Segment_2  Segment;
    typedef typename CDT::Geom_traits::Triangle_2 Triangle;
    typedef typename CDT::Geom_traits::FT         FT;
    typedef typename CDT::Geom_traits::Vector_2   Vector_2;

    typedef typename CGAL::Constrained_voronoi_diagram_2<CDT> CVD;
    typedef typename CVD::Cvd_cell               Cvd_cell;

  public:
    typedef SizingField Sizing_field;

  public:
    Vector_2 operator()(Vertex_handle v,
          const CDT& cdt,
          const Sizing_field& sizing_field = Sizing_field()) const
    {
      if(cdt.are_there_incident_constraints(v))
        return CGAL::NULL_VECTOR;

      Point_2 p = v->point();
      Vector_2 move = CGAL::NULL_VECTOR;
      FT sum_masses(0);

      Cvd_cell cell = CGAL::dual(cdt, v);
      if(cell.is_infinite() || cell.is_empty())
        return CGAL::NULL_VECTOR; //center of mass is at infinity!

      CGAL_assertion(cell.number_of_vertices() > 2);

      typename Cvd_cell::segment_iterator sit = cell.segments_begin();
      typename CDT::Geom_traits::Compute_area_2 compute_area =
        cdt.geom_traits().compute_area_2_object();
      for( ; sit != cell.segments_end(); ++sit)
      {
        Segment s = *sit;
        Triangle tri(p, s.source(), s.target());
        Point_2 tri_centroid = CGAL::centroid(tri);

        // Compute mass
        FT density = density_2d(tri_centroid, sizing_field);
        FT abs_area = CGAL::abs(compute_area(tri[0], tri[1], tri[2]));
        FT mass = abs_area * density;

        move = move + mass * Vector_2(p, tri_centroid);
        sum_masses += mass;
      }

      CGAL_assertion(sum_masses != 0.0);
      return move / sum_masses;
    }

  private:
    FT density_2d(const Point_2& p,
                  const Sizing_field& sizing_field) const
    {
      FT s = sizing_field(p);
      CGAL_assertion( s > 0. );

      // 1 / s^(d+2)
      return ( 1/(s*s*s*s) );
    }

#ifdef CGAL_MESH_2_OPTIMIZER_VERBOSE
  public:
    static std::string name() { return std::string("Lloyd"); }
#endif

  };

} //end namespace Mesh_2
} //end namespace CGAL

#endif //CGAL_LLOYD_MOVE_2_H