use serde::{Deserialize, Serialize};
use std::{error, fmt, io, sync::Arc};
pub struct ResultExpand<T, E>(pub Result<T, E>);
impl<T, E> IntoIterator for ResultExpand<T, E>
where
T: IntoIterator,
{
type Item = Result<T::Item, E>;
type IntoIter = ResultExpandIter<T::IntoIter, E>;
fn into_iter(self) -> Self::IntoIter {
ResultExpandIter(self.0.map(IntoIterator::into_iter).map_err(Some))
}
}
pub struct ResultExpandIter<T, E>(Result<T, Option<E>>);
impl<T, E> Iterator for ResultExpandIter<T, E>
where
T: Iterator,
{
type Item = Result<T::Item, E>;
fn next(&mut self) -> Option<Self::Item> {
transpose(self.0.as_mut().map(Iterator::next).map_err(Option::take))
}
}
fn transpose<T, E>(result: Result<Option<T>, Option<E>>) -> Option<Result<T, E>> {
match result {
Ok(Some(x)) => Some(Ok(x)),
Err(Some(e)) => Some(Err(e)),
Ok(None) | Err(None) => None,
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(transparent)]
pub struct IoError(#[serde(with = "crate::misc_serde")] Arc<io::Error>);
impl PartialEq for IoError {
fn eq(&self, other: &Self) -> bool {
self.0.to_string() == other.0.to_string()
}
}
impl error::Error for IoError {}
impl fmt::Display for IoError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl fmt::Debug for IoError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl From<io::Error> for IoError {
fn from(err: io::Error) -> Self {
Self(Arc::new(err))
}
}
impl From<IoError> for io::Error {
fn from(err: IoError) -> Self {
Arc::try_unwrap(err.0).unwrap()
}
}