Crate fera_optional

source ·
Expand description

An optional value trait and some implementations.

There are two main uses for this:

  1. To abstract over the representation of optional values in generic code (Optional trait);
  2. To represent optional value in a space efficient way (OptionalBool, OptionalMax, OptionalMin, etc).

Note that this is complementary to std::option::Option, not a replacement. The idea is to use std::option::Option interface by converting an Optional value to an std::option::Option value.

The optional crate is similar, but we think that this module is more generic, mainly because optional crate is not concerned with the use case 1.

This crate can be used through fera crate.

Example

One can use OptionalMax<usize> to represent an optional usize where the None value is represented by usize::MAX.

use fera_optional::*;
use std::mem;

assert_eq!(mem::size_of::<usize>(), mem::size_of::<OptionalMax<usize>>());

// default
let y = OptionalMax::<usize>::default();
assert_eq!(None, y.into_option());

// from a value
let x = OptionalMax::from(10usize);
assert_eq!(Some(&10), x.to_option_ref());
assert_eq!(10, *x.to_option_ref().unwrap());

// from an optional value
let z = Some(10);
let w = OptionalMax::from(z);
assert_eq!(Some(10), w.into_option());

Using OptionalBool

use fera_optional::*;
use std::mem;

assert_eq!(1, mem::size_of::<OptionalBool>());

let mut x = OptionalBool::from(false);
assert!(!*x.to_option_ref().unwrap());

// change the value
*x.to_option_mut().unwrap() = true;
assert!(*x.to_option_ref().unwrap());

Structs

Creates T::max_value() as None.
Creates T::min_value() as None.
An Optional for bool with 1 byte size. std::option::Option<bool> have size 1 since rustc 1.23.
An Optional that represents None with a specified value (B::none()) of T domain.

Traits

A builder for None values for type T.
A trait that represents an optional value.

Type Definitions

An Optional that uses T::max_value() as None.
An Optional that uses T::min_value() as None.