use crate::FbError;
use bincode::{Options, DefaultOptions};
#[cfg(feature = "base64")]
use base64::prelude::{BASE64_STANDARD, Engine};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FbKey(pub(crate) Vec<Vec<(usize, usize)>>);
impl FbKey {
pub fn to_bytes(&self) -> Vec<u8> {
let binc = DefaultOptions::new();
binc.serialize(&self.0)
.expect("Should be fine")
}
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))
}
#[cfg(feature = "base64")]
pub fn to_base64(&self) -> String {
BASE64_STANDARD.encode(&self.to_bytes())
}
#[cfg(feature = "base64")]
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)
}
}