zenpng 0.1.4

PNG encoding and decoding with zencodec trait integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
//! PNG encode pipeline: filtering, compression, chunk assembly.

pub(crate) mod apng;
pub(crate) mod compress;
pub(crate) mod filter;
pub(crate) mod metadata;

use alloc::string::ToString;
use alloc::vec;
use alloc::vec::Vec;

use enough::Stop;

use crate::chunk::PNG_SIGNATURE;
use crate::chunk::write::write_chunk;
use crate::error::PngError;
#[allow(unused_imports)]
use whereat::at;

pub(crate) use self::compress::compress_filtered;
pub(crate) use self::metadata::{PngWriteMetadata, metadata_size_estimate, write_all_metadata};

/// Compression options passed through the pipeline.
pub(crate) struct CompressOptions<'a> {
    /// Run screening and refinement phases in parallel.
    pub parallel: bool,
    /// Hard cancel — passed into zenflate/zenzop, aborts mid-compression.
    pub cancel: &'a dyn Stop,
    /// Soft deadline — checked between phases/strategies for graceful early return.
    pub deadline: &'a dyn Stop,
    /// Optional remaining-time query for zopfli iteration calibration.
    /// Returns remaining nanoseconds, or `None` if unknown/unlimited.
    #[allow(dead_code)] // read only with `zopfli` feature
    pub remaining_ns: Option<&'a dyn Fn() -> Option<u64>>,
    /// Maximum thread count for compression. 0 = no limit, 1 = single-threaded.
    pub max_threads: usize,
}

/// Statistics for one compression phase.
#[derive(Clone, Debug)]
#[doc(hidden)]
#[allow(dead_code)]
pub struct PhaseStat {
    pub name: alloc::string::String,
    pub duration_ns: u64,
    pub best_size: usize,
    pub evaluations: u32,
}

/// Collected per-phase statistics from compression.
#[derive(Clone, Debug, Default)]
#[doc(hidden)]
pub struct PhaseStats {
    pub phases: Vec<PhaseStat>,
    pub raw_size: usize,
}

/// Encode palette-indexed pixel data into a complete PNG file.
#[allow(clippy::too_many_arguments)]
pub(crate) fn write_indexed_png(
    indices: &[u8],
    width: u32,
    height: u32,
    palette_rgb: &[u8],
    palette_alpha: Option<&[u8]>,
    write_meta: &PngWriteMetadata<'_>,
    effort: u32,
    opts: CompressOptions<'_>,
) -> crate::error::Result<Vec<u8>> {
    let w = width as usize;
    let h = height as usize;
    let n_colors = palette_rgb.len() / 3;

    if n_colors == 0 || n_colors > 256 {
        return Err(at!(PngError::InvalidInput(alloc::format!(
            "palette must have 1-256 entries, got {n_colors}"
        ))));
    }
    if indices.len() < w * h {
        return Err(at!(PngError::InvalidInput(
            "index buffer too small for dimensions".to_string(),
        )));
    }

    let bit_depth = select_bit_depth(n_colors);
    let packed_rows = pack_all_rows(indices, w, h, bit_depth);
    let row_bytes = packed_row_bytes(w, bit_depth);

    // Compress with multi-strategy filter selection (bpp=1 for indexed)
    let compressed = compress_filtered(&packed_rows, row_bytes, h, 1, effort, opts, None)?;

    // Assemble PNG
    let trns_data = truncate_trns(palette_alpha);
    let est = 8
        + 25
        + (12 + n_colors * 3)
        + trns_data.as_ref().map_or(0, |t| 12 + t.len())
        + (12 + compressed.len())
        + 12
        + metadata_size_estimate(write_meta);
    let mut out = Vec::with_capacity(est);

    out.extend_from_slice(&PNG_SIGNATURE);

    // IHDR
    let mut ihdr = [0u8; 13];
    ihdr[0..4].copy_from_slice(&width.to_be_bytes());
    ihdr[4..8].copy_from_slice(&height.to_be_bytes());
    ihdr[8] = bit_depth;
    ihdr[9] = 3; // indexed color
    write_chunk(&mut out, b"IHDR", &ihdr);

    // Color metadata and generic metadata (before PLTE per PNG spec)
    write_all_metadata(&mut out, write_meta)?;

    // PLTE
    write_chunk(&mut out, b"PLTE", &palette_rgb[..n_colors * 3]);

    // tRNS
    if let Some(trns) = &trns_data {
        write_chunk(&mut out, b"tRNS", trns);
    }

    // IDAT
    write_chunk(&mut out, b"IDAT", &compressed);

    // IEND
    write_chunk(&mut out, b"IEND", &[]);

    Ok(out)
}

