rust-j2k 0.5.0

Decodes JPEG 2000 images in pure Rust, for programs that need to read them without linking a C library.
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
//! The decode's tier-1 work bound, and the [`WorkLimit`] options that raise
//! or lift it and the tier-2 one.
//!
//! A code-block's packet header can ask for 88 coding passes in about four
//! bytes, and each pass scans the whole block, so a small file can ask the
//! block decoder for minutes of work. The decode counts that work (passes
//! times samples) before it decodes a tile, and refuses a file past the
//! bound with [`Error::Limit`]. OpenJPEG 2.5.0 has no such bound. See
//! `tests/fixtures/tier1_work_bound/README.md` and `docs/resource-bounds.md`.
//!
//! The committed files are written by
//! `scripts/gen-tier1-work-bound-fixtures.py`; the issue's 76 KB shape is
//! built here, with the same layout.

mod support;

use std::time::{Duration, Instant};

use rust_j2k::{
    DecodeOptions, Error, LimitDetail, LimitKind, WorkLimit, decode, decode_with, read_header,
    read_header_with,
};
use support::jp2::sha256_hex;
use support::synth::{self, Bits, seg};

fn fixture(path: &str) -> Vec<u8> {
    synth::read_file(synth::fixtures(path))
}

/// `t1bomb` from the generator: one `size` x `size` tile of one 8-bit
/// component, no wavelet levels, 64x64 code-blocks, one layer, each block
/// included with 88 coding passes and the one byte 0x00. QCD gives the band
/// 30 bit-planes and no block has a zero bit-plane, so each runs all 88.
fn t1bomb(size: u32) -> Vec<u8> {
    t1bomb_tiled_with_length(size, 1, 1)
}

/// `t1bomb(size)` as `side` x `side` tiles, each the same bomb.
fn t1bomb_tiled(size: u32, side: u32) -> Vec<u8> {
    t1bomb_tiled_with_length(size, side, 1)
}

/// [`t1bomb`] with each code-block's length `length` (0 or 1), and that
/// many bytes of 0x00 for each.
fn t1bomb_with_length(size: u32, length: u32) -> Vec<u8> {
    t1bomb_tiled_with_length(size, 1, length)
}

fn t1bomb_tiled_with_length(size: u32, side: u32, length: u32) -> Vec<u8> {
    assert!(length <= 1);
    let blocks = size.div_ceil(64);
    // The tag trees' levels, leaves first: (columns, rows).
    let mut levels = vec![(blocks, blocks)];
    while *levels.last().unwrap() != (1, 1) {
        let (c, r) = *levels.last().unwrap();
        levels.push((c.div_ceil(2), r.div_ceil(2)));
    }
    let mut known = [
        std::collections::HashSet::new(),
        std::collections::HashSet::new(),
    ];
    let mut bits = Bits::new();
    bits.put(1);
    for y in 0..blocks {
        for x in 0..blocks {
            // Inclusion, then the zero bit-planes: every value is 0, so each
            // node not yet known codes a 1.
            for tree in &mut known {
                for level in (0..levels.len() as u32).rev() {
                    if tree.insert((level, x >> level, y >> level)) {
                        bits.put(1);
                    }
                }
            }
            // 88 passes (Table B.4), Lblock stays 3, the length in
            // 3 + floor(log2(88)) = 9 bits.
            bits.put_int(0b1_1111_1111, 9);
            bits.put_int(88 - 37, 7);
            bits.put(0);
            bits.put_int(length, 9);
        }
    }
    let mut data = bits.finish();
    data.resize(data.len() + (blocks * blocks * length) as usize, 0);

    let siz = synth::siz_body(
        [size * side, size * side, 0, 0, size, size, 0, 0],
        &[[7, 1, 1]],
    );
    let mut cs = vec![0xFF, 0x4F];
    cs.extend(seg(0xFF51, &siz));
    cs.extend(seg(0xFF52, &synth::cod_body(1, 0, 4, 0)));
    cs.extend(seg(0xFF5C, &synth::qcd_none_body(2, &[29])));
    for tile in 0..side * side {
        cs.extend_from_slice(&[0xFF, 0x90, 0, 10]);
        cs.extend_from_slice(&(tile as u16).to_be_bytes());
        cs.extend_from_slice(&(12 + 2 + data.len() as u32).to_be_bytes());
        cs.extend_from_slice(&[0, 1, 0xFF, 0x93]);
        cs.extend_from_slice(&data);
    }
    cs.extend_from_slice(&[0xFF, 0xD9]);
    cs
}

