Struct Optioned

Source
pub struct Optioned<T: Noned + Copy> { /* private fields */ }
Expand description

An Option<T>-like structure that takes only as much space as the enclosed value, at the cost of removing one particular None value from the value domain (see Noned)

Implementations§

Source§

impl<T: Noned + Copy> Optioned<T>

Source

pub fn some(t: T) -> Self

Create an Optioned<T> that is some(t).

§Panics

panics if the supplied value is the None value

§Examples
Optioned::<i32>::some(1); // Optioned(1)
Optioned::<f64>::some(std::f64::NAN); // panic!s
Source

pub fn none() -> Self

Create an Optioned<T> that is none().

§Examples
Optioned::<u16>::none(); // Optioned(std::u16::MAX)
Source

pub fn into_option(self) -> Option<T>

Convenience funtion to convert an Optioned into an Option.

Techinically this is possible with the Into<Option<T>> implementation in this crate. However, experience has shown that there are many cases where the compiler isn’t able to infer the correct type for the generic parameter and issues an error. As a workaround you can use Into::<Option<T>>::into(...) or .map(|inner| inner) which will both work. The first is verbose and the second makes the intention less clear, so this method is provided as a convenience.

if let Some(val) = some(15).into_option() {
    println!("val = {}", val);
}

The following example will fail to compile because of type inference.

if let Some(val) = some(15).into() {
    println!("val = {}", val);
}
Source

pub fn is_none(&self) -> bool

Returns true if this Optioned is None, false otherwise.

Source

pub fn is_some(&self) -> bool

Returns true if this Optioned contains a value, false otherwise.

Source

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

Unwraps the value, if any, else panics with the given message.

§Panics

if self is None

§Examples

For Some(_), the corresponding value is returned.

assert_eq!(42u8, Optioned::some(42u8).expect("FAIL"));

On None, it panics with the given message.

Optioned::<u8>::none().expect("FAIL"); // panics with FAIL
Source

pub fn unwrap(&self) -> T

Unwraps the value, if any, else panics with “unwrap called on None”.

§Panics

if self is None

§Examples

For Some(_), the corresponding value is returned.

assert_eq!(42u8, Optioned::some(42u8).unwrap());

On None, it panics with the given message.

Optioned::<u8>::none().unwrap(); // panics
Source

pub fn unpack(&self) -> T

Returns the contained value, even if None.

§Examples
assert_eq!(-128i8, none().unpack());
assert_eq!(1u32, some(1).unpack());
Source

pub fn unwrap_or(&self, def: T) -> T

Returns the contained value or a default.

§Examples
assert_eq!(-1i8, some(-1i8).unwrap_or(127i8));
assert_eq!(42u16, none().unwrap_or(42u16));
Source

pub fn unwrap_or_else<F>(self, f: F) -> T
where F: FnOnce() -> T,

Returns the contained value or a calculated default.

§Examples
assert_eq!(-1i8, some(-1i8).unwrap_or_else(|| panic!()));
assert_eq!(42u16, none().unwrap_or_else(|| 42u16));
Source

pub fn map<U, F>(self, f: F) -> Option<U>
where F: FnOnce(T) -> U,

Maps the Optioned to an Option<U> by applying the function over the contained value, if any.

§Examples
assert_eq!(Some(-42), some(42i8).map(|x| -x));
assert_eq!(None, none::<i8>().map(|x| -x));
Source

pub fn map_t<U, F>(self, f: F) -> Optioned<U>
where F: FnOnce(T) -> U, U: Noned + Copy,

Maps the Optioned<T> to an Optioned<U> by applying the function over the contained value, if any. Requires that the result type of the function be Noned + Copy, as other types aren’t compatible with Optioned.

§Examples
assert_eq!(some(-42), some(42i8).map_t(|x| -x));
assert_eq!(none::<i8>(), none::<i8>().map_t(|x| -x));
Source

pub fn map_or<U, F>(self, default: U, f: F) -> U
where F: FnOnce(T) -> U,

Maps the contained value to a U by applying the function or return a default.

§Examples
assert_eq!("1", some(1usize).map_or("Unknown".to_string(), |b| b.to_string()));
assert_eq!("Unknown", none::<usize>().map_or("Unknown".to_string(), |b| b.to_string()));
Source

pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
where D: FnOnce() -> U, F: FnOnce(T) -> U,

Maps a value to a U by applying the function or return a computed default.

§Examples
assert_eq!("1", some(1usize).map_or_else(|| "Unknown".to_string(),
    |b| b.to_string()));
assert_eq!("Unknown", none::<usize>().map_or_else(
    || "Unknown".to_string(), |b| b.to_string()));
Source

pub fn or(self, other: Optioned<T>) -> Optioned<T>

Returns this option if it contains a value, otherwise returns the other.

Arguments passed to or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use or_else, which is lazily evaluated.

§Examples
let x = some(2);
let y = none();
assert_eq!(x.or(y), some(2));

let x = none();
let y = some(100);
assert_eq!(x.or(y), some(100));

let x = some(2);
let y = some(100);
assert_eq!(x.or(y), some(2));

let x: Optioned<u32> = none();
let y = none();
assert_eq!(x.or(y), none());
Source

pub fn or_else<F>(self, f: F) -> Optioned<T>
where F: FnOnce() -> Optioned<T>,

Returns this option if it contains a value, otherwise calls f and returns the result.

§Examples
fn nothing() -> Optioned<u32> { none() }
fn something() -> Optioned<u32> { some(1) }

