From 9a23090b6e7b09729c9e03b16382e97738a154f5 Mon Sep 17 00:00:00 2001 From: "A. Molzer" <5550310+197g@users.noreply.github.com> Date: Sun, 11 Jan 2026 22:30:20 +0100 Subject: [PATCH] Provide write_entry_bytes This complements the entry API of the encoder with the byte slice based method. Note we don't provide it for writing raw data, here a `std::io::Write` would be more appropriate and we should not attempt to make it `write_all`, nor compress. You'd get all the benefits of the other API through `[u8]: TiffValue` since that interface is otherwise type agnostic and `u8` specifically is endian agnostic. --- src/encoder/mod.rs | 27 +++++++++++++++++++++++++++ src/error.rs | 4 ++++ 2 files changed, 31 insertions(+) diff --git a/src/encoder/mod.rs b/src/encoder/mod.rs index 712326e..8f1cb20 100644 --- a/src/encoder/mod.rs +++ b/src/encoder/mod.rs @@ -396,6 +396,33 @@ impl<'a, W: 'a + Write + Seek, K: TiffKind> DirectoryEncoder<'a, W, K> { ) } + /// Write a directory entry by its byte data. + /// + /// The data must be pre-formatted to the byte order expected by the file. + /// + /// Returns an [`Entry`]. If the value is short enough it will *not* be written in the file but + /// stored in the entry's offset field. + pub fn write_entry_bytes(&mut self, ty: Type, data: &[u8]) -> TiffResult { + if data.len() % usize::from(ty.byte_len()) != 0 { + return Err(TiffError::UsageError(UsageError::MismatchedEntryLength { + ty, + found: data.len(), + })); + } + + let count = data.len() / usize::from(ty.byte_len()); + let count = u64::try_from(count)?; + + Self::write_entry_inner( + self.writer, + DirectoryEntry { + data_type: ty, + count: K::convert_offset(count)?, + data: data.into(), + }, + ) + } + /// Insert previously written key-value entries. /// /// It is the caller's responsibility to ensure that the data referred to by the entries is diff --git a/src/error.rs b/src/error.rs index 94dc468..9311915 100644 --- a/src/error.rs +++ b/src/error.rs @@ -5,6 +5,7 @@ use std::string; use quick_error::quick_error; use crate::decoder::ChunkType; +use crate::tags::Type; use crate::tags::{ CompressionMethod, PhotometricInterpretation, PlanarConfiguration, SampleFormat, Tag, }; @@ -211,6 +212,9 @@ quick_error! { ByteOrderMismatch { display("attempted to use data with a byte order that does not match the required one") } + MismatchedEntryLength {ty: Type, found: usize } { + display("the length of data is not a multiple of the size of the type {ty:?}, found {found}") + } } }