Skip to main content

Refined

Struct Refined 

Source
pub struct Refined<T, V: Validator<T>> { /* private fields */ }
Expand description

A value of type T that is guaranteed to satisfy the validator V.

Refined is the heart of the parse-dont-validate pattern: a value is checked once, when the wrapper is constructed, and the type then proves the invariant for the rest of the value’s life. Code that receives a Refined<T, V> never has to re-validate, because a Refined that violates V cannot be constructed through safe code.

The wrapper is #[repr(transparent)] and stores only the value plus a zero-sized marker, so it has the exact same size and layout as T. The guarantee costs nothing at runtime.

There is deliberately no DerefMut and no public field: handing out a &mut T would let a caller mutate the value into an invalid state behind the type’s back. To change a refined value, build a new one with Refined::new (or recover the inner value with Refined::into_inner, change it, and re-wrap it).

§Examples

Define a rule, alias a domain type, and construct it:

use type_lib::{Refined, ValidationError, Validator};

struct NonEmpty;

impl<S: AsRef<str> + ?Sized> Validator<S> for NonEmpty {
    type Error = ValidationError;

    fn validate(value: &S) -> Result<(), Self::Error> {
        if value.as_ref().is_empty() {
            Err(ValidationError::new("non_empty", "value must not be empty"))
        } else {
            Ok(())
        }
    }
}

/// A username that can never be empty.
type Username = Refined<String, NonEmpty>;

let user = Username::new("alice".to_owned());
assert!(user.is_ok());
assert!(Username::new(String::new()).is_err());

Read the inner value through Deref, Refined::get, or Refined::into_inner:

let user = Username::new("alice".to_owned())?;

assert_eq!(user.len(), 5);          // via Deref to String
assert_eq!(user.get(), "alice");    // borrow the inner value
assert_eq!(user.into_inner(), "alice"); // take ownership back

Implementations§

Source§

impl<T, V: Validator<T>> Refined<T, V>

Source

pub fn new(value: T) -> Result<Self, V::Error>

Validates value and, on success, wraps it.

This is the only safe way to construct a Refined, which is what makes the invariant trustworthy everywhere else.

§Errors

Returns V::Error when value fails V’s rule. The value is dropped in that case.

§Examples
let ok = Refined::<&str, NonEmpty>::new("hi");
assert!(ok.is_ok());

let bad = Refined::<&str, NonEmpty>::new("");
assert!(bad.is_err());
Source

pub fn get(&self) -> &T

Borrows the validated inner value.

The same borrow is also available through Deref, so methods of T can be called directly on a Refined; get is the explicit form for when inference needs a nudge.

§Examples
let n = Refined::<i32, AnyI32>::new(7).expect("always valid");
assert_eq!(*n.get(), 7);
Source

pub fn into_inner(self) -> T

Consumes the wrapper and returns the inner value.

Use this when you need to mutate or transform the value: take it out, change it, then re-wrap with Refined::new to re-establish the guarantee.

§Examples
let n = Refined::<i32, AnyI32>::new(7).expect("always valid");
assert_eq!(n.into_inner(), 7);

Trait Implementations§

Source§

impl<T, V: Validator<T>> AsRef<T> for Refined<T, V>

Source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<T: Clone, V: Validator<T>> Clone for Refined<T, V>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T: Debug, V: Validator<T>> Debug for Refined<T, V>

Source§

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

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

impl<T, V: Validator<T>> Deref for Refined<T, V>

Source§

type Target = T

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<T: Display, V: Validator<T>> Display for Refined<T, V>

Source§

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

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

impl<T: Hash, V: Validator<T>> Hash for Refined<T, V>

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<T: Ord, V: Validator<T>> Ord for Refined<T, V>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

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

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

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

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

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

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

impl<T: PartialEq, V: Validator<T>> PartialEq for Refined<T, V>

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: PartialOrd, V: Validator<T>> PartialOrd for Refined<T, V>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T: Copy, V: Validator<T>> Copy for Refined<T, V>

Source§

impl<T: Eq, V: Validator<T>> Eq for Refined<T, V>

Auto Trait Implementations§

§

impl<T, V> Freeze for Refined<T, V>
where T: Freeze,

§

impl<T, V> RefUnwindSafe for Refined<T, V>
where T: RefUnwindSafe,

§

impl<T, V> Send for Refined<T, V>
where T: Send,

§

impl<T, V> Sync for Refined<T, V>
where T: Sync,

§

impl<T, V> Unpin for Refined<T, V>
where T: Unpin,

§

impl<T, V> UnsafeUnpin for Refined<T, V>
where T: UnsafeUnpin,

§

impl<T, V> UnwindSafe for Refined<T, V>
where T: 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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

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

Source§

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

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

Source§

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>,

Source§

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.