Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions module-lattice/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ zeroize = { version = "1.8.1", optional = true, default-features = false }
getrandom = { version = "0.4", features = ["sys_rng"] }

[features]
alloc = []
ctutils = ["dep:ctutils", "array/ctutils"]
zeroize = ["array/zeroize", "dep:zeroize"]

Expand Down
7 changes: 7 additions & 0 deletions module-lattice/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,19 @@
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg"
)]

#[cfg(feature = "alloc")]
extern crate alloc;

/// Linear algebra with degree-256 polynomials over a prime-order field, vectors of such
/// polynomials, and NTT polynomials / vectors.
mod algebra;

/// Packing of polynomials into coefficients with a specified number of bits.
mod encoding;

/// Support for optional heap offload gated on the `alloc` feature.
mod maybe_box;

/// Integer truncation support.
mod truncate;

Expand All @@ -23,6 +29,7 @@ pub use encoding::{
ArraySize, DecodedValue, Encode, EncodedPolynomial, EncodedPolynomialSize, EncodedVector,
EncodedVectorSize, EncodingSize, VectorEncodingSize, byte_decode, byte_encode,
};
pub use maybe_box::MaybeBox;
pub use truncate::Truncate;

#[cfg(feature = "ctutils")]
Expand Down
56 changes: 56 additions & 0 deletions module-lattice/src/maybe_box.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use core::ops::{Deref, DerefMut};

/// `Box`-like type providing opportunistic heap allocation when the `alloc` feature is available
/// that falls back to stack allocation when it's unavailable.
#[derive(Clone, Debug, PartialEq)]
pub struct MaybeBox<T> {
#[cfg(not(feature = "alloc"))]
inner: T,
#[cfg(feature = "alloc")]
inner: alloc::boxed::Box<T>,
}

impl<T> MaybeBox<T> {
/// Create a new `MaybeBox`, using `Box` if `alloc` is available.
#[inline]
pub fn new(inner: T) -> Self {
#[cfg(not(feature = "alloc"))]
{
Self { inner }
}
#[cfg(feature = "alloc")]
Self {
inner: alloc::boxed::Box::new(inner),
}
}

/// Move the contents out of a [`MaybeBox`].
///
/// This emulates the compiler magic that allows moving out of a box with `*my_box`.
#[inline]
#[must_use]
pub fn into_inner(self) -> T {
#[cfg(not(feature = "alloc"))]
{
self.inner
}
#[cfg(feature = "alloc")]
{
*self.inner
}
}
}

impl<T> Deref for MaybeBox<T> {
type Target = T;

fn deref(&self) -> &Self::Target {
&self.inner
}
}

impl<T> DerefMut for MaybeBox<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}