1use 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#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
13pub struct FbKey(pub(crate) Vec<Vec<(usize, usize)>>);
14
15
16impl FbKey {
17
18 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 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 #[cfg(feature = "base64")]
42 pub fn to_base64(&self) -> String {
43 BASE64_STANDARD.encode(&self.to_bytes())
44 }
45
46 #[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}