/// The HT counterpart of [`t1bomb`]: one `size` x `size` tile of one 8-bit
/// component, no wavelet levels, 64x64 HT code-blocks, one layer, each block
/// included with all three coding passes of an HT set and the fewest bytes
/// that decode: a cleanup segment of the two bytes `0xF2 0x00` (`Scup = 2`)
/// and a refinement segment of the byte `0x00`. QCD gives the band 30
/// bit-planes and no block has a zero bit-plane. A packet header spends
/// about 14 bits on each block, so this is about as many sample-passes for
/// the bytes as an HT file can ask for.
fn htbomb(size: u32) -> Vec<u8> {
    let blocks = size.div_ceil(64);
    let mut levels = vec![(blocks, blocks)];
    while *levels.last().unwrap() != (1, 1) {
        let (c, r) = *levels.last().unwrap();
        levels.push((c.div_ceil(2), r.div_ceil(2)));
    }
    let mut known = [
        std::collections::HashSet::new(),
        std::collections::HashSet::new(),
    ];
    let mut bits = Bits::new();
    bits.put(1);
    for y in 0..blocks {
        for x in 0..blocks {
            // Inclusion, then the zero bit-planes: every value is 0, so each
            // node not yet known codes a 1.
            for tree in &mut known {
                for level in (0..levels.len() as u32).rev() {
                    if tree.insert((level, x >> level, y >> level)) {
                        bits.put(1);
                    }
                }
            }
            // Three passes (`11 00`, Table B.4), Lblock stays 3: the cleanup
            // length 2 in 3 bits, the refinement length 1 in 3 + 1 bits.
            bits.put_int(0b1100, 4);
            bits.put(0);
            bits.put_int(2, 3);
            bits.put_int(1, 4);
        }
    }
    let mut data = bits.finish();
    for _ in 0..blocks * blocks {
        data.extend_from_slice(&[0xF2, 0x00, 0x00]);
    }

    let siz = synth::siz_body([size, size, 0, 0, size, size, 0, 0], &[[7, 1, 1]]);
    let mut cs = vec![0xFF, 0x4F];
    cs.extend(seg(0xFF51, &siz));
    // CAP: Part 15 only, one HT set per block, no `RGN`, and a
    // magnitude bound of 12 bits (`Ccap15` low bits 4).
    cs.extend(seg(0xFF50, &[0, 2, 0, 0, 0, 4]));
    // COD: block style HT (0x40), 64x64 code-blocks, no wavelet level.
    cs.extend(seg(0xFF52, &synth::cod_body(1, 0, 4, 0x40)));
    cs.extend(seg(0xFF5C, &synth::qcd_none_body(2, &[29])));
    cs.extend_from_slice(&[0xFF, 0x90, 0, 10, 0, 0]);
    cs.extend_from_slice(&(12 + 2 + data.len() as u32).to_be_bytes());
    cs.extend_from_slice(&[0, 1, 0xFF, 0x93]);
    cs.extend_from_slice(&data);
    cs.extend_from_slice(&[0xFF, 0xD9]);
    cs
}

/// The HT bomb the work-bound table measures is the shape built here.
#[test]
fn the_committed_ht_bomb_is_the_shape_built_here() {
    assert_eq!(
        htbomb(1024),
        fixture("tier1_work_bound/htbomb_1024_64_3.j2k")
    );
}

/// An HT file asks the block decoder for at most 3 passes over a block's
/// samples, and a block cannot cost under about 5 bytes of packet header and
/// data for all three, so the bound (2^15 sample-passes a byte) is out of
/// reach: this file, the most an HT file can ask for its bytes, decodes at
/// the default, as OpenJPEG 2.5.0 decodes it (the hash of its samples, all 128).
/// `every_committed_file_decodes_far_below_the_tier1_work_bound` (in
/// `src/tier1/work_bound_tests.rs`) measures its share of the bound.
#[test]
fn an_ht_bomb_decodes_at_the_default_bound() {
    let bytes = htbomb(1024);
    let image = decode(&bytes).expect("an HT file cannot reach the tier-1 bound");
    assert_eq!(image.components[0].samples.len(), 1024 * 1024);
    assert_eq!(
        sha256_hex(&samples_u8(&image)),
        "36ff34972077a9e824cce89d6a7056a0923719b8ae884a5ed7f0ba299303534e"
    );
}

