· 7 years ago · May 07, 2018, 08:28 AM
1use base64;
2use failure;
3
4#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
5struct Bytes(Vec<u8>);
6
7impl Bytes {
8 fn bytes(&self) -> &[u8] {
9 &self.0
10 }
11 fn bytes_mut(&mut self) -> &mut [u8] {
12 &mut self.0
13 }
14 fn into_bytes(self) -> Vec<u8> {
15 self.0
16 }
17}
18
19#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
20pub enum SecretKey {
21 Some(Bytes),
22 None,
23}
24
25impl SecretKey {
26 // constructors
27 pub fn from_base64_encoded_string(s: String) -> Result<SecretKey, failure::Error> {
28 let b = base64::decode_config(&s, base64::STANDARD)?;
29 Ok(SecretKey::Some(Bytes(b)))
30 }
31 pub fn from_string(s: String) -> SecretKey {
32 SecretKey::Some(Bytes(s.into_bytes()))
33 }
34 pub fn from_bytes(b: Vec<u8>) -> SecretKey {
35 SecretKey::Some(Bytes(b))
36 }
37
38 // getters
39 pub fn bytes(&self) -> &[u8] {
40 match *self {
41 SecretKey::Some(ref b) => b.bytes(),
42 SecretKey::None => &[],
43 }
44 }
45 pub fn bytes_mut(&mut self) -> &mut [u8] {
46 match *self {
47 SecretKey::Some(ref mut b) => b.bytes_mut(),
48 SecretKey::None => &mut [],
49 }
50 }
51 pub fn into_bytes(self) -> Vec<u8> {
52 match self {
53 SecretKey::Some(b) => b.into_bytes(),
54 SecretKey::None => vec![],
55 }
56 }
57}