Enum validated::Validated

source ·
pub enum Validated<T, E> {
    Good(T),
    Fail(NEVec<E>),
}
Expand description

Similar to Result, but cumulative in its error type.

§Error weaving

Consider that when using collect in a “Traversable” way to pull a single Result out of an Iterator containing many Results, it will fail on the first Err and short-circuit the iteration. This is suboptimal if we wish to be made aware of every failure that (would have) occurred.

use validated::Validated::{self, Good, Fail};
use nonempty_collections::*;

let v = vec![Ok(1), Ok(2), Ok(3)];
let r: Validated<Vec<u32>, &str> = Good(vec![1, 2, 3]);
assert_eq!(r, v.into_iter().collect());

let v = vec![Ok(1), Err("Oh!"), Ok(2), Err("No!"), Ok(3)];
let r: Validated<Vec<u32>, &str> = Fail(nev!["Oh!", "No!"]);
assert_eq!(r, v.into_iter().collect());

Naturally iterators of Validated values can be collected in a similar way:

use validated::Validated::{self, Good, Fail};
use nonempty_collections::*;

let v = vec![Good(1), Good(2), Good(3)];
let r: Validated<Vec<u32>, &str> = Good(vec![1, 2, 3]);
assert_eq!(r, v.into_iter().collect());

let v = vec![Good(1), Validated::fail("No!"), Good(3), Validated::fail("Ack!")];
let r: Validated<Vec<u32>, &str> = Fail(nev!["No!", "Ack!"]);
assert_eq!(r, v.into_iter().collect());

§Mapping composite results

This type also provides mapN methods, which are surprisingly missing on Option and Result.

use validated::Validated::{self, Good, Fail};

let v: Validated<u32, &str> = Good(1).map3(Good(2), Good(3), |a, b, c| a + b + c);
assert_eq!(v, Good(6));

For Validated in particular these are quite useful, as a meaningful and_then cannot be written for it.

Formally, Validated is not a Monad, but it is an Applicative Functor.

Variants§

§

Good(T)

Analogous to Result::Ok.

§

Fail(NEVec<E>)

Analogous to Result::Err, except that the error type is cumulative.

Implementations§

source§

impl<T, E> Validated<T, E>

source

pub fn fail(e: E) -> Validated<T, E>

Fail with the given error.

source

pub fn as_mut(&mut self) -> Validated<&mut T, &mut E>

Converts from &mut Validated<T, E> to Validated<&mut T, &mut E>.

Note: In the case of Fail, a new Vec of references is allocated.

source

pub fn as_ref(&self) -> Validated<&T, &E>

Converts from &Validated<T, E> to Validated<&T, &E>.

Produces a new Validated, containing references to the original, leaving the original in place.

Note: In the case of Fail, a new Vec of references is allocated.

source

pub fn expect(self, msg: &str) -> T

Returns the contained Good value, consuming self.

§Panics

Panics with a custom message if self is actually the Fail variant.

source

pub fn is_good(&self) -> bool

Was a given Validated operation completely successful?

source

pub fn is_fail(&self) -> bool

Did a given Validated operation have at least one failure?

source

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator over the possibly contained value.

The iterator yields one value if the result is Good, otherwise nothing.

source

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns a mutable iterator over the possibly contained value.

The iterator yields one value if the result is Good, otherwise nothing.

source

pub fn map<U, F>(self, op: F) -> Validated<U, E>
where F: FnOnce(T) -> U,

Applies a function to the T value of a Good variant, or leaves a Fail variant untouched.

use validated::Validated::{self, Good, Fail};

let v: Validated<u32, &str> = Good(1);
let r = v.map(|n| n * 2);
assert_eq!(r, Good(2));

let v: Validated<u32, &str> = Validated::fail("No!");
let r = v.map(|n| n * 2);
assert_eq!(r, Validated::fail("No!"));
source

pub fn map_err<R, F>(self, op: F) -> Validated<T, R>
where F: FnOnce(NEVec<E>) -> NEVec<R>,

Applies a function to the Vec<E> of a Fail variant, or leaves a Good variant untouched.

source

pub fn map2<U, Z, F>(self, vu: Validated<U, E>, f: F) -> Validated<Z, E>
where F: FnOnce(T, U) -> Z,

Maps a function over two Validated, but only if both are of the Good variant. If both failed, then their errors are concatenated.

use validated::Validated::{self, Good, Fail};

let v: Validated<u32, &str> = Good(1).map2(Good(2), |a, b| a + b);
assert_eq!(v, Good(3));

let v: Validated<u32, &str> = Good(1).map2(Validated::fail("No!"), |a, b: u32| a + b);
assert_eq!(v, Validated::fail("No!"));
source

pub fn map3<U, V, Z, F>( self, vu: Validated<U, E>, vv: Validated<V, E>, f: F ) -> Validated<Z, E>
where F: FnOnce(T, U, V) -> Z,

Maps a function over three Validated, but only if all three are of the Good variant. If any failed, then their errors are concatenated.

use validated::Validated::{self, Good, Fail};

let v: Validated<u32, &str> = Good(1).map3(Good(2), Good(3), |a, b, c| a + b + c);
assert_eq!(v, Good(6));

let v: Validated<u32, &str> = Good(1).map3(Good(2), Validated::fail("No!"), |a, b, c: u32| a + b + c);
assert_eq!(v, Validated::fail("No!"));
source

pub fn map4<U, V, W, Z, F>( self, vu: Validated<U, E>, vv: Validated<V, E>, vw: Validated<W, E>, f: F ) -> Validated<Z, E>
where F: FnOnce(T, U, V, W) -> Z,