/// Encode truecolor/grayscale pixel data into a complete PNG file.
///
/// `trns` is optional tRNS chunk data for binary transparency:
/// - Grayscale: 2 bytes `[0, gray_value]` (big-endian u16)
/// - RGB: 6 bytes `[0, R, 0, G, 0, B]` (3× big-endian u16)
///
/// For sub-byte grayscale (bit_depth < 8), `pixel_bytes` must contain
/// pre-scaled sample values (0..2^bit_depth), one byte per sample.
/// This function handles bit-packing into rows.
#[allow(clippy::too_many_arguments)]
pub(crate) fn write_truecolor_png(
    pixel_bytes: &[u8],
    width: u32,
    height: u32,
    color_type: u8,
    bit_depth: u8,
    trns: Option<&[u8]>,
    write_meta: &PngWriteMetadata<'_>,
    effort: u32,
    opts: CompressOptions<'_>,
) -> crate::error::Result<Vec<u8>> {
    let w = width as usize;
    let h = height as usize;

    // Sub-byte grayscale path: pack samples and compress
    if color_type == 0 && bit_depth < 8 {
        // pixel_bytes has one byte per sample (pre-scaled to bit_depth range)
        let expected_samples = w * h;
        if pixel_bytes.len() < expected_samples {
            return Err(at!(PngError::InvalidInput(alloc::format!(
                "pixel buffer too small: need {expected_samples} samples, got {}",
                pixel_bytes.len()
            ))));
        }
        let packed = pack_all_rows(pixel_bytes, w, h, bit_depth);
        let row_bytes = packed_row_bytes(w, bit_depth);

        let compressed = compress_filtered(&packed, row_bytes, h, 1, effort, opts, None)?;

        let trns_size = trns.map_or(0, |t| 12 + t.len());
        let est =
            8 + 25 + trns_size + (12 + compressed.len()) + 12 + metadata_size_estimate(write_meta);
        let mut out = Vec::with_capacity(est);

        out.extend_from_slice(&PNG_SIGNATURE);

        let mut ihdr = [0u8; 13];
        ihdr[0..4].copy_from_slice(&width.to_be_bytes());
        ihdr[4..8].copy_from_slice(&height.to_be_bytes());
        ihdr[8] = bit_depth;
        ihdr[9] = color_type;
        write_chunk(&mut out, b"IHDR", &ihdr);
        write_all_metadata(&mut out, write_meta)?;

        if let Some(trns_data) = trns {
            write_chunk(&mut out, b"tRNS", trns_data);
        }

        write_chunk(&mut out, b"IDAT", &compressed);
        write_chunk(&mut out, b"IEND", &[]);

        return Ok(out);
    }

    let channels: usize = match color_type {
        0 => 1, // Grayscale
        2 => 3, // RGB
        4 => 2, // GrayscaleAlpha
        6 => 4, // RGBA
        _ => {
            return Err(at!(PngError::InvalidInput(alloc::format!(
                "unsupported PNG color type: {color_type}"
            ))));
        }
    };
    let bytes_per_channel = bit_depth as usize / 8;
    let bpp = channels * bytes_per_channel;
    let row_bytes = w * bpp;

    let expected_len = row_bytes * h;
    if pixel_bytes.len() < expected_len {
        return Err(at!(PngError::InvalidInput(alloc::format!(
            "pixel buffer too small: need {expected_len}, got {}",
            pixel_bytes.len()
        ))));
    }

    // Effort 0 fast path: write zlib stored blocks directly into the PNG output,
    // avoiding a separate compressed Vec allocation. For 42MB images this
    // eliminates one 42MB allocation + copy.
    if effort == 0 {
        let filtered_row = row_bytes + 1;
        let total_filtered = filtered_row * h;
        let num_blocks = if total_filtered == 0 {
            1
        } else {
            total_filtered.div_ceil(65535)
        };
        let idat_data_len = 2 + 5 * num_blocks + total_filtered + 4; // zlib wrapper

        let trns_size = trns.map_or(0, |t| 12 + t.len());
        let est =
            8 + 25 + trns_size + (12 + idat_data_len) + 12 + metadata_size_estimate(write_meta);
        let mut out = Vec::with_capacity(est);

        out.extend_from_slice(&PNG_SIGNATURE);

        let mut ihdr = [0u8; 13];
        ihdr[0..4].copy_from_slice(&width.to_be_bytes());
        ihdr[4..8].copy_from_slice(&height.to_be_bytes());
        ihdr[8] = bit_depth;
        ihdr[9] = color_type;
        write_chunk(&mut out, b"IHDR", &ihdr);
        write_all_metadata(&mut out, write_meta)?;

        if let Some(trns_data) = trns {
            write_chunk(&mut out, b"tRNS", trns_data);
        }

        // Write IDAT chunk directly: length + type + inline zlib data + CRC
        out.extend_from_slice(&(idat_data_len as u32).to_be_bytes());
        out.extend_from_slice(b"IDAT");
        let idat_start = out.len(); // CRC covers type + data

        compress::write_zlib_stored_inline(&mut out, &pixel_bytes[..expected_len], row_bytes, h);

        // CRC-32 over "IDAT" + data
        let crc = zenflate::crc32(zenflate::crc32(0, b"IDAT"), &out[idat_start..]);
        out.extend_from_slice(&crc.to_be_bytes());

        write_chunk(&mut out, b"IEND", &[]);
        return Ok(out);
    }

    // Compress with multi-strategy filter selection
    let compressed = compress_filtered(
        &pixel_bytes[..expected_len],
        row_bytes,
        h,
        bpp,
        effort,
        opts,
        None,
    )?;

    // Assemble PNG
    let trns_size = trns.map_or(0, |t| 12 + t.len());
    let est =
        8 + 25 + trns_size + (12 + compressed.len()) + 12 + metadata_size_estimate(write_meta);
    let mut out = Vec::with_capacity(est);

    out.extend_from_slice(&PNG_SIGNATURE);

    // IHDR
    let mut ihdr = [0u8; 13];
    ihdr[0..4].copy_from_slice(&width.to_be_bytes());
    ihdr[4..8].copy_from_slice(&height.to_be_bytes());
    ihdr[8] = bit_depth;
    ihdr[9] = color_type;
    // ihdr[10] = 0 compression method
    // ihdr[11] = 0 filter method
    // ihdr[12] = 0 interlace method
    write_chunk(&mut out, b"IHDR", &ihdr);

    // Color metadata and generic metadata (before IDAT)
    write_all_metadata(&mut out, write_meta)?;

    // tRNS chunk (after metadata, before IDAT)
    if let Some(trns_data) = trns {
        write_chunk(&mut out, b"tRNS", trns_data);
    }

    // IDAT
    write_chunk(&mut out, b"IDAT", &compressed);

    // IEND
    write_chunk(&mut out, b"IEND", &[]);

    Ok(out)
}

