#![doc = include_str!("../README.md")]
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, allow(unused_attributes))]
#[cfg(any(test, feature = "std"))]
extern crate std;
#[cfg(feature = "serde")]
pub mod serde_untagged;
#[cfg(feature = "serde")]
pub mod serde_untagged_optional;
#[cfg(feature = "either")]
mod either_impl;
#[cfg(feature = "either")]
#[cfg_attr(docsrs, doc(cfg(feature = "either")))]
pub use either_impl::*;
#[cfg(all(feature = "futures-io", feature = "std"))]
mod futures_impl;
#[cfg(feature = "tokio")]
mod tokio_impl;
mod result_ext;
pub use result_ext::*;
use core::{
convert::{AsMut, AsRef, TryInto},
fmt,
future::Future,
ops::{Deref, DerefMut},
pin::Pin,
};
#[cfg(any(test, feature = "std"))]
use std::error::Error;
#[cfg(any(test, feature = "std"))]
use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
pub use crate::Among::{Left, Middle, Right};
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Among<L, M, R> {
Left(L),
Middle(M),
Right(R),
}
#[macro_export]
macro_rules! for_all {
($value:expr, $pattern:pat => $result:expr) => {
match $value {
$crate::Among::Middle($pattern) => $result,
$crate::Among::Left($pattern) => $result,
$crate::Among::Right($pattern) => $result,
}
};
}
macro_rules! map_among {
($value:expr, $pattern:pat => $result:expr) => {
match $value {
Left($pattern) => Left($result),
Middle($pattern) => Middle($result),
Right($pattern) => Right($result),
}
};
}
mod iterator;
pub use self::iterator::IterAmong;
mod into_among;
pub use self::into_among::IntoAmong;
impl<L: Clone, M: Clone, R: Clone> Clone for Among<L, M, R> {
fn clone(&self) -> Self {
match self {
Left(inner) => Left(inner.clone()),
Middle(inner) => Middle(inner.clone()),
Right(inner) => Right(inner.clone()),
}
}
fn clone_from(&mut self, source: &Self) {
match (self, source) {
(Left(dest), Left(source)) => dest.clone_from(source),
(Middle(dest), Middle(source)) => dest.clone_from(source),
(Right(dest), Right(source)) => dest.clone_from(source),
(dest, source) => *dest = source.clone(),
}
}
}
impl<L, M, R> Among<L, M, R> {
pub const fn is_left(&self) -> bool {
matches!(*self, Left(_))
}
pub const fn is_right(&self) -> bool {
matches!(*self, Right(_))
}
pub const fn is_middle(&self) -> bool {
matches!(*self, Middle(_))
}
pub fn is_left_and<F>(&self, f: F) -> bool
where
F: FnOnce(&L) -> bool,
{
match self {
Left(l) => f(l),
_ => false,
}
}
pub fn is_middle_and<F>(&self, f: F) -> bool
where
F: FnOnce(&M) -> bool,
{
match self {
Middle(m) => f(m),
_ => false,
}
}
pub fn is_right_and<F>(&self, f: F) -> bool
where
F: FnOnce(&R) -> bool,
{
match self {
Right(r) => f(r),
_ => false,
}
}
pub const fn left_ref(&self) -> Option<&L> {
match self {
Left(l) => Some(l),
_ => None,
}
}
pub const fn middle_ref(&self) -> Option<&M> {
match self {
Middle(m) => Some(m),
_ => None,
}
}
pub const fn right_ref(&self) -> Option<&R> {
match self {
Right(r) => Some(r),
_ => None,
}
}
pub const fn left_mut(&mut self) -> Option<&mut L> {
match self {
Left(l) => Some(l),
_ => None,
}
}
pub const fn middle_mut(&mut self) -> Option<&mut M> {
match self {
Middle(m) => Some(m),
_ => None,
}
}
pub const fn right_mut(&mut self) -> Option<&mut R> {
match self {
Right(r) => Some(r),
_ => None,
}
}
pub fn left(self) -> Option<L> {
match self {
Left(l) => Some(l),
_ => None,
}
}
pub fn middle(self) -> Option<M> {
match self {
Middle(m) => Some(m),
_ => None,
}
}
pub fn right(self) -> Option<R> {
match self {
Right(r) => Some(r),
_ => None,
}
}
pub const fn as_ref(&self) -> Among<&L, &M, &R> {
match *self {
Left(ref inner) => Left(inner),
Middle(ref inner) => Middle(inner),
Right(ref inner) => Right(inner),
}
}
pub const fn as_mut(&mut self) -> Among<&mut L, &mut M, &mut R> {
match *self {
Left(ref mut inner) => Left(inner),
Middle(ref mut inner) => Middle(inner),
Right(ref mut inner) => Right(inner),
}
}
pub const fn as_pin_ref(self: Pin<&Self>) -> Among<Pin<&L>, Pin<&M>, Pin<&R>> {
unsafe {
match *Pin::get_ref(self) {
Left(ref inner) => Left(Pin::new_unchecked(inner)),
Middle(ref inner) => Middle(Pin::new_unchecked(inner)),
Right(ref inner) => Right(Pin::new_unchecked(inner)),
}
}
}
pub const fn as_pin_mut(self: Pin<&mut Self>) -> Among<Pin<&mut L>, Pin<&mut M>, Pin<&mut R>> {
unsafe {
match *Pin::get_unchecked_mut(self) {
Left(ref mut inner) => Left(Pin::new_unchecked(inner)),
Middle(ref mut inner) => Middle(Pin::new_unchecked(inner)),
Right(ref mut inner) => Right(Pin::new_unchecked(inner)),
}
}
}
pub fn flip(self) -> Among<R, M, L> {
match self {
Left(l) => Right(l),
Right(r) => Left(r),
Middle(m) => Middle(m),
}
}
pub fn flip_left_middle(self) -> Among<M, L, R> {
match self {
Left(l) => Middle(l),
Right(r) => Right(r),
Middle(m) => Left(m),
}
}
pub fn flip_middle_right(self) -> Among<L, R, M> {
match self {
Left(l) => Left(l),
Right(r) => Middle(r),
Middle(m) => Right(m),
}
}
pub fn map_left<F, N>(self, f: F) -> Among<N, M, R>
where
F: FnOnce(L) -> N,
{
match self {
Left(l) => Left(f(l)),
Middle(m) => Middle(m),
Right(r) => Right(r),
}
}
pub fn map_middle<F, N>(self, f: F) -> Among<L, N, R>
where
F: FnOnce(M) -> N,
{
match self {
Left(l) => Left(l),
Middle(m) => Middle(f(m)),
Right(r) => Right(r),
}
}
pub fn map_right<F, S>(self, f: F) -> Among<L, M, S>
where
F: FnOnce(R) -> S,
{
match self {
Left(l) => Left(l),
Middle(m) => Middle(m),
Right(r) => Right(f(r)),
}
}
pub fn inspect_left<F>(self, f: F) -> Self
where
F: FnOnce(&L),
{
if let Left(ref l) = self {
f(l);
}
self
}
pub fn inspect_middle<F>(self, f: F) -> Self
where
F: FnOnce(&M),
{
if let Middle(ref m) = self {
f(m);
}
self
}
pub fn inspect_right<F>(self, f: F) -> Self
where
F: FnOnce(&R),
{
if let Right(ref r) = self {
f(r);
}
self
}
pub fn map_among<F, G, H, S, T, U>(self, f: F, g: G, h: H) -> Among<S, T, U>
where
F: FnOnce(L) -> S,
G: FnOnce(M) -> T,
H: FnOnce(R) -> U,
{
match self {
Left(l) => Left(f(l)),
Middle(m) => Middle(g(m)),
Right(r) => Right(h(r)),
}
}
pub fn map_among_with<Ctx, F, G, H, S, T, U>(self, ctx: Ctx, f: F, g: G, h: H) -> Among<S, T, U>
where
F: FnOnce(Ctx, L) -> S,
G: FnOnce(Ctx, M) -> T,
H: FnOnce(Ctx, R) -> U,
{
match self {
Left(l) => Left(f(ctx, l)),
Middle(m) => Middle(g(ctx, m)),
Right(r) => Right(h(ctx, r)),
}
}
pub fn among<F, G, H, T>(self, f: F, g: G, h: H) -> T
where
F: FnOnce(L) -> T,
G: FnOnce(M) -> T,
H: FnOnce(R) -> T,
{
match self {
Left(l) => f(l),
Middle(m) => g(m),
Right(r) => h(r),
}
}
pub fn among_with<Ctx, F, G, H, T>(self, ctx: Ctx, f: F, g: G, h: H) -> T
where
F: FnOnce(Ctx, L) -> T,
G: FnOnce(Ctx, M) -> T,
H: FnOnce(Ctx, R) -> T,
{
match self {
Left(l) => f(ctx, l),
Middle(m) => g(ctx, m),
Right(r) => h(ctx, r),
}
}
pub fn left_and_then<F, S>(self, f: F) -> Among<S, M, R>
where
F: FnOnce(L) -> Among<S, M, R>,
{
match self {
Left(l) => f(l),
Middle(m) => Middle(m),
Right(r) => Right(r),
}
}
pub fn middle_and_then<F, S>(self, f: F) -> Among<L, S, R>
where
F: FnOnce(M) -> Among<L, S, R>,
{
match self {
Left(l) => Left(l),
Middle(m) => f(m),
Right(r) => Right(r),
}
}
pub fn right_and_then<F, S>(self, f: F) -> Among<L, M, S>
where
F: FnOnce(R) -> Among<L, M, S>,
{
match self {
Left(l) => Left(l),
Middle(m) => Middle(m),
Right(r) => f(r),
}
}
#[allow(clippy::should_implement_trait)]
pub fn into_iter(self) -> Among<L::IntoIter, M::IntoIter, R::IntoIter>
where
L: IntoIterator,
M: IntoIterator<Item = L::Item>,
R: IntoIterator<Item = L::Item>,
{
map_among!(self, inner => inner.into_iter())
}
pub fn iter(
&self,
) -> Among<
<&L as IntoIterator>::IntoIter,
<&M as IntoIterator>::IntoIter,
<&R as IntoIterator>::IntoIter,
>
where
for<'a> &'a L: IntoIterator,
for<'a> &'a M: IntoIterator<Item = <&'a L as IntoIterator>::Item>,
for<'a> &'a R: IntoIterator<Item = <&'a L as IntoIterator>::Item>,
{
map_among!(self, inner => inner.into_iter())
}
pub fn iter_mut(
&mut self,
) -> Among<
<&mut L as IntoIterator>::IntoIter,
<&mut M as IntoIterator>::IntoIter,
<&mut R as IntoIterator>::IntoIter,
>
where
for<'a> &'a mut L: IntoIterator,
for<'a> &'a mut M: IntoIterator<Item = <&'a mut L as IntoIterator>::Item>,
for<'a> &'a mut R: IntoIterator<Item = <&'a mut L as IntoIterator>::Item>,
{
map_among!(self, inner => inner.into_iter())
}
#[doc(alias = "transpose")]
pub fn factor_into_iter(self) -> IterAmong<L::IntoIter, M::IntoIter, R::IntoIter>
where
L: IntoIterator,
M: IntoIterator,
R: IntoIterator,
{
IterAmong::new(map_among!(self, inner => inner.into_iter()))
}
pub fn factor_iter(
&self,
) -> IterAmong<
<&L as IntoIterator>::IntoIter,
<&M as IntoIterator>::IntoIter,
<&R as IntoIterator>::IntoIter,
>
where
for<'a> &'a L: IntoIterator,
for<'a> &'a M: IntoIterator,
for<'a> &'a R: IntoIterator,
{
IterAmong::new(map_among!(self, inner => inner.into_iter()))
}
pub fn factor_iter_mut(
&mut self,
) -> IterAmong<
<&mut L as IntoIterator>::IntoIter,
<&mut M as IntoIterator>::IntoIter,
<&mut R as IntoIterator>::IntoIter,
>
where
for<'a> &'a mut L: IntoIterator,
for<'a> &'a mut M: IntoIterator,
for<'a> &'a mut R: IntoIterator,
{
IterAmong::new(map_among!(self, inner => inner.into_iter()))
}
pub fn left_or(self, other: L) -> L {
match self {
Among::Left(l) => l,
Among::Right(_) => other,
Among::Middle(_) => other,
}
}
pub fn left_or_default(self) -> L
where
L: Default,
{
match self {
Among::Left(l) => l,
Among::Right(_) => L::default(),
Among::Middle(_) => L::default(),
}
}
pub fn left_or_else<F, G>(self, f: F, g: G) -> L
where
F: FnOnce(R) -> L,
G: FnOnce(M) -> L,
{
match self {
Among::Left(l) => l,
Among::Right(r) => f(r),
Among::Middle(m) => g(m),
}
}
pub fn middle_or(self, other: M) -> M {
match self {
Among::Middle(m) => m,
_ => other,
}
}
pub fn middle_or_default(self) -> M
where
M: Default,
{
match self {
Among::Middle(m) => m,
_ => M::default(),
}
}
pub fn middle_or_else<F, G>(self, f: F, g: G) -> M
where
F: FnOnce(L) -> M,
G: FnOnce(R) -> M,
{
match self {
Among::Left(l) => f(l),
Among::Middle(m) => m,
Among::Right(r) => g(r),
}
}
pub fn right_or(self, other: R) -> R {
match self {
Among::Left(_) => other,
Among::Middle(_) => other,
Among::Right(r) => r,
}
}
pub fn right_or_default(self) -> R
where
R: Default,
{
match self {
Among::Left(_) => R::default(),
Among::Middle(_) => R::default(),
Among::Right(r) => r,
}
}
pub fn right_or_else<F, G>(self, f: F, g: G) -> R
where
F: FnOnce(L) -> R,
G: FnOnce(M) -> R,
{
match self {
Among::Left(l) => f(l),
Among::Middle(m) => g(m),
Among::Right(r) => r,
}
}
pub fn unwrap_left(self) -> L
where
M: core::fmt::Debug,
R: core::fmt::Debug,
{
match self {
Among::Left(l) => l,
Among::Middle(m) => {
panic!("called `Among::unwrap_left()` on a `Middle` value: {:?}", m)
}
Among::Right(r) => {
panic!("called `Among::unwrap_left()` on a `Right` value: {:?}", r)
}
}
}
pub fn unwrap_middle(self) -> M
where
L: core::fmt::Debug,
R: core::fmt::Debug,
{
match self {
Among::Left(l) => {
panic!("called `Among::unwrap_middle()` on a `Left` value: {:?}", l)
}
Among::Middle(m) => m,
Among::Right(r) => {
panic!(
"called `Among::unwrap_middle()` on a `Right` value: {:?}",
r
)
}
}
}
pub fn unwrap_right(self) -> R
where
L: core::fmt::Debug,
M: core::fmt::Debug,
{
match self {
Among::Right(r) => r,
Among::Middle(m) => {
panic!(
"called `Among::unwrap_right()` on a `Middle` value: {:?}",
m
)
}
Among::Left(l) => panic!("called `Among::unwrap_right()` on a `Left` value: {:?}", l),
}
}
pub fn expect_left(self, msg: &str) -> L
where
M: core::fmt::Debug,
R: core::fmt::Debug,
{
match self {
Among::Left(l) => l,
Among::Middle(m) => panic!("{}: {:?}", msg, m),
Among::Right(r) => panic!("{}: {:?}", msg, r),
}
}
pub fn expect_middle(self, msg: &str) -> M
where
L: core::fmt::Debug,
R: core::fmt::Debug,
{
match self {
Among::Left(l) => panic!("{}: {:?}", msg, l),
Among::Middle(m) => m,
Among::Right(r) => panic!("{}: {:?}", msg, r),
}
}
pub fn expect_right(self, msg: &str) -> R
where
L: core::fmt::Debug,
M: core::fmt::Debug,
{
match self {
Among::Right(r) => r,
Among::Middle(m) => panic!("{}: {:?}", msg, m),
Among::Left(l) => panic!("{}: {:?}", msg, l),
}
}
pub fn shift_right(self) -> Among<R, L, M> {
match self {
Among::Left(l) => Among::Middle(l),
Among::Middle(m) => Among::Right(m),
Among::Right(r) => Among::Left(r),
}
}
pub fn shift_left(self) -> Among<M, R, L> {
match self {
Among::Left(l) => Among::Right(l),
Among::Middle(m) => Among::Left(m),
Among::Right(r) => Among::Middle(r),
}
}
pub fn insert_left(&mut self, value: L) -> &mut L {
*self = Left(value);
match self {
Left(l) => l,
_ => unreachable!(),
}
}
pub fn insert_middle(&mut self, value: M) -> &mut M {
*self = Middle(value);
match self {
Middle(m) => m,
_ => unreachable!(),
}
}
pub fn insert_right(&mut self, value: R) -> &mut R {
*self = Right(value);
match self {
Right(r) => r,
_ => unreachable!(),
}
}
pub fn get_or_insert_left(&mut self, default: L) -> &mut L {
self.get_or_insert_left_with(|| default)
}
pub fn get_or_insert_middle(&mut self, default: M) -> &mut M {
self.get_or_insert_middle_with(|| default)
}
pub fn get_or_insert_right(&mut self, default: R) -> &mut R {
self.get_or_insert_right_with(|| default)
}
pub fn get_or_insert_left_with<F>(&mut self, f: F) -> &mut L
where
F: FnOnce() -> L,
{
if !self.is_left() {
*self = Left(f());
}
match self {
Left(l) => l,
_ => unreachable!(),
}
}
pub fn get_or_insert_middle_with<F>(&mut self, f: F) -> &mut M
where
F: FnOnce() -> M,
{
if !self.is_middle() {
*self = Middle(f());
}
match self {
Middle(m) => m,
_ => unreachable!(),
}
}
pub fn get_or_insert_right_with<F>(&mut self, f: F) -> &mut R
where
F: FnOnce() -> R,
{
if !self.is_right() {
*self = Right(f());
}
match self {
Right(r) => r,
_ => unreachable!(),
}
}
pub fn among_into<T>(self) -> T
where
L: Into<T>,
M: Into<T>,
R: Into<T>,
{
match self {
Among::Left(l) => l.into(),
Among::Middle(m) => m.into(),
Among::Right(r) => r.into(),
}
}
#[allow(clippy::type_complexity)]
pub fn try_among_into<T>(
self,
) -> Result<T, Among<<L as TryInto<T>>::Error, <M as TryInto<T>>::Error, <R as TryInto<T>>::Error>>
where
L: TryInto<T>,
M: TryInto<T>,
R: TryInto<T>,
{
match self {
Among::Left(l) => l.try_into().map_err(Among::Left),
Among::Middle(m) => m.try_into().map_err(Among::Middle),
Among::Right(r) => r.try_into().map_err(Among::Right),
}
}
}
impl<L, M, R> Among<Option<L>, Option<M>, Option<R>> {
pub fn factor_none(self) -> Option<Among<L, M, R>> {
match self {
Left(l) => l.map(Among::Left),
Middle(m) => m.map(Among::Middle),
Right(r) => r.map(Among::Right),
}
}
}
impl<L, M, R, E> Among<Result<L, E>, Result<M, E>, Result<R, E>> {
pub fn factor_err(self) -> Result<Among<L, M, R>, E> {
match self {
Left(l) => l.map(Among::Left),
Middle(m) => m.map(Among::Middle),
Right(r) => r.map(Among::Right),
}
}
}
impl<T, L, M, R> Among<Result<T, L>, Result<T, M>, Result<T, R>> {
pub fn factor_ok(self) -> Result<T, Among<L, M, R>> {
match self {
Left(l) => l.map_err(Among::Left),
Middle(m) => m.map_err(Among::Middle),
Right(r) => r.map_err(Among::Right),
}
}
}
impl<T, L, M, R> Among<(T, L), (T, M), (T, R)> {
pub fn factor_first(self) -> (T, Among<L, M, R>) {
match self {
Left((t, l)) => (t, Left(l)),
Middle((t, m)) => (t, Middle(m)),
Right((t, r)) => (t, Right(r)),
}
}
}
impl<T, L, M, R> Among<(L, T), (M, T), (R, T)> {
pub fn factor_second(self) -> (Among<L, M, R>, T) {
match self {
Left((l, t)) => (Left(l), t),
Middle((m, t)) => (Middle(m), t),
Right((r, t)) => (Right(r), t),
}
}
}
impl<T> Among<T, T, T> {
pub fn into_inner(self) -> T {
for_all!(self, inner => inner)
}
pub const fn as_inner(&self) -> &T {
for_all!(*self, ref inner => inner)
}
pub const fn as_inner_mut(&mut self) -> &mut T {
for_all!(*self, ref mut inner => inner)
}
pub fn map<F, M>(self, f: F) -> Among<M, M, M>
where
F: FnOnce(T) -> M,
{
match self {
Left(l) => Left(f(l)),
Middle(m) => Middle(f(m)),
Right(r) => Right(f(r)),
}
}
}
impl<L, M, R> Among<&L, &M, &R> {
pub fn cloned(self) -> Among<L, M, R>
where
L: Clone,
M: Clone,
R: Clone,
{
match self {
Self::Left(l) => Among::Left(l.clone()),
Self::Middle(m) => Among::Middle(m.clone()),
Self::Right(r) => Among::Right(r.clone()),
}
}
pub const fn copied(self) -> Among<L, M, R>
where
L: Copy,
M: Copy,
R: Copy,
{
match self {
Self::Left(l) => Among::Left(*l),
Self::Middle(m) => Among::Middle(*m),
Self::Right(r) => Among::Right(*r),
}
}
}
impl<L, M, R> Among<&mut L, &mut M, &mut R> {
pub fn cloned(self) -> Among<L, M, R>
where
L: Clone,
M: Clone,
R: Clone,
{
match self {
Self::Left(l) => Among::Left(l.clone()),
Self::Middle(m) => Among::Middle(m.clone()),
Self::Right(r) => Among::Right(r.clone()),
}
}
pub const fn copied(self) -> Among<L, M, R>
where
L: Copy,
M: Copy,
R: Copy,
{
match self {
Self::Left(l) => Among::Left(*l),
Self::Middle(m) => Among::Middle(*m),
Self::Right(r) => Among::Right(*r),
}
}
}
impl<L, M, R> Future for Among<L, M, R>
where
L: Future,
M: Future,
R: Future,
{
type Output = Among<L::Output, M::Output, R::Output>;
fn poll(
self: Pin<&mut Self>,
cx: &mut core::task::Context<'_>,
) -> core::task::Poll<Self::Output> {
match self.as_pin_mut() {
Left(l) => l.poll(cx).map(Left),
Middle(m) => m.poll(cx).map(Middle),
Right(r) => r.poll(cx).map(Right),
}
}
}
#[cfg(any(test, feature = "std"))]
impl<L, M, R> Read for Among<L, M, R>
where
L: Read,
M: Read,
R: Read,
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
for_all!(*self, ref mut inner => inner.read(buf))
}
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
for_all!(*self, ref mut inner => inner.read_exact(buf))
}
fn read_to_end(&mut self, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> {
for_all!(*self, ref mut inner => inner.read_to_end(buf))
}
fn read_to_string(&mut self, buf: &mut std::string::String) -> io::Result<usize> {
for_all!(*self, ref mut inner => inner.read_to_string(buf))
}
}
#[cfg(any(test, feature = "std"))]
impl<L, M, R> Seek for Among<L, M, R>
where
L: Seek,
M: Seek,
R: Seek,
{
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
for_all!(*self, ref mut inner => inner.seek(pos))
}
}
#[cfg(any(test, feature = "std"))]
impl<L, M, R> BufRead for Among<L, M, R>
where
L: BufRead,
M: BufRead,
R: BufRead,
{
fn fill_buf(&mut self) -> io::Result<&[u8]> {
for_all!(*self, ref mut inner => inner.fill_buf())
}
fn consume(&mut self, amt: usize) {
for_all!(*self, ref mut inner => inner.consume(amt))
}
fn read_until(&mut self, byte: u8, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> {
for_all!(*self, ref mut inner => inner.read_until(byte, buf))
}
fn read_line(&mut self, buf: &mut std::string::String) -> io::Result<usize> {
for_all!(*self, ref mut inner => inner.read_line(buf))
}
}
#[cfg(any(test, feature = "std"))]
impl<L, M, R> Write for Among<L, M, R>
where
L: Write,
M: Write,
R: Write,
{
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
for_all!(*self, ref mut inner => inner.write(buf))
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
for_all!(*self, ref mut inner => inner.write_all(buf))
}
fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
for_all!(*self, ref mut inner => inner.write_fmt(fmt))
}
fn flush(&mut self) -> io::Result<()> {
for_all!(*self, ref mut inner => inner.flush())
}
}
impl<L, M, R, Target> AsRef<Target> for Among<L, M, R>
where
L: AsRef<Target>,
M: AsRef<Target>,
R: AsRef<Target>,
{
fn as_ref(&self) -> &Target {
for_all!(*self, ref inner => inner.as_ref())
}
}
macro_rules! impl_specific_ref_and_mut {
($t:ty, $($attr:meta),* ) => {
$(#[$attr])*
impl<L, M, R> AsRef<$t> for Among<L, M, R>
where L: AsRef<$t>, M: AsRef<$t>, R: AsRef<$t>,
{
fn as_ref(&self) -> &$t {
for_all!(*self, ref inner => inner.as_ref())
}
}
$(#[$attr])*
impl<L, M, R> AsMut<$t> for Among<L, M, R>
where L: AsMut<$t>, M: AsMut<$t>, R: AsMut<$t>,
{
fn as_mut(&mut self) -> &mut $t {
for_all!(*self, ref mut inner => inner.as_mut())
}
}
};
}
impl_specific_ref_and_mut!(str,);
impl_specific_ref_and_mut!(
::std::path::Path,
cfg(feature = "std"),
doc = "Requires crate feature `std`."
);
impl_specific_ref_and_mut!(
::std::ffi::OsStr,
cfg(feature = "std"),
doc = "Requires crate feature `std`."
);
impl_specific_ref_and_mut!(
::std::ffi::CStr,
cfg(feature = "std"),
doc = "Requires crate feature `std`."
);
impl<L, M, R, Target> AsRef<[Target]> for Among<L, M, R>
where
L: AsRef<[Target]>,
M: AsRef<[Target]>,
R: AsRef<[Target]>,
{
fn as_ref(&self) -> &[Target] {
for_all!(*self, ref inner => inner.as_ref())
}
}
impl<L, M, R, Target> AsMut<Target> for Among<L, M, R>
where
L: AsMut<Target>,
M: AsMut<Target>,
R: AsMut<Target>,
{
fn as_mut(&mut self) -> &mut Target {
for_all!(*self, ref mut inner => inner.as_mut())
}
}
impl<L, M, R, Target> AsMut<[Target]> for Among<L, M, R>
where
L: AsMut<[Target]>,
M: AsMut<[Target]>,
R: AsMut<[Target]>,
{
fn as_mut(&mut self) -> &mut [Target] {
for_all!(*self, ref mut inner => inner.as_mut())
}
}
impl<L, M, R> Deref for Among<L, M, R>
where
L: Deref,
M: Deref<Target = L::Target>,
R: Deref<Target = L::Target>,
{
type Target = L::Target;
fn deref(&self) -> &Self::Target {
for_all!(*self, ref inner => &**inner)
}
}
impl<L, M, R> DerefMut for Among<L, M, R>
where
L: DerefMut,
M: DerefMut<Target = L::Target>,
R: DerefMut<Target = L::Target>,
{
fn deref_mut(&mut self) -> &mut Self::Target {
for_all!(*self, ref mut inner => &mut *inner)
}
}
#[cfg(any(test, feature = "std"))]
impl<L, M, R> Error for Among<L, M, R>
where
L: Error,
M: Error,
R: Error,
{
fn source(&self) -> Option<&(dyn Error + 'static)> {
for_all!(*self, ref inner => inner.source())
}
#[allow(deprecated)]
fn description(&self) -> &str {
for_all!(*self, ref inner => inner.description())
}
#[allow(deprecated)]
fn cause(&self) -> Option<&dyn Error> {
for_all!(*self, ref inner => inner.cause())
}
}
impl<L, M, R> fmt::Display for Among<L, M, R>
where
L: fmt::Display,
M: fmt::Display,
R: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for_all!(*self, ref inner => inner.fmt(f))
}
}
#[test]
fn basic() {
let mut e = Left(2);
let m = Middle(2);
let r = Right(2);
assert_eq!(e, Left(2));
e = r;
assert_eq!(e, Right(2));
assert_eq!(e.left(), None);
assert_eq!(e.middle(), None);
assert_eq!(e.right(), Some(2));
assert_eq!(e.as_ref().right(), Some(&2));
assert_eq!(e.as_mut().right(), Some(&mut 2));
e = m;
assert_eq!(e, Middle(2));
assert_eq!(e.left(), None);
assert_eq!(e.right(), None);
assert_eq!(e.middle(), Some(2));
assert_eq!(e.as_ref().middle(), Some(&2));
assert_eq!(e.as_mut().middle(), Some(&mut 2));
}
#[test]
fn deref() {
use std::{borrow::Cow, string::String};
fn is_str(_: &str) {}
let value: Among<String, Cow<'_, str>, &str> = Left(String::from("test"));
is_str(&value);
}
#[test]
fn iter() {
let x = 3;
let mut iter = match x {
3 => Left(0..10),
6 => Middle(11..17),
_ => Right(17..),
};
assert_eq!(iter.next(), Some(0));
assert_eq!(iter.count(), 9);
}
#[test]
fn seek() {
use std::{io, vec};
let use_empty = 1;
let mut mockdata = [0x00; 256];
for (i, elem) in mockdata.iter_mut().enumerate() {
*elem = i as u8;
}
let mockvec: vec::Vec<u8> = vec![];
let mut reader = if use_empty == 0 {
Left(io::Cursor::new([]))
} else if use_empty == 1 {
Right(io::Cursor::new(&mockdata[..]))
} else {
Middle(io::Cursor::new(&mockvec[..]))
};
let mut buf = [0u8; 16];
assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
assert_eq!(buf, mockdata[..buf.len()]);
assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
assert_ne!(buf, mockdata[..buf.len()]);
reader.seek(io::SeekFrom::Start(0)).unwrap();
assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
assert_eq!(buf, mockdata[..buf.len()]);
}
#[test]
fn read_write() {
use std::{io, vec};
let io = 1;
let mockdata = [0xff; 256];
let mut mockvec = io::Cursor::new(vec![]);
let mut reader = if io == 0 {
Left(io::stdin())
} else if io == 1 {
Right(&mockdata[..])
} else {
Middle(&mut mockvec)
};
let mut buf = [0u8; 16];
assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
assert_eq!(&buf, &mockdata[..buf.len()]);
let mut mockbuf = [0u8; 256];
let mut writer = if io == 0 {
Left(io::stdout())
} else if io == 1 {
Right(&mut mockbuf[..])
} else {
Middle(&mut mockvec)
};
let buf = [1u8; 16];
assert_eq!(writer.write(&buf).unwrap(), buf.len());
}
macro_rules! check_t {
($t:ty) => {{
fn check_ref<T: AsRef<$t>>() {}
fn propagate_ref<T1: AsRef<$t>, T2: AsRef<$t>, T3: AsRef<$t>>() {
check_ref::<Among<T1, T2, T3>>()
}
fn check_mut<T: AsMut<$t>>() {}
fn propagate_mut<T1: AsMut<$t>, T2: AsMut<$t>, T3: AsMut<$t>>() {
check_mut::<Among<T1, T2, T3>>()
}
}};
}
fn _unsized_ref_propagation() {
check_t!(str);
fn check_array_ref<T: AsRef<[Item]>, Item>() {}
fn check_array_mut<T: AsMut<[Item]>, Item>() {}
fn propagate_array_ref<T1: AsRef<[Item]>, T2: AsRef<[Item]>, T3: AsRef<[Item]>, Item>() {
check_array_ref::<Among<T1, T2, T3>, _>()
}
fn propagate_array_mut<T1: AsMut<[Item]>, T2: AsMut<[Item]>, T3: AsMut<[Item]>, Item>() {
check_array_mut::<Among<T1, T2, T3>, _>()
}
}
#[cfg(feature = "std")]
fn _unsized_std_propagation() {
check_t!(::std::path::Path);
check_t!(::std::ffi::OsStr);
check_t!(::std::ffi::CStr);
}