use crate::prelude::*;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
pub trait WriteNoStd {
fn write_all(&mut self, buf: &[u8]) -> ser::Result<()>;
fn flush(&mut self) -> ser::Result<()>;
}
#[cfg(feature = "std")]
use std::io::Write;
#[cfg(feature = "std")]
impl<W: Write> WriteNoStd for W {
#[inline(always)]
fn write_all(&mut self, buf: &[u8]) -> ser::Result<()> {
Write::write_all(self, buf).map_err(|_| ser::Error::WriteError)
}
#[inline(always)]
fn flush(&mut self) -> ser::Result<()> {
Write::flush(self).map_err(|_| ser::Error::WriteError)
}
}
#[cfg(not(feature = "std"))]
impl WriteNoStd for Vec<u8> {
fn write_all(&mut self, buf: &[u8]) -> ser::Result<()> {
self.extend_from_slice(buf);
Ok(())
}
fn flush(&mut self) -> ser::Result<()> {
Ok(())
}
}
pub trait WriteWithPos: WriteNoStd {
fn pos(&self) -> usize;
}
#[derive(Debug)]
#[cfg_attr(feature = "mem_dbg", derive(mem_dbg::MemDbg, mem_dbg::MemSize))]
pub struct WriterWithPos<'a, F: WriteNoStd> {
backend: &'a mut F,
pos: usize,
}
impl<'a, F: WriteNoStd> WriterWithPos<'a, F> {
#[inline(always)]
pub const fn new(backend: &'a mut F) -> Self {
Self { backend, pos: 0 }
}
}
impl<F: WriteNoStd> WriteNoStd for WriterWithPos<'_, F> {
#[inline(always)]
fn write_all(&mut self, buf: &[u8]) -> ser::Result<()> {
self.backend.write_all(buf)?;
self.pos += buf.len();
Ok(())
}
#[inline(always)]
fn flush(&mut self) -> ser::Result<()> {
self.backend.flush()
}
}
impl<F: WriteNoStd> WriteWithPos for WriterWithPos<'_, F> {
#[inline(always)]
fn pos(&self) -> usize {
self.pos
}
}