/// Like `write_truecolor_png` but also collects per-phase compression statistics.
#[cfg(feature = "_dev")]
#[allow(clippy::too_many_arguments)]
pub(crate) fn write_truecolor_png_with_stats(
    pixel_bytes: &[u8],
    width: u32,
    height: u32,
    color_type: u8,
    bit_depth: u8,
    trns: Option<&[u8]>,
    write_meta: &PngWriteMetadata<'_>,
    effort: u32,
    opts: CompressOptions<'_>,
    stats: &mut PhaseStats,
) -> crate::error::Result<Vec<u8>> {
    let w = width as usize;
    let h = height as usize;

    // Sub-byte grayscale path
    if color_type == 0 && bit_depth < 8 {
        let expected_samples = w * h;
        if pixel_bytes.len() < expected_samples {
            return Err(at!(PngError::InvalidInput(alloc::format!(
                "pixel buffer too small: need {expected_samples} samples, got {}",
                pixel_bytes.len()
            ))));
        }
        let packed = pack_all_rows(pixel_bytes, w, h, bit_depth);
        let row_bytes = packed_row_bytes(w, bit_depth);

        let compressed = compress_filtered(&packed, row_bytes, h, 1, effort, opts, Some(stats))?;

        let trns_size = trns.map_or(0, |t| 12 + t.len());
        let est =
            8 + 25 + trns_size + (12 + compressed.len()) + 12 + metadata_size_estimate(write_meta);
        let mut out = Vec::with_capacity(est);

        out.extend_from_slice(&PNG_SIGNATURE);

        let mut ihdr = [0u8; 13];
        ihdr[0..4].copy_from_slice(&width.to_be_bytes());
        ihdr[4..8].copy_from_slice(&height.to_be_bytes());
        ihdr[8] = bit_depth;
        ihdr[9] = color_type;
        write_chunk(&mut out, b"IHDR", &ihdr);
        write_all_metadata(&mut out, write_meta)?;
        if let Some(trns_data) = trns {
            write_chunk(&mut out, b"tRNS", trns_data);
        }
        write_chunk(&mut out, b"IDAT", &compressed);
        write_chunk(&mut out, b"IEND", &[]);

        return Ok(out);
    }

    let channels: usize = match color_type {
        0 => 1,
        2 => 3,
        4 => 2,
        6 => 4,
        _ => {
            return Err(at!(PngError::InvalidInput(alloc::format!(
                "unsupported PNG color type: {color_type}"
            ))));
        }
    };
    let bytes_per_channel = bit_depth as usize / 8;
    let bpp = channels * bytes_per_channel;
    let row_bytes = w * bpp;

    let expected_len = row_bytes * h;
    if pixel_bytes.len() < expected_len {
        return Err(at!(PngError::InvalidInput(alloc::format!(
            "pixel buffer too small: need {expected_len}, got {}",
            pixel_bytes.len()
        ))));
    }

    let compressed = compress_filtered(
        &pixel_bytes[..expected_len],
        row_bytes,
        h,
        bpp,
        effort,
        opts,
        Some(stats),
    )?;

    let trns_size = trns.map_or(0, |t| 12 + t.len());
    let est =
        8 + 25 + trns_size + (12 + compressed.len()) + 12 + metadata_size_estimate(write_meta);
    let mut out = Vec::with_capacity(est);

    out.extend_from_slice(&PNG_SIGNATURE);

    let mut ihdr = [0u8; 13];
    ihdr[0..4].copy_from_slice(&width.to_be_bytes());
    ihdr[4..8].copy_from_slice(&height.to_be_bytes());
    ihdr[8] = bit_depth;
    ihdr[9] = color_type;
    write_chunk(&mut out, b"IHDR", &ihdr);

    write_all_metadata(&mut out, write_meta)?;
    if let Some(trns_data) = trns {
        write_chunk(&mut out, b"tRNS", trns_data);
    }
    write_chunk(&mut out, b"IDAT", &compressed);
    write_chunk(&mut out, b"IEND", &[]);

    Ok(out)
}

