flpdf 0.1.2

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
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
use crate::ascii85;
use crate::ascii_hex;
use crate::run_length;
use crate::security::standard::{decrypt_cipher_bytes, StringCipher};
use crate::{Dictionary, Error, Object, Result};
use flate2::read::ZlibDecoder;
use flate2::write::ZlibEncoder;
use flate2::Compression;
use std::io::{Read, Write};

pub fn decode_stream_data(dict: &Dictionary, stream_data: &[u8]) -> Result<Vec<u8>> {
    decode_stream_data_with_filters(dict.get("Filter"), dict.get("DecodeParms"), stream_data)
}

// Wired into encrypted document reads by later flpdf-9hc.3 layers.
#[allow(dead_code)]
pub(crate) fn decode_stream_data_with_decryption(
    dict: &Dictionary,
    stream_data: &[u8],
    cipher: StringCipher<'_>,
) -> Result<Vec<u8>> {
    let mut decrypted = stream_data.to_vec();
    decrypt_cipher_bytes(&mut decrypted, cipher)?;
    decode_stream_data(dict, &decrypted)
}

pub(crate) fn decode_stream_data_with_crypt_filter<F>(
    dict: &Dictionary,
    stream_data: &[u8],
    mut decrypt_crypt: F,
) -> Result<Vec<u8>>
where
    F: FnMut(Option<&Object>, &[u8]) -> Result<Vec<u8>>,
{
    decode_stream_data_with_filters_and_crypt(
        dict.get("Filter"),
        dict.get("DecodeParms"),
        stream_data,
        &mut decrypt_crypt,
    )
}

pub fn encode_stream_data(dict: &Dictionary, stream_data: &[u8]) -> Result<Vec<u8>> {
    encode_stream_data_with_filters(dict.get("Filter"), stream_data)
}

fn decode_stream_data_with_filters(
    filter: Option<&Object>,
    decode_params: Option<&Object>,
    stream_data: &[u8],
) -> Result<Vec<u8>> {
    decode_stream_data_with_filters_and_crypt(filter, decode_params, stream_data, &mut |_, _| {
        Err(Error::Unsupported(
            "unsupported stream filter: Crypt".to_string(),
        ))
    })
}

fn decode_stream_data_with_filters_and_crypt<F>(
    filter: Option<&Object>,
    decode_params: Option<&Object>,
    stream_data: &[u8],
    decrypt_crypt: &mut F,
) -> Result<Vec<u8>>
where
    F: FnMut(Option<&Object>, &[u8]) -> Result<Vec<u8>>,
{
    match filter {
        None => Ok(stream_data.to_vec()),
        Some(Object::Name(filter_name)) => {
            if filter_name == b"Crypt" {
                return decrypt_crypt(get_decode_params(decode_params, 0), stream_data);
            }
            let decoded =
                apply_single_filter_decode(filter_name, stream_data).map_err(Error::Unsupported)?;
            apply_decode_params(get_decode_params(decode_params, 0), &decoded)
        }
        Some(Object::Array(filters)) => {
            let mut decoded = stream_data.to_vec();
            for (index, filter) in filters.iter().enumerate() {
                let Object::Name(filter_name) = filter else {
                    return Err(Error::Unsupported(
                        "unsupported stream filter type: expected name".to_string(),
                    ));
                };
                if filter_name == b"Crypt" {
                    decoded = decrypt_crypt(get_decode_params(decode_params, index), &decoded)?;
                } else {
                    decoded = apply_single_filter_decode(filter_name, &decoded)
                        .map_err(Error::Unsupported)?;
                    decoded =
                        apply_decode_params(get_decode_params(decode_params, index), &decoded)?;
                }
            }
            Ok(decoded)
        }
        Some(other) => Err(Error::Unsupported(format!(
            "unsupported stream filter syntax: {}",
            object_debug_repr(other)
        ))),
    }
}

fn encode_stream_data_with_filters(filter: Option<&Object>, stream_data: &[u8]) -> Result<Vec<u8>> {
    match filter {
        None => Ok(stream_data.to_vec()),
        Some(Object::Name(filter_name)) => {
            apply_single_filter_encode(filter_name, stream_data).map_err(Error::Unsupported)
        }
        Some(Object::Array(filters)) => {
            let mut encoded = stream_data.to_vec();
            for filter in filters {
                let Object::Name(filter_name) = filter else {
                    return Err(Error::Unsupported(
                        "unsupported stream filter type: expected name".to_string(),
                    ));
                };
                encoded = apply_single_filter_encode(filter_name, &encoded)
                    .map_err(Error::Unsupported)?;
            }
            Ok(encoded)
        }
        Some(other) => Err(Error::Unsupported(format!(
            "unsupported stream filter syntax: {}",
            object_debug_repr(other)
        ))),
    }
}

