use crate::CborOwned;
use std::marker::PhantomData;
mod encoder;
mod low_level;
mod writer;
mod writers;
pub use encoder::Encoder;
use low_level::*;
pub use writer::Writer;
pub use writers::{ArrayWriter, DictWriter, KeyBuilder, SingleBuilder, SingleResult};
pub trait CborOutput {
type Output;
fn output(bytes: &[u8]) -> Self::Output;
}
pub struct WithOutput;
impl CborOutput for WithOutput {
type Output = CborOwned;
fn output(bytes: &[u8]) -> Self::Output {
CborOwned::unchecked(bytes)
}
}
pub struct NoOutput;
impl CborOutput for NoOutput {
type Output = ();
fn output(_bytes: &[u8]) -> Self::Output {}
}
pub struct CborBuilder<'a, O: CborOutput> {
bytes: Bytes<'a>,
max_definite: Option<u64>,
ph: PhantomData<O>,
}
impl Default for CborBuilder<'static, WithOutput> {
fn default() -> Self {
Self::new()
}
}
impl<'a> CborBuilder<'a, WithOutput> {
pub fn new() -> Self {
Self {
bytes: Bytes::Owned(Vec::new()),
max_definite: Some(255),
ph: PhantomData,
}
}
pub fn with_scratch_space(v: &'a mut Vec<u8>) -> Self {
v.clear();
Self {
bytes: Bytes::Borrowed(v),
max_definite: Some(255),
ph: PhantomData,
}
}
}
impl<'a> CborBuilder<'a, NoOutput> {
pub fn append_to(v: &'a mut Vec<u8>) -> Self {
Self {
bytes: Bytes::Borrowed(v),
max_definite: Some(255),
ph: PhantomData,
}
}
}
impl<'a, O: CborOutput> CborBuilder<'a, O> {
pub fn with_max_definite_size(self, max_definite: Option<u64>) -> Self {
Self {
bytes: self.bytes,
max_definite,
ph: PhantomData,
}
}
}
impl<'a, O: CborOutput> Writer for CborBuilder<'a, O> {
type Output = O::Output;
fn bytes<T>(&mut self, f: impl FnOnce(&mut Vec<u8>) -> T) -> T {
f(self.bytes.as_mut())
}
fn into_output(self) -> Self::Output {
O::output(self.bytes.as_slice())
}
fn max_definite(&self) -> Option<u64> {
self.max_definite
}
fn set_max_definite(&mut self, max: Option<u64>) {
self.max_definite = max;
}
}