secure_gate/cloneable/
array.rs

1use crate::Fixed;
2use zeroize::Zeroize;
3
4/// Inner wrapper for a fixed-size array of bytes that can be safely cloned as a secret.
5///
6/// This struct wraps a `[u8; N]` array and implements the necessary traits for secure
7/// secret handling: `Clone` for duplication and `Zeroize` for secure memory wiping.
8/// The `zeroize(drop)` attribute ensures the array is zeroized when this struct is dropped.
9#[derive(Clone, PartialEq, Zeroize)]
10#[zeroize(drop)]
11pub struct CloneableArrayInner<const N: usize>(pub [u8; N]);
12
13impl<const N: usize> crate::CloneSafe for CloneableArrayInner<N> {}
14
15/// A fixed-size array of bytes wrapped as a cloneable secret.
16///
17/// This type provides a secure wrapper around a `[u8; N]` array that can be safely cloned
18/// while ensuring the underlying data is properly zeroized when no longer needed.
19/// Use this for cryptographic keys, nonces, or other fixed-size secret data.
20///
21/// # Examples
22///
23/// ```
24/// # #[cfg(feature = "zeroize")]
25/// # {
26/// use secure_gate::{CloneableArray, ExposeSecret};
27///
28/// // Create from an array
29/// let key: CloneableArray<32> = [42u8; 32].into();
30///
31/// // Access the inner array
32/// let inner = &key.expose_secret().0;
33/// assert_eq!(inner.len(), 32);
34/// # }
35/// ```
36pub type CloneableArray<const N: usize> = Fixed<CloneableArrayInner<N>>;
37
38impl<const N: usize> CloneableArray<N> {
39    /// Construct a cloneable array secret by building it in a closure.
40    ///
41    /// Same stack-minimization benefits as `CloneableString::init_with`.
42    ///
43    /// # Example
44    ///
45    /// ```
46    /// # #[cfg(feature = "zeroize")]
47    /// # {
48    /// use secure_gate::CloneableArray;
49    ///
50    /// let key = CloneableArray::<32>::init_with(|| {
51    ///     let mut arr = [0u8; 32];
52    ///     // Fill from some source...
53    ///     arr
54    /// });
55    /// # }
56    /// ```
57    #[must_use]
58    pub fn init_with<F>(constructor: F) -> Self
59    where
60        F: FnOnce() -> [u8; N],
61    {
62        let mut tmp = constructor();
63        let secret = Self::from(tmp);
64        tmp.zeroize();
65        secret
66    }
67
68    /// Fallible version of `init_with`.
69    ///
70    /// Same stack-minimization benefits as `init_with`, but allows for construction
71    /// that may fail with an error. Useful when reading secrets from fallible sources
72    /// like files or network connections.
73    pub fn try_init_with<F, E>(constructor: F) -> Result<Self, E>
74    where
75        F: FnOnce() -> Result<[u8; N], E>,
76    {
77        let mut tmp = constructor()?;
78        let secret = Self::from(tmp);
79        tmp.zeroize();
80        Ok(secret)
81    }
82}
83
84impl<const N: usize> From<[u8; N]> for CloneableArray<N> {
85    /// Wrap a `[u8; N]` array in a `CloneableArray`.
86    fn from(arr: [u8; N]) -> Self {
87        Fixed::new(CloneableArrayInner(arr))
88    }
89}