assert_eq!(some(2).or_else(something), some(2));
assert_eq!(none().or_else(something), some(1));
assert_eq!(none().or_else(nothing), none());
Source

pub fn and<U>(self, other: Optioned<U>) -> Optioned<U>
where U: Noned + Copy,

Returns the None value for type U if this value or other contains their respective None values. Otherwise returns the other Optioned struct.

§Examples
let the_other = some::<u32>(42);

assert_eq!(some('a').and(the_other), some(42));
assert_eq!(none::<char>().and(the_other), none::<u32>());
assert_eq!(some('a').and(none::<u32>()), none::<u32>());
assert_eq!(none::<char>().and(none::<u32>()), none::<u32>());
Source

pub fn and_then<F, U>(self, f: F) -> Optioned<U>
where F: FnOnce(T) -> Optioned<U>, U: Noned + Copy,

Returns this Optioned if it contains the the None value, otherwise calls f with the contained value and returns the result as an Optioned<U>.

§Examples
fn nothing() -> Optioned<u32> { none() }
fn something() -> Optioned<u32> { some(1) }
fn add_two(val: u32) -> Optioned<u32> {
  wrap( val + 2)
}

fn failed_function(val: u32) -> Optioned<u32> {
  none()
}

assert_eq!(some(2).and_then(add_two), some(4));
assert_eq!(none().and_then(add_two), none());
assert_eq!(some(2).and_then(failed_function), none());
assert_eq!(none().and_then(failed_function), none());
Source

pub fn ok_or<E>(self, err: E) -> Result<T, E>

Transforms the Optioned<T> into a Result<T, E>, mapping some(v) to Ok(v) and none() to Err(err).

§Examples

let x = some(42u32);
assert_eq!(x.ok_or("was none"), Ok(42u32));

let x: Optioned<u32> = none();
assert_eq!(x.ok_or("was none"), Err("was none"));
Source

pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E>

Transforms the Optioned<T> into a Result<T, E>, mapping some(v) to Ok(v) and none() to Err(err).

§Examples

let x = some(42u32);
assert_eq!(x.ok_or_else(|| "was none"), Ok(42u32));

let x: Optioned<u32> = none();
assert_eq!(x.ok_or_else(|| "was none"), Err("was none"));
Source

pub fn take(&mut self) -> Option<T>

Takes the value out of the Optioned and returns ist as Option<T>, changing self to None.

§Examples
let mut x = some(1u8);
assert_eq!(Some(1u8), x.take());
assert!(x.is_none());
Source

pub fn as_slice(&self) -> &[T]

Return a possibly empty slice over the contained value, if any.

§Examples
assert_eq!(&[42], some(42u8).as_slice());
assert!(none::<i16>().as_slice().is_empty());
Source

pub fn iter(&self) -> OptionedIter<T>

return an iterator over all contained (that is zero or one) values.

§Examples
assert_eq!(None, none::<u64>().iter().next());
assert_eq!(Some(42u64), some(42u64).iter().next());

Trait Implementations§

Source§

impl<T: Clone + Noned + Copy> Clone for Optioned<T>

Source§

fn clone(&self) -> Optioned<T>

Returns a duplicate 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: Noned + Copy + Debug> Debug for Optioned<T>

Source§

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

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

impl<T: Noned + Copy> Default for Optioned<T>

Source§

fn default() -> Optioned<T>

Returns the “default value” for a type. Read more
Source§

impl<'a, T: Noned + Copy> From<&'a Option<T>> for Optioned<T>

Source§

fn from(o: &Option<T>) -> Optioned<T>

Converts to this type from the input type.
Source§

impl<T: Noned + Copy> From<Option<T>> for Optioned<T>

Source§

fn from(o: Option<T>) -> Optioned<T>

Converts to this type from the input type.
Source§

impl<T: Noned + Copy> From<T> for Optioned<T>

Source§

fn from(o: T) -> Optioned<T>

Converts to this type from the input type.
Source§

impl<T> Hash for Optioned<T>
where T: Noned + Copy + Hash,

Source§

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

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: Noned + Copy> Into<Option<T>> for &'a Optioned<T>

Source§

fn into(self) -> Option<T>

Converts this type into the (usually inferred) input type.
Source§

impl<T: Noned + Copy> Into<Option<T>> for Optioned<T>

Source§

fn into(self) -> Option<T>

Converts this type into the (usually inferred) input type.
Source§

impl<T> Ord for Optioned<T>
where T: Eq + OptEq + OptOrd + Noned + Copy,

Source§

fn cmp(&self, other: &Self) -> 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,

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

impl<T> PartialEq for Optioned<T>
where T: OptEq + Noned + Copy,

Equality works as usual.

§Examples

assert_eq!(some(1u8), some(1u8));
assert_eq!(none::<u32>(), none::<u32>());
Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · 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 for Optioned<T>
where T: PartialEq + OptEq + OptOrd + Noned + Copy,

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 · 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 · 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 · 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 · 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 + Noned + Copy> Copy for Optioned<T>

Source§

impl<T> Eq for Optioned<T>
where T: OptEq + Noned + Copy,

Auto Trait Implementations§

§

impl<T> Freeze for Optioned<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for Optioned<T>
where T: RefUnwindSafe,

§

impl<T> Send for Optioned<T>
where T: Send,

§

impl<T> Sync for Optioned<T>
where T: Sync,

§

impl<T> Unpin for Optioned<T>
where T: Unpin,

§

impl<T> UnwindSafe for Optioned<T>
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<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, 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.