fn get_decode_params(params: Option<&Object>, index: usize) -> Option<&Object> {
    match params {
        None => None,
        Some(Object::Dictionary(_)) => Some(params.unwrap()),
        Some(Object::Array(values)) => values.get(index),
        Some(_) => None,
    }
}

fn apply_decode_params(decode_params: Option<&Object>, stream_data: &[u8]) -> Result<Vec<u8>> {
    let Some(Object::Dictionary(params)) = decode_params else {
        return Ok(stream_data.to_vec());
    };

    let predictor = match params.get("Predictor") {
        Some(Object::Integer(value)) => u8::try_from(*value).map_err(|_| {
            Error::Unsupported("/DecodeParms /Predictor must be non-negative".to_string())
        })?,
        Some(_) => {
            return Err(Error::Unsupported(
                "/DecodeParms /Predictor must be integer".to_string(),
            ))
        }
        None => return Ok(stream_data.to_vec()),
    };

    if predictor <= 1 {
        return Ok(stream_data.to_vec());
    }

    if predictor == 2 {
        return Err(Error::Unsupported(
            "/DecodeParms /Predictor 2 is not supported for this stream type".to_string(),
        ));
    }

    if !(10..=15).contains(&predictor) {
        return Err(Error::Unsupported(format!(
            "unsupported /DecodeParms /Predictor {predictor}"
        )));
    }

    let colors = match params.get("Colors") {
        None => 1usize,
        Some(Object::Integer(value)) => usize::try_from(*value).map_err(|_| {
            Error::Unsupported("/DecodeParms /Colors must be non-negative".to_string())
        })?,
        Some(_) => {
            return Err(Error::Unsupported(
                "/DecodeParms /Colors must be integer".to_string(),
            ))
        }
    };

    let bits_per_component = match params.get("BitsPerComponent") {
        None => 8usize,
        Some(Object::Integer(value)) => usize::try_from(*value).map_err(|_| {
            Error::Unsupported("/DecodeParms /BitsPerComponent must be non-negative".to_string())
        })?,
        Some(_) => {
            return Err(Error::Unsupported(
                "/DecodeParms /BitsPerComponent must be integer".to_string(),
            ))
        }
    };

    let columns = match params.get("Columns") {
        Some(Object::Integer(value)) => usize::try_from(*value).map_err(|_| {
            Error::Unsupported("/DecodeParms /Columns must be non-negative".to_string())
        })?,
        Some(_) => {
            return Err(Error::Unsupported(
                "/DecodeParms /Columns must be integer".to_string(),
            ))
        }
        None => {
            return Err(Error::Unsupported(
                "/DecodeParms /Columns required for PNG predictor".to_string(),
            ))
        }
    };

    let row_bits = columns
        .checked_mul(colors)
        .and_then(|value| value.checked_mul(bits_per_component))
        .ok_or_else(|| Error::Unsupported("/DecodeParms /Predictor overflow".to_string()))?;
    let row_bytes = row_bits.div_ceil(8);
    if row_bytes == 0 {
        return Err(Error::Unsupported(
            "/DecodeParms /Predictor produced zero row width".to_string(),
        ));
    }
    let bits_per_pixel = colors
        .checked_mul(bits_per_component)
        .ok_or_else(|| Error::Unsupported("/DecodeParms /Predictor overflow".to_string()))?;
    let bytes_per_pixel = bits_per_pixel.div_ceil(8).max(1);

    decode_png_predictor(stream_data, row_bytes, bytes_per_pixel)
}

