#![deny(missing_docs, warnings, clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]
#![doc(test(attr(deny(warnings))))]
//! Reimplementation of the private `std::sys::cvt()`, but as a trait method.
//!
//! ### Example
//! ```
//! use cvt_trait::prelude::*;
//! # use std::os::raw::c_int;
//! # #[cfg(unix)]
//! # unsafe fn os_api() -> c_int {
//! #     0
//! # }
//! # #[cfg(windows)]
//! # unsafe fn os_api() -> c_int {
//! #    1
//! # }
//! unsafe { os_api() }.cvt().expect("OS API failed");
//! ```

use sealed::Sealed;
use std::io;

mod unix;
mod windows;

mod sealed {
    pub trait Sealed {
        type Output;
    }
}

/// The main trait in this crate.
pub trait Cvt: Sealed {
    /// Converts the "numeric" result returned by the native operating system's C
    /// API to [`io::Result`].
    fn cvt(self) -> io::Result<Self::Output>;
}

/// The trait for [NT APIs](https://docs.microsoft.com/en-us/sysinternals/resources/inside-native-applications#introduction).
///
/// ### Example (Windows-only)
#[cfg_attr(windows, doc = "```")]
#[cfg_attr(not(windows), doc = "```compile_fail")]
/// use cvt_trait::prelude::*;
/// # use std::os::raw::c_int;
/// # #[allow(non_snake_case)]
/// # unsafe fn NtDoSomething() -> c_int {
/// #     0
/// # }
/// unsafe { NtDoSomething() }.nt_cvt().expect("NT API failed");
/// ```
pub trait NtCvt: Sealed {
    /// Converts the "numeric" result returned by the NT API to [`io::Result`].
    fn nt_cvt(self) -> io::Result<Self::Output>;
}

/// The trait for [Winsock 2 APIs](https://docs.microsoft.com/windows/win32/winsock/windows-sockets-start-page-2).
///
/// ### Example (Windows-only)
#[cfg_attr(windows, doc = "```")]
#[cfg_attr(not(windows), doc = "```compile_fail")]
/// use cvt_trait::prelude::*;
/// # use std::os::raw::c_int;
/// # #[allow(non_snake_case)]
/// # unsafe fn WSADoSomething() -> c_int {
/// #     0
/// # }
/// unsafe { WSADoSomething() }.wsa_cvt().expect("Winsock API failed");
/// ```
pub trait WSACvt: Sealed {
    /// Converts the "numeric" result returned by the Winsock 2 API to
    /// [`io::Result`].
    fn wsa_cvt(self) -> io::Result<Self::Output>;
}

/// The prelude.
/// ```
/// # #[allow(unused_imports)]
/// use cvt_trait::prelude::*;
/// ```
pub mod prelude {
    pub use crate::{Cvt as _, NtCvt as _, WSACvt as _};
}
