add boolean and optional
This commit is contained in:
parent
3e37286621
commit
7fe4942b9c
27
src/datastructures/boolean.rs
Normal file
27
src/datastructures/boolean.rs
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,6 @@
|
|||||||
|
pub mod boolean;
|
||||||
pub mod btree;
|
pub mod btree;
|
||||||
|
pub mod optional;
|
||||||
pub mod queue;
|
pub mod queue;
|
||||||
pub mod string;
|
pub mod string;
|
||||||
pub mod vector;
|
pub mod vector;
|
||||||
|
58
src/datastructures/optional.rs
Normal file
58
src/datastructures/optional.rs
Normal 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()
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user