/// The same shape at 8192^2, 79 KB: 2.0e8 sample-passes, 7.7% of its bound.
/// Ignored for the time it takes, 1.4 s on a release build (OpenJPEG 2.5.0:
/// see `docs/resource-bounds.md`).
#[test]
#[ignore = "slow: about 1.4 s on a release build"]
fn the_large_ht_bomb_decodes_at_the_default_bound() {
    let bytes = htbomb(8192);
    assert_eq!(bytes.len(), 79348);
    let start = Instant::now();
    let image = decode(&bytes).expect("an HT file cannot reach the tier-1 bound");
    eprintln!("htbomb(8192): {:?}", start.elapsed());
    assert_eq!(image.components[0].samples.len(), 8192 * 8192);
}

fn assert_limit(name: &str, result: rust_j2k::Result<rust_j2k::Image>) {
    match result {
        Err(Error::Limit(m)) => assert!(m.message().contains("work bound"), "{name}: {m}"),
        Err(e) => panic!("{name}: expected the work bound, got {e}"),
        Ok(_) => panic!("{name}: expected the work bound, got an image"),
    }
}

fn samples_u8(image: &rust_j2k::Image) -> Vec<u8> {
    image.components[0]
        .samples
        .iter()
        .map(|&s| s as u8)
        .collect()
}

/// The generator's file and the shape built here are the same bytes.
#[test]
fn the_committed_bomb_is_the_shape_built_here() {
    assert_eq!(
        t1bomb(1024),
        fixture("tier1_work_bound/t1bomb_1024_64_88.j2k")
    );
}

/// 1024^2 in 64x64 code-blocks of 88 passes asks for 9.2e7 sample-passes
/// in 1.2 KB of tile data, past the bound's floor of 2^26: refused, while
/// the header still reads. Twice the bound admits it, and it decodes to
/// what OpenJPEG 2.5.0 decodes (the hash of `opj_decompress`'s samples).
#[test]
fn raising_the_code_block_limit_admits_a_file_the_default_refuses() {
    let bytes = fixture("tier1_work_bound/t1bomb_1024_64_88.j2k");
    assert_limit("default", decode(&bytes));
    read_header(&bytes).expect("the header does not decode code-blocks");
    let raised = DecodeOptions::default().with_code_block_work_limit(WorkLimit::Raised(2));
    let image = decode_with(&bytes, &raised).expect("within twice the bound");
    assert_eq!(
        sha256_hex(&samples_u8(&image)),
        "a20e3adaff1e3c720b7cb8efe4a3da15a0a41df1b17c1b9cb247c3207882734d"
    );
    // Lifting the bound decodes it the same way.
    let lifted = DecodeOptions::default().with_code_block_work_limit(WorkLimit::Unlimited);
    assert_eq!(decode_with(&bytes, &lifted).unwrap(), image);
    // Raising the other bound does not.
    let other = DecodeOptions::default().with_packet_work_limit(WorkLimit::Unlimited);
    assert_limit("packet limit", decode_with(&bytes, &other));
}

/// The same shape with a length of zero for every code-block: passes and no
/// bytes, which B.10.7 allows and Tier-1 decodes from the `0xFF` fill. The
/// passes cost what they cost with a byte, so the file, smaller by a byte a
/// block, is still past the bound. Twice the bound admits it, and it decodes
/// to what OpenJPEG 2.5.0 decodes.
#[test]
fn passes_with_no_bytes_still_count_against_the_code_block_bound() {
    let bytes = t1bomb_with_length(1024, 0);
    assert_limit("default", decode(&bytes));
    let raised = DecodeOptions::default().with_code_block_work_limit(WorkLimit::Raised(2));
    let image = decode_with(&bytes, &raised).expect("within twice the bound");
    // The hash of `opj_decompress`'s samples for these bytes.
    assert_eq!(
        sha256_hex(&samples_u8(&image)),
        "36ff34972077a9e824cce89d6a7056a0923719b8ae884a5ed7f0ba299303534e"
    );
}

/// The issue's shape: 8192^2 in 64x64 code-blocks of 88 passes, 76 KB. It
/// asks for 5.9e9 sample-passes, about 19 s on a release build, past the
/// bound of 2^15 a byte (2.5e9). It is refused before any code-block is
/// decoded.
#[test]
fn the_issue_bomb_is_refused_fast() {
    let bytes = t1bomb(8192);
    assert_eq!(bytes.len(), 76525);
    let start = Instant::now();
    assert_limit("t1bomb 8192", decode(&bytes));
    // The refusal costs the packet walk alone: well under a second on a
    // release build. Debug builds are slower, so the check is loose.
    assert!(
        start.elapsed() < Duration::from_secs(20),
        "{:?}",
        start.elapsed()
    );
}

