use std::convert::TryInto;
pub trait Storable {
fn to_bytes(&self) -> std::borrow::Cow<[u8]>;
fn from_bytes(bytes: Vec<u8>) -> Self;
}
impl Storable for () {
fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
std::borrow::Cow::Borrowed(&[])
}
fn from_bytes(bytes: Vec<u8>) -> Self {
assert!(bytes.is_empty());
}
}
impl Storable for Vec<u8> {
fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
std::borrow::Cow::Borrowed(self)
}
fn from_bytes(bytes: Vec<u8>) -> Self {
bytes
}
}
impl Storable for String {
fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
std::borrow::Cow::Borrowed(self.as_bytes())
}
fn from_bytes(bytes: Vec<u8>) -> Self {
String::from_utf8(bytes).unwrap()
}
}
impl Storable for u128 {
fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
std::borrow::Cow::Owned(self.to_be_bytes().to_vec())
}
fn from_bytes(bytes: Vec<u8>) -> Self {
Self::from_be_bytes(bytes.try_into().unwrap())
}
}
impl Storable for u64 {
fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
std::borrow::Cow::Owned(self.to_be_bytes().to_vec())
}
fn from_bytes(bytes: Vec<u8>) -> Self {
Self::from_be_bytes(bytes.try_into().unwrap())
}
}
impl Storable for u32 {
fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
std::borrow::Cow::Owned(self.to_be_bytes().to_vec())
}
fn from_bytes(bytes: Vec<u8>) -> Self {
Self::from_be_bytes(bytes.try_into().unwrap())
}
}
impl Storable for u16 {
fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
std::borrow::Cow::Owned(self.to_be_bytes().to_vec())
}
fn from_bytes(bytes: Vec<u8>) -> Self {
Self::from_be_bytes(bytes.try_into().unwrap())
}
}
impl Storable for u8 {
fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
std::borrow::Cow::Owned(self.to_be_bytes().to_vec())
}
fn from_bytes(bytes: Vec<u8>) -> Self {
Self::from_be_bytes(bytes.try_into().unwrap())
}
}