#![doc(html_root_url = "https://docs.rs/toad-async/0.0.0")]
#![cfg_attr(any(docsrs, feature = "docs"), feature(doc_cfg))]
#![allow(clippy::unused_unit)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![deny(missing_copy_implementations)]
#![cfg_attr(not(test), deny(unsafe_code))]
#![cfg_attr(not(test), warn(unreachable_pub))]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "alloc")]
extern crate alloc as std_alloc;
pub mod nb {
pub use crate::{Error, Result};
}
pub type Result<T, E> = core::result::Result<T, Error<E>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Error<E> {
WouldBlock,
Other(E),
}
impl<E> Error<E> {
pub fn map<F, R>(self, mut f: F) -> Error<R>
where F: FnMut(E) -> R
{
match self {
| Error::Other(e) => Error::Other(f(e)),
| Error::WouldBlock => Error::WouldBlock,
}
}
}
pub fn block<T, E, F>(f: F) -> core::result::Result<T, E>
where F: Fn() -> Result<T, E>
{
loop {
match f() {
| Ok(ok) => break Ok(ok),
| Err(Error::Other(e)) => break Err(e),
| Err(Error::WouldBlock) => {
#[cfg(feature = "std")]
std::thread::sleep(std::time::Duration::from_nanos(500));
continue;
},
}
}
}
pub trait AsyncResult<T, E>
where Self: Sized
{
fn async_map_err<F, R>(self, f: F) -> Result<T, R>
where F: FnMut(E) -> R;
}
impl<T, E> AsyncResult<T, E> for Result<T, E> {
fn async_map_err<F, R>(self, mut f: F) -> Result<T, R>
where F: FnMut(E) -> R
{
self.map_err(|e| match e {
| Error::WouldBlock => Error::WouldBlock,
| Error::Other(e) => Error::Other(f(e)),
})
}
}
pub trait AsyncPollable<T, E> {
fn block(self) -> core::result::Result<T, E>;
}
impl<F, T, E> AsyncPollable<T, E> for F where F: Fn() -> Result<T, E>
{
fn block(self) -> core::result::Result<T, E> {
crate::block(self)
}
}