add boolean and optional

This commit is contained in:
soruh 2023-08-24 21:52:12 +02:00
parent 3e37286621
commit 7fe4942b9c
3 changed files with 87 additions and 0 deletions

View File

@ -0,0 +1,27 @@
use zerocopy::{AsBytes, FromBytes, FromZeroes, Unaligned};
#[derive(Clone, Copy, FromBytes, FromZeroes, AsBytes, Unaligned)]
#[repr(transparent)]
pub struct Boolean(u8);
impl From<bool> for Boolean {
fn from(value: bool) -> Self {
Self::new(value)
}
}
impl From<Boolean> for bool {
fn from(value: Boolean) -> Self {
value.get()
}
}
impl Boolean {
pub fn get(self) -> bool {
self.0 != 0
}
pub fn new(value: bool) -> Self {
Self(value as u8)
}
}

View File

@ -1,4 +1,6 @@
pub mod boolean;
pub mod btree;
pub mod optional;
pub mod queue;
pub mod string;
pub mod vector;

View File

@ -0,0 +1,58 @@
use zerocopy::{AsBytes, FromBytes, FromZeroes, Unaligned};
use super::boolean::Boolean;
#[derive(Clone, Copy, FromBytes, FromZeroes, AsBytes, Unaligned)]
#[repr(packed)]
pub struct Optional<T> {
present: Boolean,
value: T,
}
impl<T: FromZeroes> From<Option<T>> for Optional<T> {
fn from(value: Option<T>) -> Self {
match value {
Some(value) => Optional::some(value),
None => Optional::none(),
}
}
}
impl<T: FromZeroes> Default for Optional<T> {
fn default() -> Self {
Self::none()
}
}
impl<T> Optional<T> {
pub fn none() -> Self
where
T: FromZeroes,
{
Self {
present: Boolean::new(false),
value: T::new_zeroed(),
}
}
pub fn some(value: T) -> Self {
Self {
present: Boolean::new(true),
value,
}
}
pub fn get(self) -> Option<T> {
if self.present.get() {
Some(self.value)
} else {
None
}
}
pub fn is_some(&self) -> bool {
self.present.get()
}
pub fn is_none(&self) -> bool {
!self.is_some()
}
}