use anyhow::{anyhow,bail};
use std::path::PathBuf;
use crate::common;
use crate::header::*;
use bincode::config::*;
use std::io::{
Read,Write,
BufReader,BufWriter,
};
use once_cell::sync::Lazy;
static ENCODING_OPTIONS: Lazy<WithOtherIntEncoding<DefaultOptions, VarintEncoding>> =
Lazy::new(|| bincode::DefaultOptions::new().with_varint_encoding());
common::impl_macro_binary!(Bincode, "bin");
pub unsafe trait Bincode: serde::Serialize + serde::de::DeserializeOwned {
#[doc(hidden)]
#[inline(always)]
fn __from_file() -> Result <Self, anyhow::Error> {
let path = Self::absolute_path()?;
let mut file = std::fs::File::open(path)?;
Self::from_reader(&mut file)
}
#[doc(hidden)]
#[inline(always)]
fn __from_path(path: &std::path::Path) -> Result <Self, anyhow::Error> {
let mut file = std::fs::File::open(path)?;
Self::from_reader(&mut file)
}
#[inline(always)]
fn from_bytes(bytes: &[u8]) -> Result<Self, anyhow::Error> {
ensure_header!(bytes);
Ok(ENCODING_OPTIONS.deserialize(&bytes[25..])?)
}
#[inline(always)]
fn to_bytes(&self) -> Result<Vec<u8>, anyhow::Error> {
let mut vec = ENCODING_OPTIONS.serialize(self)?;
header_return!(vec)
}
#[inline(always)]
fn from_reader<R>(reader: &mut R) -> Result<Self, anyhow::Error>
where
R: Read,
{
let mut bytes = [0_u8; 25];
let mut reader = BufReader::new(reader);
reader.read_exact(&mut bytes)?;
ensure_header!(bytes);
Ok(ENCODING_OPTIONS.deserialize_from(&mut reader)?)
}
#[inline(always)]
fn to_writer<W>(&self, writer: &mut W) -> Result<(), anyhow::Error>
where
W: Write,
{
let mut writer = BufWriter::new(writer);
writer.write_all(&Self::full_header())?;
Ok(ENCODING_OPTIONS.serialize_into(&mut writer, self)?)
}
impl_header!();
common::impl_binary!("bincode");
}