From 7fe4942b9c2f1f6023eda0fc613be7eff747dcc2 Mon Sep 17 00:00:00 2001 From: soruh Date: Thu, 24 Aug 2023 21:52:12 +0200 Subject: [PATCH] add boolean and optional --- src/datastructures/boolean.rs | 27 ++++++++++++++++ src/datastructures/mod.rs | 2 ++ src/datastructures/optional.rs | 58 ++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+) create mode 100644 src/datastructures/boolean.rs create mode 100644 src/datastructures/optional.rs diff --git a/src/datastructures/boolean.rs b/src/datastructures/boolean.rs new file mode 100644 index 0000000..8b073a1 --- /dev/null +++ b/src/datastructures/boolean.rs @@ -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 for Boolean { + fn from(value: bool) -> Self { + Self::new(value) + } +} + +impl From 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) + } +} diff --git a/src/datastructures/mod.rs b/src/datastructures/mod.rs index 0637479..601be13 100644 --- a/src/datastructures/mod.rs +++ b/src/datastructures/mod.rs @@ -1,4 +1,6 @@ +pub mod boolean; pub mod btree; +pub mod optional; pub mod queue; pub mod string; pub mod vector; diff --git a/src/datastructures/optional.rs b/src/datastructures/optional.rs new file mode 100644 index 0000000..9a3ab80 --- /dev/null +++ b/src/datastructures/optional.rs @@ -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 { + present: Boolean, + value: T, +} + +impl From> for Optional { + fn from(value: Option) -> Self { + match value { + Some(value) => Optional::some(value), + None => Optional::none(), + } + } +} + +impl Default for Optional { + fn default() -> Self { + Self::none() + } +} + +impl Optional { + 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 { + 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() + } +}