// ---- Bit depth and packing (indexed only) ----

pub(crate) fn select_bit_depth(n_colors: usize) -> u8 {
    if n_colors <= 2 {
        1
    } else if n_colors <= 4 {
        2
    } else if n_colors <= 16 {
        4
    } else {
        8
    }
}

pub(crate) fn packed_row_bytes(width: usize, bit_depth: u8) -> usize {
    match bit_depth {
        8 => width,
        4 => width.div_ceil(2),
        2 => width.div_ceil(4),
        1 => width.div_ceil(8),
        _ => width,
    }
}

pub(crate) fn pack_all_rows(indices: &[u8], width: usize, height: usize, bit_depth: u8) -> Vec<u8> {
    if bit_depth == 8 {
        return indices[..width * height].to_vec();
    }

    let row_bytes = packed_row_bytes(width, bit_depth);
    let mut packed = vec![0u8; row_bytes * height];
    let ppb = 8 / bit_depth as usize;
    let mask = (1u8 << bit_depth) - 1;

    for y in 0..height {
        let src_row = &indices[y * width..y * width + width];
        let dst_row = &mut packed[y * row_bytes..y * row_bytes + row_bytes];
        for (x, &idx) in src_row.iter().enumerate() {
            let byte_pos = x / ppb;
            let bit_offset = (ppb - 1 - x % ppb) * bit_depth as usize;
            dst_row[byte_pos] |= (idx & mask) << bit_offset;
        }
    }
    packed
}

pub(crate) fn truncate_trns(palette_alpha: Option<&[u8]>) -> Option<Vec<u8>> {
    let alpha = palette_alpha?;
    let last_non_opaque = alpha.iter().rposition(|&a| a != 255)?;
    Some(alpha[..=last_non_opaque].to_vec())
}

#[cfg(test)]
mod tests {
    use super::*;
    use enough::Unstoppable;

