#![allow(unused_imports)]

use std::os::fd::IntoRawFd;
use cfg_if::cfg_if;
use crate::prelude::*;

/// Version of [`nix::sys::uio::writev`] with a fixed type for the fd
//
///  * nix <=0.26 has `fd: c_int`
///  * nix >=0.27 has `fd: impl AsFd`
pub unsafe fn writev(fd: c_int, iov: &[IoSlice]) -> nix::Result<usize> {
  nix::sys::uio::writev(
    { cfg_if! {
      if #[cfg(nix_ge_0_27)] {
        BorrowedFd::borrow_raw(fd)
      } else {
        fd
      }
    }},
    iov,
  )
}

/// Version of [`nix::unistd::write`] with a fixed type for the fd
//
///  * nix <=0.27 has `fd: c_int`
///  * nix >=0.28 has `fd: impl AsFd`
pub unsafe fn write(fd: c_int, buf: &[u8]) -> nix::Result<usize> {
  nix::unistd::write(
    { cfg_if! {
      if #[cfg(nix_ge_0_28)] {
        BorrowedFd::borrow_raw(fd)
      } else {
        fd
      }
    }},
    buf,
  )
}

/// Version of [`nix::unistd::pipe`] with a fixed type for the fd
//
///  * nix <=0.27 returns a pair of `c_int`
///  * nix >=0.28 returns a pair of `OwnedFd`
pub fn pipe() -> nix::Result<(c_int, c_int)> {
  let (a, b) = nix::unistd::pipe()?;
  let map = |fd| { cfg_if! {
    if #[cfg(nix_ge_0_28)] {
      OwnedFd::into_raw_fd(fd)
    } else {
      fd
    }
  }};
  Ok((map(a), map(b)))
}

#[allow(deprecated)]
pub fn nix_last_errno() -> nix::errno::Errno {
  use nix::errno::*;
  from_i32(errno())
}
