use crate::assemble;
use crate::error::{Error, Result};
use crate::format::Format;
use crate::formats;
use crate::options::ConvertOptions;
use crate::report::{Converted, Report};
use std::io::{Read, Write};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Converter {
options: ConvertOptions,
}
impl Converter {
#[cfg(feature = "export")]
pub fn export(book: &mbook::Book, format: Format, sink: impl Write) -> Result<()> {
crate::export::write(book, format, sink)
}
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_options(options: ConvertOptions) -> Self {
Self { options }
}
pub fn convert(&self, source: impl Read, sink: impl Write) -> Result<Report> {
let converted = self.load(source)?;
self.write(converted, sink)
}
pub fn convert_slice(&self, source: &[u8], sink: impl Write) -> Result<Report> {
let converted = self.load_slice(source)?;
self.write(converted, sink)
}
pub fn load(&self, source: impl Read) -> Result<Converted> {
let limit = self.options.limits.max_source_bytes;
let mut bytes = Vec::new();
source
.take(limit.saturating_add(1))
.read_to_end(&mut bytes)?;
self.load_slice(&bytes)
}
pub fn load_slice(&self, source: &[u8]) -> Result<Converted> {
let fits = u64::try_from(source.len())
.is_ok_and(|len| len <= self.options.limits.max_source_bytes);
if !fits {
return Err(Error::Limit("the source is larger than the source limit"));
}
let format = self
.options
.format
.or_else(|| Format::detect(source))
.ok_or(Error::UnknownFormat)?;
let draft = formats::read(format, source, &self.options)?;
let (book, warnings) = assemble::assemble(draft, source, &self.options)?;
Ok(Converted {
book,
report: Report { format, warnings },
})
}
fn write(&self, converted: Converted, sink: impl Write) -> Result<Report> {
converted.book.write_with(sink, &self.options.write)?;
Ok(converted.report)
}
}