secure_gate/cloneable/
vec.rs

1use crate::Dynamic;
2use zeroize::Zeroize;
3
4#[cfg(feature = "zeroize")]
5#[derive(Clone, Zeroize)]
6#[zeroize(drop)]
7pub struct CloneableVecInner(Vec<u8>);
8
9#[cfg(feature = "zeroize")]
10impl crate::CloneableSecretMarker for CloneableVecInner {}
11
12#[cfg(feature = "zeroize")]
13pub type CloneableVec = Dynamic<CloneableVecInner>;
14
15#[cfg(feature = "zeroize")]
16impl CloneableVec {
17    #[inline(always)]
18    pub const fn expose_inner(&self) -> &Vec<u8> {
19        &self.expose_secret().0
20    }
21
22    #[inline(always)]
23    pub fn expose_inner_mut(&mut self) -> &mut Vec<u8> {
24        &mut self.expose_secret_mut().0
25    }
26
27    /// Construct a cloneable vec secret by building it in a closure.
28    ///
29    /// Same stack-minimization benefits as `CloneableString::init_with`.
30    ///
31    /// # Example
32    ///
33    /// ```
34    /// # #[cfg(feature = "zeroize")]
35    /// # {
36    /// use secure_gate::CloneableVec;
37    ///
38    /// let seed = CloneableVec::init_with(|| {
39    ///     let mut v = vec![0u8; 32];
40    ///     // Fill from some source...
41    ///     v
42    /// });
43    /// # }
44    /// ```
45    #[must_use]
46    pub fn init_with<F>(constructor: F) -> Self
47    where
48        F: FnOnce() -> Vec<u8>,
49    {
50        let mut tmp = constructor();
51        let secret = Self::from(tmp.clone());
52        tmp.zeroize();
53        secret
54    }
55
56    /// Fallible version of `init_with`.
57    pub fn try_init_with<F, E>(constructor: F) -> Result<Self, E>
58    where
59        F: FnOnce() -> Result<Vec<u8>, E>,
60    {
61        let mut tmp = constructor()?;
62        let secret = Self::from(tmp.clone());
63        tmp.zeroize();
64        Ok(secret)
65    }
66}
67
68#[cfg(feature = "zeroize")]
69impl From<Vec<u8>> for CloneableVec {
70    fn from(value: Vec<u8>) -> Self {
71        Dynamic::new(CloneableVecInner(value))
72    }
73}
74
75#[cfg(feature = "zeroize")]
76impl From<&[u8]> for CloneableVec {
77    fn from(value: &[u8]) -> Self {
78        Self::from(value.to_vec())
79    }
80}