/// With the bound lifted, the issue's shape decodes, as OpenJPEG decodes
/// it. About 19 s on a release build, minutes on a debug one, so ignored:
/// run with `cargo test --release --test work_limit -- --ignored`.
#[test]
#[ignore = "slow: about 19 s on a release build"]
fn the_issue_bomb_decodes_with_the_limit_lifted() {
    let bytes = t1bomb(8192);
    let lifted = DecodeOptions::default().with_code_block_work_limit(WorkLimit::Unlimited);
    let image = decode_with(&bytes, &lifted).expect("decodes");
    assert_eq!(image.components[0].samples.len(), 8192 * 8192);
}

/// Encoder output that spends much work per byte: `opj_compress` on a
/// 16-bit image of 1000 with 128 specks of 60000, lossless. Each speck
/// makes its code-blocks run every pass for a few bytes. It decodes at the
/// default bound, sample for sample the image that was coded (OpenJPEG
/// 2.5.0 decodes it the same way).
#[test]
fn encoder_output_of_specks_decodes_at_the_default_bound() {
    let image = decode(&fixture("tier1_work_bound/opj_specks2048_16bit.j2k")).expect("decodes");
    let mut expected = vec![1000; 2048 * 2048];
    for i in 0..128 {
        let (x, y) = (i * 977 % 2048, i * 613 % 2048);
        expected[y * 2048 + x] = 60000;
    }
    assert_eq!(image.components.len(), 1);
    assert!(
        image.components[0].samples == expected,
        "not the coded image"
    );
}

/// The encoder output that spends the most work per byte seen:
/// `opj_compress -n 1` on a flat 16-bit image of 0, 42% of the bound. Each
/// code-block runs about 46 passes for about 14 bytes. It decodes at the
/// default bound to the flat image that was coded (OpenJPEG 2.5.0 decodes
/// it the same way).
#[test]
fn encoder_output_of_a_flat_image_without_wavelet_decodes_at_the_default_bound() {
    let image = decode(&fixture("tier1_work_bound/opj_flat2048_16bit_n1.j2k")).expect("decodes");
    assert_eq!(image.components.len(), 1);
    assert_eq!(image.components[0].samples.len(), 2048 * 2048);
    assert!(image.components[0].samples.iter().all(|&s| s == 0));
}

/// `t2skip_2048x1024_40000` walks 2.0e7 steps for 40 KB, past the tier-2
/// floor of 2^24: refused by default, and decoded to its flat 128 under
/// twice the bound or none.
#[test]
fn raising_the_packet_limit_admits_a_file_the_default_refuses() {
    let bytes = fixture("work_bound/t2skip_2048x1024_40000.j2k");
    assert_limit("default", decode(&bytes));
    for limit in [WorkLimit::Raised(2), WorkLimit::Unlimited] {
        let options = DecodeOptions::default().with_packet_work_limit(limit.clone());
        let image = decode_with(&bytes, &options).unwrap_or_else(|e| panic!("{limit:?}: {e}"));
        assert_eq!(image.components[0].samples.len(), 2048 * 1024);
        assert!(image.components[0].samples.iter().all(|&s| s == 128));
    }
    let other = DecodeOptions::default().with_code_block_work_limit(WorkLimit::Unlimited);
    assert_limit("code-block limit", decode_with(&bytes, &other));
}

/// The walk `read_header_with` makes of a `Psot = 0` tile takes the packet
/// limit too. `jp2_t2skip_512_20000.jp2` walks 5.1e6 steps, past that
/// walk's floor of 2^22, so by default the codestream is taken to run to the
/// end of the file and the decode refuses the `free` box after it as bytes
/// left after the last packet. Under twice the bound the walk finds the
/// packets end at the box's end, and the file decodes.
#[test]
fn the_packet_limit_reaches_the_walk_of_a_psot_zero_tile() {
    let bytes = fixture("work_bound/jp2_t2skip_512_20000.jp2");
    match decode(&bytes) {
        Err(Error::Codestream(_)) => {}
        other => panic!("expected the bytes after the packets refused, got {other:?}"),
    }
    let raised = DecodeOptions::default().with_packet_work_limit(WorkLimit::Raised(2));
    let image = decode_with(&bytes, &raised).expect("ends at the box");
    assert!(image.components[0].samples.iter().all(|&s| s == 128));
    let header = read_header_with(&bytes, &raised).unwrap();
    let default = read_header(&bytes).unwrap();
    assert_eq!(header.jp2.as_ref().unwrap(), image.jp2.as_ref().unwrap());
    assert_eq!(
        (header.width, header.height),
        (default.width, default.height)
    );
}

