#![forbid(unsafe_code)]
use crate::common::errors::EncodeError;
use crate::common::types::Encoded;
pub trait BarcodeEncoder {
type Input: ?Sized;
fn encode_into(input: &Self::Input, buf: &mut [bool]) -> Result<Encoded, EncodeError>;
fn symbology_name() -> &'static str;
#[cfg(feature = "alloc")]
fn encode(input: &Self::Input) -> Result<crate::common::types::BarcodeOutput, EncodeError> {
use crate::common::types::{BarcodeOutput, LinearBarcode, MatrixBarcode};
use alloc::{vec, vec::Vec};
let mut buf: Vec<bool> = vec![false; 128];
loop {
match Self::encode_into(input, &mut buf) {
Ok(Encoded::Linear { len, height }) => {
buf.truncate(len);
return Ok(BarcodeOutput::Linear(LinearBarcode {
bars: buf,
height,
text: None,
}));
}
Ok(Encoded::Matrix { width, height }) => {
let mut modules: Vec<Vec<bool>> = Vec::with_capacity(height);
for row in 0..height {
modules.push(buf[row * width..(row + 1) * width].to_vec());
}
return Ok(BarcodeOutput::Matrix(MatrixBarcode {
modules,
width,
height,
}));
}
Err(EncodeError::BufferTooSmall) => {
let bigger = buf.len().saturating_mul(2);
buf.clear();
buf.resize(bigger, false);
}
Err(e) => return Err(e),
}
}
}
}