use core::marker::PhantomData;
use crate::mode::Text;
use crate::{Context, Encode};
use super::en::{EncState, Pass, RecordEncoder};
use super::encoding::Config;
#[cfg(feature = "alloc")]
use super::error::Error;
pub struct Writer<W, M = Text> {
cfg: Config,
writer: W,
state: EncState,
_marker: PhantomData<M>,
}
impl<W, M> Writer<W, M>
where
W: crate::Writer,
M: 'static,
{
#[inline]
pub(crate) fn new(cfg: Config, writer: W) -> Self {
Self {
cfg,
writer,
state: EncState::new(),
_marker: PhantomData,
}
}
#[inline]
pub fn serialize_with<C, T>(&mut self, cx: C, value: &T) -> Result<(), C::Error>
where
C: Context,
T: ?Sized + Encode<M>,
{
cx.clear();
T::encode(
value,
RecordEncoder::<_, _, M, _, _>::new(
cx,
self.writer.borrow_mut(),
self.cfg,
&mut self.state,
Some(value),
Pass::Value,
),
)
}
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[inline]
pub fn serialize<T>(&mut self, value: &T) -> Result<(), Error>
where
T: ?Sized + Encode<M>,
{
let cx = crate::context::new().with_error();
self.serialize_with(&cx, value)
}
#[inline]
pub fn get_ref(&self) -> &W {
&self.writer
}
#[inline]
pub fn get_mut(&mut self) -> &mut W {
&mut self.writer
}
#[inline]
pub fn into_inner(self) -> W {
self.writer
}
#[inline]
pub fn finish_with<C>(mut self, cx: C) -> Result<W::Ok, C::Error>
where
C: Context,
{
self.writer.finish(cx)
}
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[inline]
pub fn finish(self) -> Result<W::Ok, Error> {
let cx = crate::context::new().with_error();
self.finish_with(&cx)
}
}