Skip to content

Commit 79a396e

Browse files
hoshinolinajannau
authored andcommitted
*RFL import: kernel::types::Bool
Commit reference: 3dfc5eb
1 parent 6063863 commit 79a396e

1 file changed

Lines changed: 82 additions & 0 deletions

File tree

rust/kernel/types.rs

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -445,3 +445,85 @@ pub enum Either<L, R> {
445445
/// Constructs an instance of [`Either`] containing a value of type `R`.
446446
Right(R),
447447
}
448+
449+
/// A trait for boolean types.
450+
///
451+
/// This is meant to be used in type states to allow boolean constraints in implementation blocks.
452+
/// In the example below, the implementation containing `MyType::set_value` could _not_ be
453+
/// constrained to type states containing `Writable = true` if `Writable` were a constant instead
454+
/// of a type.
455+
///
456+
/// # Safety
457+
///
458+
/// No additional implementations of [`Bool`] should be provided, as [`True`] and [`False`] are
459+
/// already provided.
460+
///
461+
/// # Examples
462+
///
463+
/// ```
464+
/// # use kernel::{Bool, False, True};
465+
/// use core::marker::PhantomData;
466+
///
467+
/// // Type state specifies whether the type is writable.
468+
/// trait MyTypeState {
469+
/// type Writable: Bool;
470+
/// }
471+
///
472+
/// // In state S1, the type is writable.
473+
/// struct S1;
474+
/// impl MyTypeState for S1 {
475+
/// type Writable = True;
476+
/// }
477+
///
478+
/// // In state S2, the type is not writable.
479+
/// struct S2;
480+
/// impl MyTypeState for S2 {
481+
/// type Writable = False;
482+
/// }
483+
///
484+
/// struct MyType<T: MyTypeState> {
485+
/// value: u32,
486+
/// _p: PhantomData<T>,
487+
/// }
488+
///
489+
/// impl<T: MyTypeState> MyType<T> {
490+
/// fn new(value: u32) -> Self {
491+
/// Self {
492+
/// value,
493+
/// _p: PhantomData,
494+
/// }
495+
/// }
496+
/// }
497+
///
498+
/// // This implementation block only applies if the type state is writable.
499+
/// impl<T> MyType<T>
500+
/// where
501+
/// T: MyTypeState<Writable = True>,
502+
/// {
503+
/// fn set_value(&mut self, v: u32) {
504+
/// self.value = v;
505+
/// }
506+
/// }
507+
///
508+
/// let mut x = MyType::<S1>::new(10);
509+
/// let mut y = MyType::<S2>::new(20);
510+
///
511+
/// x.set_value(30);
512+
513+
///
514+
/// // The code below fails to compile because `S2` is not writable.
515+
/// // y.set_value(40);
516+
/// ```
517+
pub unsafe trait Bool {}
518+
519+
/// Represents the `true` value for types with [`Bool`] bound.
520+
pub struct True;
521+
522+
// SAFETY: This is one of the only two implementations of `Bool`.
523+
unsafe impl Bool for True {}
524+
525+
/// Represents the `false` value for types wth [`Bool`] bound.
526+
pub struct False;
527+
528+
// SAFETY: This is one of the only two implementations of `Bool`.
529+
unsafe impl Bool for False {}

0 commit comments

Comments
 (0)