fn decode_png_predictor(bytes: &[u8], row_bytes: usize, bytes_per_pixel: usize) -> Result<Vec<u8>> {
    let row_size = row_bytes
        .checked_add(1)
        .ok_or_else(|| Error::Unsupported("PNG predictor row size overflow".to_string()))?;
    if !bytes.len().is_multiple_of(row_size) {
        return Err(Error::Unsupported(
            "corrupt PNG predictor stream".to_string(),
        ));
    }

    let row_count = bytes.len() / row_size;
    let mut decoded = Vec::with_capacity(row_count * row_bytes);
    let mut previous_row = vec![0u8; row_bytes];

    for row in bytes.chunks_exact(row_size) {
        let filter = row[0];
        let raw = &row[1..];
        let mut current = vec![0u8; row_bytes];

        for i in 0..row_bytes {
            let raw_byte = raw[i];
            let left = if i >= bytes_per_pixel {
                current[i - bytes_per_pixel]
            } else {
                0
            };
            let above = previous_row[i];
            let upper_left = if i >= bytes_per_pixel {
                previous_row[i - bytes_per_pixel]
            } else {
                0
            };

            current[i] = match filter {
                0 => raw_byte,
                1 => raw_byte.wrapping_add(left),
                2 => raw_byte.wrapping_add(above),
                3 => {
                    let average = (u16::from(left) + u16::from(above)) / 2;
                    raw_byte.wrapping_add(average as u8)
                }
                4 => {
                    let p = left as i16 + above as i16 - upper_left as i16;
                    let pa = (p - left as i16).abs();
                    let pb = (p - above as i16).abs();
                    let pc = (p - upper_left as i16).abs();

                    let predictor = if pa <= pb && pa <= pc {
                        left
                    } else if pb <= pc {
                        above
                    } else {
                        upper_left
                    };

                    raw_byte.wrapping_add(predictor)
                }
                _ => {
                    return Err(Error::Unsupported(
                        "unsupported PNG predictor filter".to_string(),
                    ))
                }
            };
        }

        decoded.extend_from_slice(&current);
        previous_row = current;
    }

    Ok(decoded)
}

fn apply_single_filter_decode(
    filter_name: &[u8],
    stream_data: &[u8],
) -> std::result::Result<Vec<u8>, String> {
    if filter_name == b"FlateDecode" {
        let mut decoded = Vec::new();
        let mut decoder = ZlibDecoder::new(stream_data);
        decoder
            .read_to_end(&mut decoded)
            .map_err(|error| error.to_string())?;
        return Ok(decoded);
    }

    if filter_name == b"ASCII85Decode" {
        return ascii85::decode(stream_data);
    }

    if filter_name == b"ASCIIHexDecode" {
        return ascii_hex::decode(stream_data);
    }

    if filter_name == b"RunLengthDecode" {
        return run_length::decode(stream_data);
    }

    Err(format!(
        "unsupported stream filter: {}",
        std::str::from_utf8(filter_name).unwrap_or("<binary>")
    ))
}

fn apply_single_filter_encode(
    filter_name: &[u8],
    stream_data: &[u8],
) -> std::result::Result<Vec<u8>, String> {
    if filter_name == b"FlateDecode" {
        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
        encoder
            .write_all(stream_data)
            .map_err(|error| error.to_string())?;
        let encoded = encoder.finish().map_err(|error| error.to_string())?;
        return Ok(encoded);
    }

    if filter_name == b"ASCII85Decode" {
        return Ok(ascii85::encode(stream_data));
    }

    if filter_name == b"ASCIIHexDecode" {
        return Ok(ascii_hex::encode(stream_data));
    }

    if filter_name == b"RunLengthDecode" {
        return Ok(run_length::encode(stream_data));
    }

    Err(format!(
        "unsupported stream filter: {}",
        std::str::from_utf8(filter_name).unwrap_or("<binary>"),
    ))
}

