use crate::command::Command;
use crate::dialect::Dialect;
use crate::error::Result;
#[derive(Debug, Clone, Default)]
pub struct Encoder<D> {
dialect: D,
}
impl<D: Dialect> Encoder<D> {
#[must_use]
pub const fn new(dialect: D) -> Self {
Self { dialect }
}
#[must_use]
pub const fn dialect(&self) -> &D {
&self.dialect
}
#[must_use]
pub fn into_dialect(self) -> D {
self.dialect
}
pub fn encode_one(&self, cmd: &Command, buf: &mut Vec<u8>) -> Result<()> {
self.dialect.encode(cmd, buf)
}
pub fn encode_into<'a, I>(&self, commands: I, buf: &mut Vec<u8>) -> Result<()>
where
I: IntoIterator<Item = &'a Command>,
{
for cmd in commands {
self.dialect.encode(cmd, buf)?;
}
Ok(())
}
pub fn encode(&self, commands: &[Command]) -> Result<Vec<u8>> {
let mut buf = Vec::with_capacity(commands.len() * 16);
self.encode_into(commands, &mut buf)?;
Ok(buf)
}
}
#[cfg(feature = "escpos")]
impl Encoder<crate::dialect::escpos::EscPos> {
#[must_use]
pub fn escpos() -> Self {
Self::new(crate::dialect::escpos::EscPos::new())
}
}
#[cfg(feature = "star")]
impl Encoder<crate::dialect::star::Star> {
#[must_use]
pub fn star() -> Self {
Self::new(crate::dialect::star::Star::new())
}
}