false_bottom/
fbkey.rs

1// SPDX-License-Identifier: GPL-3.0-or-later
2use crate::FbError;
3use bincode::{Options, DefaultOptions};
4
5#[cfg(feature = "base64")]
6use base64::prelude::{BASE64_STANDARD, Engine};
7
8#[cfg(feature = "serde")]
9use serde::{Deserialize, Serialize};
10
11/// An object that represents a message specific key.
12#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
13pub struct FbKey(pub(crate) Vec<Vec<(usize, usize)>>);
14
15
16impl FbKey {
17
18	/// Returns the byte representation of the message specific key.
19	pub fn to_bytes(&self) -> Vec<u8> {
20		let binc = DefaultOptions::new();
21
22		binc.serialize(&self.0)
23			.expect("Should be fine")
24	}
25
26	/// Constructs the message specific key from the provided bytes.
27	/// # Errors
28	/// [DecodeError](FbError::DecodeError)
29	pub fn from_bytes(fbkey: &[u8]) -> Result<FbKey, FbError> {
30		let binc = DefaultOptions::new();
31		let indices: Vec<_> = binc.deserialize(&fbkey)
32			.map_err(|_| FbError::DecodeError)?;
33		if indices.len() < 2 {
34			return Err(FbError::DecodeError);
35		}
36
37		Ok (FbKey(indices))
38	}
39
40	/// Returns the base64 encoded representation of the message specific key.
41	#[cfg(feature = "base64")]
42	pub fn to_base64(&self) -> String {
43		BASE64_STANDARD.encode(&self.to_bytes())
44	}
45
46	/// Constructs the message specific key from the provided base64 encoded form.
47	/// # Errors
48	/// [DecodeError](FbError::DecodeError)
49	#[cfg(feature = "base64")]
50	pub fn from_base64(key_str: &str) -> Result<FbKey, FbError> {
51		let indice_bytes = BASE64_STANDARD.decode(key_str)
52			.map_err(|_| FbError::DecodeError)?;
53
54		Self::from_bytes(&indice_bytes)
55	}
56}