fn object_debug_repr(object: &Object) -> &'static str {
    match object {
        Object::Name(name) if name == b"FlateDecode" => "FlateDecode",
        Object::Name(name) if name == b"ASCII85Decode" => "ASCII85Decode",
        Object::Name(name) if name == b"ASCIIHexDecode" => "ASCIIHexDecode",
        Object::Name(name) if name == b"LZWDecode" => "LZWDecode",
        Object::Name(name) if name == b"RunLengthDecode" => "RunLengthDecode",
        _ => "unsupported",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::security::primitives::rc4;
    use crate::security::standard::StringCipher;
    use aes::{Aes128, Aes256};
    use cbc::cipher::{block_padding::Pkcs7, BlockEncryptMut, KeyIvInit};
    use cbc::Encryptor;

    fn flate_dict() -> Dictionary {
        let mut dict = Dictionary::new();
        dict.insert("Filter", Object::Name(b"FlateDecode".to_vec()));
        dict
    }

    fn aes128_stream(key: &[u8; 16], iv: &[u8; 16], plaintext: &[u8]) -> Vec<u8> {
        let enc = <Encryptor<Aes128> as KeyIvInit>::new(key.into(), iv.into());
        let mut buf = plaintext.to_vec();
        let msg_len = buf.len();
        buf.resize(msg_len + 16, 0);
        let ciphertext = enc.encrypt_padded_mut::<Pkcs7>(&mut buf, msg_len).unwrap();
        let mut out = iv.to_vec();
        out.extend_from_slice(ciphertext);
        out
    }

    fn aes256_stream(key: &[u8; 32], iv: &[u8; 16], plaintext: &[u8]) -> Vec<u8> {
        let enc = <Encryptor<Aes256> as KeyIvInit>::new(key.into(), iv.into());
        let mut buf = plaintext.to_vec();
        let msg_len = buf.len();
        buf.resize(msg_len + 16, 0);
        let ciphertext = enc.encrypt_padded_mut::<Pkcs7>(&mut buf, msg_len).unwrap();
        let mut out = iv.to_vec();
        out.extend_from_slice(ciphertext);
        out
    }

    #[test]
    fn decode_stream_data_with_decryption_decrypts_before_flate() {
        let dict = flate_dict();
        let plaintext = b"stream plaintext after flate";
        let mut encrypted = encode_stream_data(&dict, plaintext).unwrap();
        rc4(b"Key", &mut encrypted).unwrap();

        let decoded = decode_stream_data_with_decryption(
            &dict,
            &encrypted,
            StringCipher::Rc4 { key: b"Key" },
        )
        .unwrap();

        assert_eq!(decoded, plaintext);
    }

    #[test]
    fn decode_stream_data_with_decryption_handles_no_filter_rc4_streams() {
        let dict = Dictionary::new();
        let mut encrypted = b"raw encrypted stream".to_vec();
        rc4(b"Key", &mut encrypted).unwrap();

        let decoded = decode_stream_data_with_decryption(
            &dict,
            &encrypted,
            StringCipher::Rc4 { key: b"Key" },
        )
        .unwrap();

        assert_eq!(decoded, b"raw encrypted stream");
    }

    #[test]
    fn decode_stream_data_with_decryption_handles_aes_streams() {
        let dict = Dictionary::new();
        let aes128_key = [0x11; 16];
        let aes128_iv = [0x22; 16];
        let aes128 = aes128_stream(&aes128_key, &aes128_iv, b"AES-128 stream");
        let decoded = decode_stream_data_with_decryption(
            &dict,
            &aes128,
            StringCipher::Aes128 { key: &aes128_key },
        )
        .unwrap();
        assert_eq!(decoded, b"AES-128 stream");

        let aes256_key = [0x33; 32];
        let aes256_iv = [0x44; 16];
        let aes256 = aes256_stream(&aes256_key, &aes256_iv, b"AES-256 stream");
        let decoded = decode_stream_data_with_decryption(
            &dict,
            &aes256,
            StringCipher::Aes256 { key: &aes256_key },
        )
        .unwrap();
        assert_eq!(decoded, b"AES-256 stream");
    }

    #[test]
    fn decode_stream_data_without_decryption_keeps_plaintext_behavior() {
        let dict = flate_dict();
        let plaintext = b"legacy plaintext flate";
        let encoded = encode_stream_data(&dict, plaintext).unwrap();

        let decoded = decode_stream_data(&dict, &encoded).unwrap();

        assert_eq!(decoded, plaintext);
    }

    // ----- ASCIIHexDecode filter integration tests -----

    fn ascii_hex_dict() -> Dictionary {
        let mut dict = Dictionary::new();
        dict.insert("Filter", Object::Name(b"ASCIIHexDecode".to_vec()));
        dict
    }

    #[test]
    fn decode_stream_data_ascii_hex_round_trip() {
        let dict = ascii_hex_dict();
        let plaintext = b"Hello from ASCIIHexDecode filter!";

        let encoded = encode_stream_data(&dict, plaintext).unwrap();
        let decoded = decode_stream_data(&dict, &encoded).unwrap();

        assert_eq!(decoded, plaintext.as_slice());
    }

    #[test]
    fn decode_stream_data_ascii_hex_empty() {
        let dict = ascii_hex_dict();
        let plaintext = b"";

        let encoded = encode_stream_data(&dict, plaintext).unwrap();
        let decoded = decode_stream_data(&dict, &encoded).unwrap();

        assert_eq!(decoded, plaintext.as_slice());
    }

    #[test]
    fn decode_stream_data_ascii_hex_odd_length_data() {
        let dict = ascii_hex_dict();
        // 3 bytes → odd nibble count in inner encoding only if we provide raw odd data;
        // encode always emits two hex chars per byte so no padding needed on decode
        let plaintext = b"ABC";

        let encoded = encode_stream_data(&dict, plaintext).unwrap();
        let decoded = decode_stream_data(&dict, &encoded).unwrap();

        assert_eq!(decoded, plaintext.as_slice());
    }

    // ----- ASCII85Decode filter integration tests -----

    fn ascii85_dict() -> Dictionary {
        let mut dict = Dictionary::new();
        dict.insert("Filter", Object::Name(b"ASCII85Decode".to_vec()));
        dict
    }

    #[test]
    fn decode_stream_data_ascii85_round_trip() {
        let dict = ascii85_dict();
        let plaintext = b"Hello from ASCII85Decode filter!";

        let encoded = encode_stream_data(&dict, plaintext).unwrap();
        let decoded = decode_stream_data(&dict, &encoded).unwrap();

        assert_eq!(decoded, plaintext.as_slice());
    }

    #[test]
    fn decode_stream_data_ascii85_empty() {
        let dict = ascii85_dict();
        let plaintext = b"";

        let encoded = encode_stream_data(&dict, plaintext).unwrap();
        let decoded = decode_stream_data(&dict, &encoded).unwrap();

        assert_eq!(decoded, plaintext.as_slice());
    }

    #[test]
    fn decode_stream_data_ascii85_zero_block() {
        let dict = ascii85_dict();
        // A 4-byte all-zero block triggers the 'z' shorthand in the encoder
        let plaintext = [0u8; 8]; // two complete zero blocks → encoder emits "zz~>"

        let encoded = encode_stream_data(&dict, &plaintext).unwrap();
        // Verify the encoder actually used the 'z' shorthand
        assert!(
            encoded.contains(&b'z'),
            "encoder should emit 'z' for 4-byte zero block"
        );
        let decoded = decode_stream_data(&dict, &encoded).unwrap();

        assert_eq!(decoded, plaintext.as_slice());
    }

    #[test]
    fn decode_stream_data_ascii85_short_final_group() {
        let dict = ascii85_dict();
        // Test all three short-final-group lengths: 1, 2, 3 bytes remainder
        for plaintext in [b"M".as_slice(), b"Ma", b"Man"] {
            let encoded = encode_stream_data(&dict, plaintext).unwrap();
            let decoded = decode_stream_data(&dict, &encoded).unwrap();
            assert_eq!(
                decoded,
                plaintext,
                "short final group round-trip failed for {} bytes",
                plaintext.len()
            );
        }
    }

    #[test]
    fn decode_stream_data_ascii85_rejects_invalid_byte() {
        let dict = ascii85_dict();
        // 'v' (0x76) is above the valid range '!'..'u' (0x21..=0x75)
        // Feed a hand-crafted stream: "9jqov~>" where 'v' is out-of-range
        let invalid_stream = b"9jqov~>";

        let result = decode_stream_data(&dict, invalid_stream);

        assert!(result.is_err(), "expected error for out-of-range byte");
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("ASCII85Decode"),
            "error message should contain 'ASCII85Decode', got: {msg}"
        );
    }

    // ----- RunLengthDecode filter integration tests -----

    fn run_length_dict() -> Dictionary {
        let mut dict = Dictionary::new();
        dict.insert("Filter", Object::Name(b"RunLengthDecode".to_vec()));
        dict
    }

    #[test]
    fn decode_stream_data_run_length_round_trip() {
        let dict = run_length_dict();
        let plaintext = b"Hello from RunLengthDecode filter!";

        let encoded = encode_stream_data(&dict, plaintext).unwrap();
        let decoded = decode_stream_data(&dict, &encoded).unwrap();

        assert_eq!(decoded, plaintext.as_slice());
    }

    #[test]
    fn decode_stream_data_run_length_empty() {
        let dict = run_length_dict();
        let plaintext = b"";

        let encoded = encode_stream_data(&dict, plaintext).unwrap();
        let decoded = decode_stream_data(&dict, &encoded).unwrap();

        assert_eq!(decoded, plaintext.as_slice());
    }

    #[test]
    fn decode_stream_data_run_length_with_repeats() {
        let dict = run_length_dict();
        // Data with prominent repeat runs (triggers repeat-run encoding).
        let mut plaintext = vec![0x42u8; 100]; // 100 'B' bytes
        plaintext.extend(b"literal");
        plaintext.extend(vec![0xCCu8; 50]); // 50 0xCC bytes

        let encoded = encode_stream_data(&dict, &plaintext).unwrap();
        let decoded = decode_stream_data(&dict, &encoded).unwrap();

        assert_eq!(decoded, plaintext.as_slice());
    }

    #[test]
    fn decode_stream_data_run_length_rejects_truncated_literal() {
        let dict = run_length_dict();
        // Hand-crafted truncated stream: header says 6 literals (l=5) but only 3 follow.
        let truncated_stream = vec![0x05u8, b'A', b'B', b'C']; // 3 bytes instead of 6

        let result = decode_stream_data(&dict, &truncated_stream);

        assert!(
            result.is_err(),
            "expected error for truncated literal stream"
        );
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("RunLengthDecode"),
            "error message should contain 'RunLengthDecode', got: {msg}"
        );
    }
}