tga: share footerless top-left sequence writing

This commit is contained in:
Dylan M. Taylor
2026-11-22 12:19:21 -05:00
parent 1507e63e6a
commit 9f18c4e96c
4 changed files with 97 additions and 2 deletions
Generated
+1
View File
@@ -3456,6 +3456,7 @@ dependencies = [
name = "craft-tga"
version = "0.1.0"
dependencies = [
"image",
"thiserror 2.0.21",
]
+4 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-tga"
description = "Clean-room Truevision Targa (TGA) reader and run-length writer: true-colour, grayscale and colour-mapped pictures, any origin, packets that end with their scan line."
description = "Clean-room Truevision Targa (TGA) reader and writer: true-colour, grayscale and colour-mapped pictures, any origin, packets that end with their scan line."
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -12,3 +12,6 @@ workspace = true
[dependencies]
thiserror = { workspace = true }
[dev-dependencies]
image = { version = "0.25", default-features = false, features = ["tga"] }
+47 -1
View File
@@ -13,7 +13,7 @@
//! (types 10 and 11), rows stored bottom-up (the bottom-left origin every reader assumes, also
//! those that ignore the origin bits), alpha bits in the descriptor and the TGA 2.0 footer. A
//! packet never crosses a scan line: TGA 2.0 forbids it, and readers that decode a row at a time
//! misread files that do.
//! misread files that do. The top-left writer also supports a footerless, uncompressed compatibility stream.
//!
//! Input is treated as hostile: the picture size is capped by [`Limits`], and a run-length file
//! must be long enough to hold the pixels its header declares before anything is allocated.
@@ -430,6 +430,52 @@ fn unpack_rle(mut data: &[u8], pixels: usize, bpp: usize) -> Result<Vec<u8>> {
Ok(out)
}
/// Write packed 8-bit grayscale, RGB, or RGBA as a footerless, uncompressed top-left Targa.
///
/// Rows and pixels arrive in display order. RGB and RGBA are stored as BGR and BGRA;
/// alpha bytes are copied verbatim. Dimensions, sample length, and the one-row conversion
/// buffer are checked before any output is written. The caller owns flushing the sink.
pub fn write_top_left_raw(mut out: impl std::io::Write, width: u32, height: u32, layout: Layout, data: &[u8]) -> Result<()> {
let (image_type, bits, alpha_bits) = match layout {
Layout::Gray => (3, 8, 0),
Layout::Rgb => (2, 24, 0),
Layout::Rgba => (2, 32, 8),
Layout::GrayAlpha => return Err(Error::Encode("footerless writer accepts grayscale, RGB or RGBA".into())),
};
let (Ok(w), Ok(h)) = (u16::try_from(width), u16::try_from(height)) else {
return Err(Error::Encode(format!("dimensions exceed 65535x65535: {width}x{height}")));
};
let bpp = layout.channels();
let row_len = usize::from(w) * bpp;
if w == 0 || h == 0 || row_len.checked_mul(usize::from(h)) != Some(data.len()) {
return Err(Error::Encode("invalid dimensions or buffer size mismatch".into()));
}
let mut row = Vec::new();
if bpp >= 3 {
row.try_reserve_exact(row_len).map_err(|_| Error::Encode("row allocation failed".into()))?;
}
let mut header = [0u8; HEADER];
header[2] = image_type;
header[12..14].copy_from_slice(&w.to_le_bytes());
header[14..16].copy_from_slice(&h.to_le_bytes());
header[16] = bits;
header[17] = 0x20 | alpha_bits;
let io_err = |err: std::io::Error| Error::Encode(err.to_string());
out.write_all(&header).map_err(io_err)?;
if bpp == 1 {
return out.write_all(data).map_err(io_err);
}
for line in data.chunks_exact(row_len) {
row.clear();
row.extend_from_slice(line);
for pixel in row.chunks_exact_mut(bpp) {
pixel.swap(0, 2);
}
out.write_all(&row).map_err(io_err)?;
}
Ok(())
}
/// Encodes 8-bit pixels (`height` rows of `width × layout.channels()` bytes, top row first) as a
/// run-length encoded Targa.
pub fn encode(width: u32, height: u32, layout: Layout, data: &[u8]) -> Result<Vec<u8>> {
+45
View File
@@ -267,3 +267,48 @@ fn aggregate_decode_budget_counts_raw_and_palette_storage() {
limits.max_decoded_bytes = 9;
assert_eq!(decode(&file, &limits).unwrap().rgba, [255, 0, 0, 255]);
}
#[test]
fn raw_top_left_matches_previous_sequence_encoder_for_every_layout() -> std::result::Result<(), Box<dyn std::error::Error>> {
use image::{ExtendedColorType, ImageEncoder, codecs::tga::TgaEncoder};
// Original generated samples, with distinguishing rows and non-opaque alpha.
for (layout, color, data) in [
(Layout::Gray, ExtendedColorType::L8, &[9, 19, 40, 80][..]),
(Layout::Rgb, ExtendedColorType::Rgb8, &[3, 5, 8, 13, 21, 34, 55, 89, 144, 150, 190, 247][..]),
(Layout::Rgba, ExtendedColorType::Rgba8, &[3, 5, 8, 13, 21, 34, 55, 89, 144, 150, 190, 247, 17, 31, 127, 1][..]),
] {
let mut legacy = Vec::new();
TgaEncoder::new(&mut legacy).disable_rle().write_image(data, 2, 2, color)?;
let mut shared = Vec::new();
write_top_left_raw(&mut shared, 2, 2, layout, data)?;
assert_eq!(shared, legacy, "{layout:?}");
assert_eq!(shared.len(), 18 + data.len(), "no footer");
}
Ok(())
}
#[test]
fn raw_top_left_rejects_bad_input_before_touching_the_sink() {
let mut output = Vec::new();
for (w, h, layout, data) in [
(0, 1, Layout::Gray, &[][..]),
(1, 0, Layout::Gray, &[][..]),
(u32::from(u16::MAX) + 1, 1, Layout::Rgb, &[][..]),
(u32::from(u16::MAX), u32::from(u16::MAX), Layout::Rgba, &[][..]),
(1, 1, Layout::GrayAlpha, &[1, 2][..]),
(1, 1, Layout::Rgba, &[0; 3][..]),
(1, 1, Layout::Rgba, &[0; 5][..]),
] {
assert!(write_top_left_raw(&mut output, w, h, layout, data).is_err());
}
assert!(output.is_empty());
}
#[test]
fn raw_top_left_reports_header_and_pixel_write_errors() {
for size in [17, 20] {
let mut bytes = [0; 20];
assert!(matches!(write_top_left_raw(&mut bytes[..size], 1, 1, Layout::Rgb, &[9, 19, 40]), Err(Error::Encode(_))));
}
}