Maps a function over four Validated, but only if all four are of the Good variant. If any failed, then their errors are concatenated.

source

pub fn ok(self) -> Result<T, NEVec<E>>

Converts self into a Result.

source

pub fn unwrap(self) -> T

Returns the contained Good value, consuming self.

§Examples
use validated::Validated;

let v: Validated<u32, &str> = Validated::Good(1);
assert_eq!(v.unwrap(), 1);
§Panics

Panics if self is actually the Fail variant.

source

pub fn unwrap_or(self, default: T) -> T

Returns the contained Good value or a provided default.

Arguments passed to unwrap_or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use Validated::unwrap_or_else instead.

§Examples
use validated::Validated;

let v: Validated<u32, &str> = Validated::Good(1);
assert_eq!(v.unwrap_or(2), 1);

let v: Validated<u32, &str> = Validated::fail("Oh no!");
assert_eq!(v.unwrap_or(2), 2);
source

pub fn unwrap_or_else<F>(self, op: F) -> T
where F: FnOnce(NEVec<E>) -> T,

Returns the contained Good value or computes it from a closure.

source§

impl<T: Default, E> Validated<T, E>

source

pub fn unwrap_or_default(self) -> T

Returns the contained Good value or the default for T.

source§

impl<T: Deref, E> Validated<T, E>

source

pub fn as_deref(&self) -> Validated<&T::Target, &E>

source§

impl<T: DerefMut, E> Validated<T, E>

source

pub fn as_deref_mut(&mut self) -> Validated<&mut T::Target, &mut E>

Trait Implementations§

source§

impl<T: Clone, E: Clone> Clone for Validated<T, E>

source§

fn clone(&self) -> Validated<T, E>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T: Debug, E: Debug> Debug for Validated<T, E>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T, E> From<Result<T, E>> for Validated<T, E>

source§

fn from(r: Result<T, E>) -> Self

Converts to this type from the input type.
source§

impl<T, U, E> FromIterator<Result<T, E>> for Validated<U, E>
where U: FromIterator<T>,

source§

fn from_iter<I: IntoIterator<Item = Result<T, E>>>(iter: I) -> Self

Creates a value from an iterator. Read more
source§

impl<T, U, E> FromIterator<Validated<T, E>> for Validated<U, E>
where U: FromIterator<T>,

source§

fn from_iter<I: IntoIterator<Item = Validated<T, E>>>(iter: I) -> Self

Creates a value from an iterator. Read more
source§

impl<T: Hash, E: Hash> Hash for Validated<T, E>

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<'a, T, E> IntoIterator for &'a Validated<T, E>

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Iter<'a, T>

Creates an iterator from a value. Read more
source§

impl<'a, T, E> IntoIterator for &'a mut Validated<T, E>

§

type Item = &'a mut T

The type of the elements being iterated over.
§

type IntoIter = IterMut<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> IterMut<'a, T>

Creates an iterator from a value. Read more
source§

impl<T, E> IntoIterator for Validated<T, E>

§

type Item = T

The type of the elements being iterated over.
§

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<T: Ord, E: Ord> Ord for Validated<T, E>

source§

fn cmp(&self, other: &Validated<T, E>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
source§

impl<T: PartialEq, E: PartialEq> PartialEq for Validated<T, E>

source§

fn eq(&self, other: &Validated<T, E>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T: PartialOrd, E: PartialOrd> PartialOrd for Validated<T, E>

source§

fn partial_cmp(&self, other: &Validated<T, E>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<T, U, E> Sum<Result<U, E>> for Validated<T, E>
where T: Sum<U>,

use validated::Validated;

let ns: Validated<u32, ()> = [Ok(1), Ok(2), Ok(3)].into_iter().sum();
assert_eq!(Validated::Good(6), ns);
source§

fn sum<I>(iter: I) -> Self
where I: Iterator<Item = Result<U, E>>,

Method which takes an iterator and generates Self from the elements by “summing up” the items.
source§

impl<T, U, E> Sum<Validated<U, E>> for Validated<T, E>
where T: Sum<U>,

source§

fn sum<I>(iter: I) -> Self
where I: Iterator<Item = Validated<U, E>>,

Method which takes an iterator and generates Self from the elements by “summing up” the items.
source§

impl<T: Eq, E: Eq> Eq for Validated<T, E>

source§

impl<T, E> StructuralPartialEq for Validated<T, E>

Auto Trait Implementations§

§

impl<T, E> Freeze for Validated<T, E>
where T: Freeze, E: Freeze,

§

impl<T, E> RefUnwindSafe for Validated<T, E>

§

impl<T, E> Send for Validated<T, E>
where T: Send, E: Send,

§

impl<T, E> Sync for Validated<T, E>
where T: Sync, E: Sync,

§

impl<T, E> Unpin for Validated<T, E>
where T: Unpin, E: Unpin,

§

impl<T, E> UnwindSafe for Validated<T, E>
where T: UnwindSafe, E: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoIteratorExt for T
where T: IntoIterator,

source§

fn try_into_nonempty_iter(self) -> Option<<T as IntoIteratorExt>::IntoIter>

Tries to convert self into NonEmptyIterator. Calls self.next() once. If self doesn’t return Some upon the first call to next(), returns None.

§

type Item = <T as IntoIterator>::Item

The type of the elements being iterated over.
§

type IntoIter = Chain<Once<<T as IntoIteratorExt>::Item>, <T as IntoIterator>::IntoIter>

Which kind of NonEmptyIterator are we turning this into?
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.