Skip to content

Commit

Permalink
Add pod option type
Browse files Browse the repository at this point in the history
  • Loading branch information
febo committed Jan 2, 2024
1 parent bdcca21 commit 4d8f286
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/types/mod.rs
@@ -1,5 +1,7 @@
mod pod_bool;
mod pod_option;
mod pod_str;

pub use pod_bool::*;
pub use pod_option::*;
pub use pod_str::*;
41 changes: 41 additions & 0 deletions src/types/pod_option.rs
@@ -0,0 +1,41 @@
use bytemuck::{Pod, Zeroable};

/// Used for "pod-enabled" types that can have a `None` value.
pub trait Nullable: Pod {
/// Indicates if the value is `Some`.
fn is_some(&self) -> bool;

/// Indicates if the value is `None`.
fn is_none(&self) -> bool;
}

/// A "pod-enabled" type that can be used as an `Option<T>` without
/// requiring extra space to indicate if the value is `Some` or `None`.
///
/// This can be used when a specific value of `T` indicates that its
/// value is `None`.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct PodOption<T: Nullable>(T);

unsafe impl<T: Nullable> Pod for PodOption<T> {}

unsafe impl<T: Nullable> Zeroable for PodOption<T> {}

impl<T: Nullable> PodOption<T> {
pub fn value(&self) -> Option<&T> {
if self.0.is_some() {
Some(&self.0)
} else {
None
}
}

pub fn value_mut(&mut self) -> Option<&mut T> {
if self.0.is_some() {
Some(&mut self.0)
} else {
None
}
}
}

0 comments on commit 4d8f286

Please sign in to comment.