/// A limit raised by a factor of 0 is an error in the options, whatever the
/// input.
#[test]
fn a_limit_raised_by_zero_is_invalid_options() {
    let bytes = fixture("tier1_work_bound/t1bomb_1024_64_88.j2k");
    for options in [
        DecodeOptions::default().with_code_block_work_limit(WorkLimit::Raised(0)),
        DecodeOptions::default().with_packet_work_limit(WorkLimit::Raised(0)),
    ] {
        assert!(matches!(
            decode_with(&bytes, &options),
            Err(Error::InvalidOptions(_))
        ));
        assert!(matches!(
            read_header_with(&bytes, &options),
            Err(Error::InvalidOptions(_))
        ));
    }
    // `Raised(1)` is the default bound.
    let one = DecodeOptions::default().with_code_block_work_limit(WorkLimit::Raised(1));
    assert_limit("Raised(1)", decode_with(&bytes, &one));
}

/// The factor a `Limit` refusal gives as `WorkLimit::Raised(n)`, read from
/// its data. The message names the same one.
fn named_factor(limit: &LimitDetail) -> u32 {
    let Some(WorkLimit::Raised(n)) = limit.retry_with() else {
        panic!("no factor given: {limit:?}");
    };
    assert!(
        limit
            .message()
            .contains(&format!("`WorkLimit::Raised({n})`")),
        "{limit}"
    );
    n
}

fn limit_detail(result: rust_j2k::Result<rust_j2k::Image>) -> LimitDetail {
    match result {
        Err(Error::Limit(limit)) => limit,
        other => panic!("expected the work bound, got {other:?}"),
    }
}

/// On these two files the named factor is the smallest that admits them:
/// decoding with it succeeds, and with one less is refused. (The packet
/// bound only names the next factor up; see below.)
#[test]
fn the_named_factor_is_the_smallest_that_admits_the_file() {
    type Setter = fn(DecodeOptions, WorkLimit) -> DecodeOptions;
    let cases: [(&str, Setter, u32); 2] = [
        (
            "tier1_work_bound/t1bomb_1024_64_88.j2k",
            DecodeOptions::with_code_block_work_limit,
            2,
        ),
        (
            "work_bound/t2skip_2048x1024_40000.j2k",
            DecodeOptions::with_packet_work_limit,
            2,
        ),
    ];
    for (name, set, expected) in cases {
        let bytes = fixture(name);
        let limit = limit_detail(decode(&bytes));
        let factor = named_factor(&limit);
        assert_eq!(factor, expected, "{name}: {limit}");
        let options = set(DecodeOptions::default(), WorkLimit::Raised(factor));
        decode_with(&bytes, &options).unwrap_or_else(|e| panic!("{name}: {e}"));
        let one_less = set(DecodeOptions::default(), WorkLimit::Raised(factor - 1));
        assert_limit(name, decode_with(&bytes, &one_less));
    }
}

/// The option a `Limit` refusal names, raised to what it says to retry
/// with; `None` for a limit no option raises.
fn raised(options: DecodeOptions, limit: &LimitDetail) -> Option<DecodeOptions> {
    assert!(limit.kind().is_adjustable());
    options.with_retry(limit)
}

/// A caller can retry a refused file from the typed data alone, without
/// reading the message: the kind names the option, and `retry_with` the
/// limit to set it to. One retry admits each of these.
#[test]
fn a_retry_with_the_typed_hint_admits_the_file() {
    for (name, kind) in [
        (
            "tier1_work_bound/t1bomb_1024_64_88.j2k",
            LimitKind::CodeBlockWork,
        ),
        (
            "work_bound/t2skip_2048x1024_40000.j2k",
            LimitKind::PacketWork,
        ),
    ] {
        let bytes = fixture(name);
        let limit = limit_detail(decode(&bytes));
        assert_eq!(limit.kind(), kind, "{name}");
        let options = raised(DecodeOptions::default(), &limit)
            .unwrap_or_else(|| panic!("{name}: no retry for {limit:?}"));
        decode_with(&bytes, &options).unwrap_or_else(|e| panic!("{name}: {e}"));
    }
}

