pub unsafe trait Bool { }
Expand description

A trait for boolean types.

This is meant to be used in type states to allow boolean constraints in implementation blocks. In the example below, the implementation containing MyType::set_value could not be constrained to type states containing Writable = true if Writable were a constant instead of a type.

Safety

No additional implementations of Bool should be provided, as True and False are already provided.

Examples

use core::marker::PhantomData;

// Type state specifies whether the type is writable.
trait MyTypeState {
    type Writable: Bool;
}

// In state S1, the type is writable.
struct S1;
impl MyTypeState for S1 {
    type Writable = True;
}

// In state S2, the type is not writable.
struct S2;
impl MyTypeState for S2 {
    type Writable = False;
}

struct MyType<T: MyTypeState> {
    value: u32,
    _p: PhantomData<T>,
}

impl<T: MyTypeState> MyType<T> {
    fn new(value: u32) -> Self {
        Self {
            value,
            _p: PhantomData,
        }
    }
}

// This implementation block only applies if the type state is writable.
impl<T> MyType<T>
where
    T: MyTypeState<Writable = True>,
{
    fn set_value(&mut self, v: u32) {
        self.value = v;
    }
}

let mut x = MyType::<S1>::new(10);
let mut y = MyType::<S2>::new(20);

x.set_value(30);

// The code below fails to compile because `S2` is not writable.
// y.set_value(40);

Implementors