use std::cell::RefCell;
use std::io::{self, Cursor, Seek, SeekFrom, Write};
use std::rc::Rc;
use tiff::encoder::{Compression, DeflateLevel, Rational, TiffEncoder, colortype::RGBA8};
use tiff::tags::ResolutionUnit;
use crate::RenderError;
#[derive(Clone, Default)]
struct Shared(Rc<RefCell<Cursor<Vec<u8>>>>);
impl Write for Shared {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.borrow_mut().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl Seek for Shared {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
self.0.borrow_mut().seek(pos)
}
}
pub struct TiffWriter {
encoder: TiffEncoder<Shared>,
file: Shared,
}
impl std::fmt::Debug for TiffWriter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TiffWriter")
.field("bytes", &self.file.0.borrow().get_ref().len())
.finish_non_exhaustive()
}
}
impl TiffWriter {
pub fn new() -> Result<Self, RenderError> {
let file = Shared::default();
let encoder = TiffEncoder::new(file.clone())
.map_err(|_| failed())?
.with_compression(Compression::Deflate(DeflateLevel::Balanced));
Ok(Self { encoder, file })
}
pub fn add_page(&mut self, width: u32, height: u32, rgba: &[u8], dpi: f64) -> Result<(), RenderError> {
let expected = u64::from(width) * u64::from(height) * 4;
if width == 0 || height == 0 || rgba.len() as u64 != expected {
return Err(RenderError::InvalidRequest {
what: "a TIFF page's pixels must be width × height × 4 bytes of RGBA",
});
}
if !dpi.is_finite() || dpi <= 0.0 {
return Err(RenderError::InvalidRequest {
what: "a TIFF page's resolution must be a positive number of pixels per inch",
});
}
let mut image = self.encoder.new_image::<RGBA8>(width, height).map_err(|_| failed())?;
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "clamped to u32's range first"
)]
let hundredths = (dpi * 100.0).round().clamp(1.0, f64::from(u32::MAX)) as u32;
image.resolution(ResolutionUnit::Inch, Rational { n: hundredths, d: 100 });
image.write_data(rgba).map_err(|_| failed())
}
#[must_use]
pub fn finish(self) -> Vec<u8> {
let Self { encoder, file } = self;
drop(encoder);
match Rc::try_unwrap(file.0) {
Ok(cell) => cell.into_inner().into_inner(),
Err(shared) => shared.borrow().get_ref().clone(),
}
}
}
fn failed() -> RenderError {
RenderError::ExportFailed { format: "tiff" }
}