sskr/
secret.rs

1use crate::{SSKRError, MIN_SECRET_LEN, MAX_SECRET_LEN};
2
3/// A secret to be split into shares.
4#[derive(Clone, Debug, Eq, PartialEq)]
5pub struct Secret(Vec<u8>);
6
7impl Secret {
8    /// Creates a new `Secret` instance with the given data.
9    ///
10    /// # Arguments
11    ///
12    /// * `data` - The secret data to be split into shares.
13    ///
14    /// # Errors
15    ///
16    /// Returns an error if the length of the secret is less than `MIN_SECRET_LEN`, greater than `MAX_SECRET_LEN`,
17    /// or not even.
18    pub fn new<T>(data: T) -> Result<Self, SSKRError>
19    where
20        T: AsRef<[u8]>,
21    {
22        let data = data.as_ref();
23        let len = data.len();
24        if len < MIN_SECRET_LEN {
25            return Err(SSKRError::SecretTooShort);
26        }
27        if len > MAX_SECRET_LEN {
28            return Err(SSKRError::SecretTooLong);
29        }
30        if len & 1 != 0 {
31            return Err(SSKRError::SecretLengthNotEven);
32        }
33        Ok(Self(data.to_vec()))
34    }
35
36    /// Returns the length of the secret.
37    pub fn len(&self) -> usize {
38        self.0.len()
39    }
40
41    /// Returns `true` if the secret is empty.
42    pub fn is_empty(&self) -> bool {
43        self.len() == 0
44    }
45
46    /// Returns a reference to the secret data.
47    pub fn data(&self) -> &[u8] {
48        &self.0
49    }
50}
51
52impl AsRef<[u8]> for Secret {
53    /// Returns a reference to the secret data.
54    fn as_ref(&self) -> &[u8] {
55        &self.0
56    }
57}