    fn default_opts() -> CompressOptions<'static> {
        CompressOptions {
            parallel: false,
            cancel: &Unstoppable,
            deadline: &Unstoppable,
            remaining_ns: None,
            max_threads: 0,
        }
    }

    // ── select_bit_depth ────────────────────────────────────────────

    #[test]
    fn select_bit_depth_boundaries() {
        assert_eq!(select_bit_depth(1), 1);
        assert_eq!(select_bit_depth(2), 1);
        assert_eq!(select_bit_depth(3), 2);
        assert_eq!(select_bit_depth(4), 2);
        assert_eq!(select_bit_depth(5), 4);
        assert_eq!(select_bit_depth(16), 4);
        assert_eq!(select_bit_depth(17), 8);
        assert_eq!(select_bit_depth(256), 8);
    }

    // ── packed_row_bytes ────────────────────────────────────────────

    #[test]
    fn packed_row_bytes_all_depths() {
        assert_eq!(packed_row_bytes(8, 8), 8);
        assert_eq!(packed_row_bytes(8, 4), 4);
        assert_eq!(packed_row_bytes(8, 2), 2);
        assert_eq!(packed_row_bytes(8, 1), 1);
        // Non-aligned widths
        assert_eq!(packed_row_bytes(3, 4), 2); // 3 pixels @ 4bpp = 2 bytes
        assert_eq!(packed_row_bytes(5, 2), 2); // 5 pixels @ 2bpp = 2 bytes
        assert_eq!(packed_row_bytes(9, 1), 2); // 9 pixels @ 1bpp = 2 bytes
    }

    // ── pack_all_rows ───────────────────────────────────────────────

    #[test]
    fn pack_8bit_is_identity() {
        let indices = vec![0u8, 1, 2, 3, 4, 5];
        let packed = pack_all_rows(&indices, 3, 2, 8);
        assert_eq!(packed, indices);
    }

    #[test]
    fn pack_4bit() {
        // 4 pixels: 0, 15, 3, 12
        let indices = vec![0, 15, 3, 12];
        let packed = pack_all_rows(&indices, 4, 1, 4);
        // MSB first: [0<<4|15, 3<<4|12] = [0x0F, 0x3C]
        assert_eq!(packed, vec![0x0F, 0x3C]);
    }

    #[test]
    fn pack_2bit() {
        // 4 pixels: 0, 1, 2, 3
        let indices = vec![0, 1, 2, 3];
        let packed = pack_all_rows(&indices, 4, 1, 2);
        // MSB first: 0<<6 | 1<<4 | 2<<2 | 3<<0 = 0b00011011 = 0x1B
        assert_eq!(packed, vec![0x1B]);
    }

    #[test]
    fn pack_1bit() {
        // 8 pixels: alternating 0,1
        let indices = vec![0, 1, 0, 1, 0, 1, 0, 1];
        let packed = pack_all_rows(&indices, 8, 1, 1);
        // MSB first: 01010101 = 0x55
        assert_eq!(packed, vec![0x55]);
    }

    // ── truncate_trns ───────────────────────────────────────────────

    #[test]
    fn truncate_trns_none() {
        assert!(truncate_trns(None).is_none());
    }

    #[test]
    fn truncate_trns_all_opaque() {
        assert!(truncate_trns(Some(&[255, 255, 255])).is_none());
    }

    #[test]
    fn truncate_trns_truncates_trailing_opaque() {
        let alpha = [0, 128, 255, 255, 255];
        let result = truncate_trns(Some(&alpha)).unwrap();
        assert_eq!(result, vec![0, 128]);
    }

    #[test]
    fn truncate_trns_single_transparent() {
        let alpha = [0, 255, 255];
        let result = truncate_trns(Some(&alpha)).unwrap();
        assert_eq!(result, vec![0]);
    }

    // ── write_indexed_png error paths ───────────────────────────────

    #[test]
    fn indexed_png_empty_palette_error() {
        let result = write_indexed_png(
            &[0; 4],
            2,
            2,
            &[], // 0 colors
            None,
            &PngWriteMetadata::from_metadata(None),
            1,
            default_opts(),
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("1-256"));
    }

    #[test]
    fn indexed_png_oversized_palette_error() {
        let palette = vec![0u8; 257 * 3]; // 257 colors
        let result = write_indexed_png(
            &[0; 4],
            2,
            2,
            &palette,
            None,
            &PngWriteMetadata::from_metadata(None),
            1,
            default_opts(),
        );
        assert!(result.is_err());
    }

    #[test]
    fn indexed_png_buffer_too_small_error() {
        let palette = vec![0u8; 3]; // 1 color
        let result = write_indexed_png(
            &[0; 2], // too small for 2x2
            2,
            2,
            &palette,
            None,
            &PngWriteMetadata::from_metadata(None),
            1,
            default_opts(),
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("too small"));
    }

    #[test]
    fn indexed_png_valid_roundtrip() {
        let palette = vec![255, 0, 0, 0, 255, 0]; // red, green
        let indices = vec![0, 1, 1, 0];
        let result = write_indexed_png(
            &indices,
            2,
            2,
            &palette,
            None,
            &PngWriteMetadata::from_metadata(None),
            1,
            default_opts(),
        );
        assert!(result.is_ok());
        let png = result.unwrap();
        assert!(png[..8] == [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
    }

    // ── write_truecolor_png error paths ─────────────────────────────

    #[test]
    fn truecolor_png_unsupported_color_type() {
        let result = write_truecolor_png(
            &[0; 12],
            2,
            2,
            5, // invalid color type
            8,
            None,
            &PngWriteMetadata::from_metadata(None),
            1,
            default_opts(),
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("unsupported"));
    }

    #[test]
    fn truecolor_png_buffer_too_small() {
        let result = write_truecolor_png(
            &[0; 4], // too small for 2x2 RGB
            2,
            2,
            2, // RGB
            8,
            None,
            &PngWriteMetadata::from_metadata(None),
            1,
            default_opts(),
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("too small"));
    }

    #[test]
    fn truecolor_png_effort_0_store_path() {
        // Effort 0 takes a different fast path (no compression)
        let pixels = vec![128u8; 2 * 2 * 3]; // 2x2 RGB
        let result = write_truecolor_png(
            &pixels,
            2,
            2,
            2, // RGB
            8,
            None,
            &PngWriteMetadata::from_metadata(None),
            0,
            default_opts(),
        );
        let png = result.unwrap();
        // Verify valid PNG signature
        assert!(png[..8] == [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
        // Verify it decodes
        let decoded = crate::decode(&png, &crate::PngDecodeConfig::strict(), &Unstoppable).unwrap();
        assert_eq!(decoded.info.width, 2);
    }

    #[test]
    fn truecolor_png_16bit_path() {
        let pixels = vec![0u8; 2 * 2 * 6]; // 2x2 RGB16
        let result = write_truecolor_png(
            &pixels,
            2,
            2,
            2,  // RGB
            16, // 16-bit
            None,
            &PngWriteMetadata::from_metadata(None),
            1,
            default_opts(),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn truecolor_png_grayscale_alpha() {
        let pixels = vec![128u8; 2 * 2 * 2]; // 2x2 GrayscaleAlpha
        let result = write_truecolor_png(
            &pixels,
            2,
            2,
            4, // GrayscaleAlpha
            8,
            None,
            &PngWriteMetadata::from_metadata(None),
            1,
            default_opts(),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn truecolor_png_with_trns() {
        let pixels = vec![0u8; 2 * 2 * 3]; // 2x2 RGB
        let trns = [0u8, 0, 0, 0, 0, 0]; // transparent black
        let result = write_truecolor_png(
            &pixels,
            2,
            2,
            2, // RGB
            8,
            Some(&trns),
            &PngWriteMetadata::from_metadata(None),
            1,
            default_opts(),
        );
        assert!(result.is_ok());
    }

    // ── Sub-byte grayscale path ─────────────────────────────────────

    #[test]
    fn subbyte_grayscale_4bit_roundtrip() {
        // Create pixel data with 4-bit values (0-15)
        let pixels: Vec<u8> = (0..16).collect();
        let result = write_truecolor_png(
            &pixels,
            4,
            4,
            0, // Grayscale
            4, // 4-bit
            None,
            &PngWriteMetadata::from_metadata(None),
            1,
            default_opts(),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn subbyte_grayscale_buffer_too_small() {
        let result = write_truecolor_png(
            &[0; 2], // too small for 4x4
            4,
            4,
            0, // Grayscale
            4, // 4-bit
            None,
            &PngWriteMetadata::from_metadata(None),
            1,
            default_opts(),
        );
        assert!(result.is_err());
    }
}