lox/core/
util.rs

1use std::{fmt, marker::PhantomData};
2
3use crate::sealed::Sealed;
4
5
6/// An optional and configurable field of a mesh data structure.
7///
8/// Often, data structures can store additional fields to speed up some
9/// operations, while having a higher memory cost. This trait is just useful to
10/// configure data structures, so you will see it in various `Config` traits.
11///
12/// This trait is only implemented by [`StoreField`] and [`OmitField`] and
13/// cannot be implemented for other types. Further, the trait items are
14/// implementation detail.
15pub trait OptionalField: Sealed {
16    #[doc(hidden)]
17    type Storage<T: fmt::Debug + Copy>: FieldStorage<T>;
18}
19
20/// Configures a data structure to *store* an optional field.
21#[allow(missing_debug_implementations)]
22pub enum StoreField {}
23impl Sealed for StoreField {}
24impl OptionalField for StoreField {
25    type Storage<T: fmt::Debug + Copy> = StoredField<T>;
26}
27
28/// Configures a data structure to *omit* an optional field.
29#[allow(missing_debug_implementations)]
30pub enum OmitField {}
31impl Sealed for OmitField {}
32impl OptionalField for OmitField {
33    type Storage<T: fmt::Debug + Copy> = OmittedField<T>;
34}
35
36pub trait FieldStorage<T>: From<T> + fmt::Debug + Copy {
37    fn into_option(self) -> Option<T>;
38}
39
40#[derive(Clone, Copy, Debug)]
41pub struct StoredField<T>(T);
42
43impl<T: Copy + fmt::Debug> FieldStorage<T> for StoredField<T> {
44    #[inline(always)]
45    fn into_option(self) -> Option<T> {
46        Some(self.0)
47    }
48}
49
50impl<T> From<T> for StoredField<T> {
51    #[inline(always)]
52    fn from(value: T) -> Self {
53        Self(value)
54    }
55}
56
57#[derive(Clone, Copy, Debug)]
58pub struct OmittedField<T>(PhantomData<T>);
59
60impl<T: Copy + fmt::Debug> FieldStorage<T> for OmittedField<T> {
61    #[inline(always)]
62    fn into_option(self) -> Option<T> {
63        None
64    }
65}
66
67impl<T> From<T> for OmittedField<T> {
68    #[inline(always)]
69    fn from(_: T) -> Self {
70        Self(PhantomData)
71    }
72}