/// Both messages point to `Unlimited` for trusted input.
#[test]
fn the_message_names_unlimited_for_trusted_input() {
    for name in [
        "tier1_work_bound/t1bomb_1024_64_88.j2k",
        "work_bound/t2skip_2048x1024_40000.j2k",
    ] {
        let limit = limit_detail(decode(&fixture(name)));
        assert!(
            limit.message().contains("`WorkLimit::Unlimited`"),
            "{limit}"
        );
    }
}

/// A raised limit that is still too small names a factor above it.
#[test]
fn a_raised_limit_that_is_too_small_names_a_larger_factor() {
    let bytes = fixture("work_bound/sweep_rpcl_1024_64.j2k");
    let options = DecodeOptions::default().with_packet_work_limit(WorkLimit::Raised(2));
    let limit = limit_detail(decode_with(&bytes, &options));
    assert_eq!(named_factor(&limit), 3, "{limit}");
}

/// The packet bound shows only that a walk ran out, so its message names the
/// next factor up, not what the file needs: `cprl_tall_poc31` (one tile)
/// needs 32 and is told 2, and is still refused when raised to 2.
#[test]
fn the_packet_factor_is_the_next_one_up_not_what_the_file_needs() {
    let bytes = fixture("work_bound/cprl_tall_poc31.j2k");
    let limit = limit_detail(decode(&bytes));
    assert_eq!(named_factor(&limit), 2, "{limit}");
    assert!(limit.message().contains("may need more"), "{limit}");
    let options = DecodeOptions::default().with_packet_work_limit(WorkLimit::Raised(2));
    assert_limit("Raised(2)", decode_with(&bytes, &options));
}

/// POC volumes that reach more packets than the walk may visit are refused
/// before the walk, and the message names the exact factor: 1.3e8 packets is
/// 7.8 times the bound. Under `Raised(7)` it is refused, naming 8; under
/// `Raised(8)` the decode gets past the bound (the file holds 100 bytes of
/// packets, so it fails some other way).
#[test]
fn poc_volumes_name_the_factor_they_need() {
    let bytes = fixture("work_bound/pocvol_1024x512_1000_2.j2k");
    let limit = limit_detail(decode(&bytes));
    assert_eq!(named_factor(&limit), 8, "{limit}");
    let options = DecodeOptions::default().with_packet_work_limit(WorkLimit::Raised(7));
    assert_eq!(
        named_factor(&limit_detail(decode_with(&bytes, &options))),
        8
    );
    let options = DecodeOptions::default().with_packet_work_limit(WorkLimit::Raised(8));
    assert!(
        !matches!(decode_with(&bytes, &options), Err(Error::Limit(_))),
        "Raised(8) should clear the bound"
    );
}

/// The factor counts what the tiles before the refused one spent. Four
/// tiles of 512^2 in 64x64 code-blocks of 88 passes ask for 2.3e7
/// sample-passes each against a bound of 2^26 (6.7e7): the third is refused,
/// with 4.6e7 spent, and the four need 9.2e7, which is `Raised(2)`. The
/// third alone would name `Raised(1)`, which is the default.
#[test]
fn the_code_block_factor_counts_the_tiles_before_the_refused_one() {
    let bytes = t1bomb_tiled(512, 2);
    let limit = limit_detail(decode(&bytes));
    assert!(limit.message().contains("tile 2 needs"), "{limit}");
    assert_eq!(named_factor(&limit), 2, "{limit}");
    let options = DecodeOptions::default().with_code_block_work_limit(WorkLimit::Raised(2));
    decode_with(&bytes, &options).expect("within twice the bound");
}

/// The same for a POC reach. `pocspent_2tiles_60000_559.j2k`: the first tile
/// reads 60000 packets; the second reaches 3.354e7, 14432 under twice the
/// bound, so with the first tile's visits it needs `Raised(3)`. Under
/// `Raised(2)` it is refused again and still names 3.
#[test]
fn the_poc_factor_counts_the_visits_of_the_tiles_before_the_refused_one() {
    let bytes = fixture("work_bound/pocspent_2tiles_60000_559.j2k");
    let limit = limit_detail(decode(&bytes));
    assert_eq!(named_factor(&limit), 3, "{limit}");
    let options = DecodeOptions::default().with_packet_work_limit(WorkLimit::Raised(2));
    assert_eq!(
        named_factor(&limit_detail(decode_with(&bytes, &options))),
        3
    );
    let options = DecodeOptions::default().with_packet_work_limit(WorkLimit::Raised(3));
    assert!(!matches!(
        decode_with(&bytes, &options),
        Err(Error::Limit(_))
    ));
}