use crate::errors::Result;
use encoding_rs::{Encoding, UTF_8};
#[derive(Clone)]
pub struct Encoder {
codec: &'static Encoding,
allow_unencodable: bool,
}
impl Default for Encoder {
fn default() -> Self {
Encoder {
codec: UTF_8,
allow_unencodable: false,
}
}
}
impl Encoder {
pub fn new(codec: &'static Encoding) -> Self {
Self {
codec,
allow_unencodable: false,
}
}
pub fn allow_unencodable(mut self, yes: bool) -> Self {
self.allow_unencodable = yes;
self
}
pub(crate) fn encode(&self, data: &str) -> Result<Vec<u8>> {
let (output, _, unmappable) = self.codec.encode(data);
if unmappable && !self.allow_unencodable {
return Err(crate::errors::PrinterError::Input(format!(
"invalid {}",
self.codec.name()
)));
}
Ok(output.into())
}
}