1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// SPDX-License-Identifier: GPL-3.0-or-later
use crate::FBError;
use base64::prelude::{BASE64_STANDARD, Engine};
use bincode::{Options, DefaultOptions};

/// A key object that is specific to a message.
pub struct FBKey {
	pub(crate) indices: Vec<Vec<(usize, usize)>>,
}

impl FBKey {

	/// Returns the byte representation of the key.
	pub fn as_bytes(&self) -> Vec<u8> {
		let binc = DefaultOptions::new();
		binc.serialize(&self.indices)
			.expect("Should be fine")
	}

	/// Returns the base64 encoded representation of the key.
	pub fn as_base64(&self) -> String {
		BASE64_STANDARD.encode(&self.as_bytes())
	}

	/// Constructs the key from the provided bytes.
	/// # Errors
	/// [DecodeError](FBError::DecodeError)
	pub fn from_bytes(fbkey: &[u8]) -> Result<FBKey, FBError> {
		let binc = DefaultOptions::new();
		let indices: Vec<_> = binc.deserialize(&fbkey)
			.map_err(|_| FBError::DecodeError)?;
		if indices.len() < 2 {
			return Err(FBError::DecodeError);
		}

		Ok (FBKey {indices})
	}

	/// Constructs the key from the provided base64 encoded form.
	/// # Errors
	/// [DecodeError](FBError::DecodeError)
	pub fn from_base64(key_str: &str) -> Result<FBKey, FBError> {
		let indice_bytes = BASE64_STANDARD.decode(key_str)
			.map_err(|_| FBError::DecodeError)?;

		Self::from_bytes(&indice_bytes)
	}
}