gwseq-io 0.2.1

Rust library for processing bigWig, bigBed, BAM, CRAM and HiC files
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
//! The file definition, containers, blocks, and the two variable-width
//! integers everything above is written in.
//!
//! Format reference: `docs/cram_format_v3.1.md` §5–§9.
//!
//! ITF8 and LTF8 live here rather than in [`crate::bytes`] on purpose. That
//! module is little-endian typed fields, and these are neither: the prefix bits
//! of the first byte say how many bytes follow, and the payload is assembled
//! *big*-endian out of them. Two encodings used by one format belong with the
//! format.
//!
//! The awkward corner of both is the widest form. ITF8's five-byte case carries
//! only the low **four** bits of its last byte, so a 32-bit value is spread
//! 4+8+8+8+4; LTF8's nine-byte case carries a bare `0xFF` prefix and eight
//! whole bytes. Getting either wrong reads plausible small numbers out of large
//! ones, which is why both have tests over their boundary values.

use bytes::Bytes;

use crate::bytes::LeCursor;
use crate::error::{Error, Result};
use crate::source::ByteSource;

/// `CRAM`, the first four bytes of the file.
pub const MAGIC: [u8; 4] = *b"CRAM";

/// Magic, major, minor, and a 20-byte file id.
pub const FILE_DEFINITION_SIZE: usize = 26;

/// The alignment start the EOF container carries, which spells `EOF` in the
/// middle of its ITF8 form (`e0 45 4f 46`). Nothing else in the format is a
/// joke, so it is worth naming rather than leaving as a bare constant.
pub const EOF_ALIGNMENT_START: i32 = 4_542_278;

/// The 38-byte end-of-file container, verbatim from §9 of the specification.
///
/// Kept whole rather than assembled: it is a constant in the format, the
/// specification prints it as a constant, and a writer that ever appears here
/// should emit these exact bytes rather than re-derive them and hope.
pub const EOF_CONTAINER: [u8; 38] = [
    0x0f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x0f, 0xe0, 0x45, 0x4f, 0x46, 0x00, 0x00, 0x00,
    0x00, 0x01, 0x00, 0x05, 0xbd, 0xd9, 0x4f, 0x00, 0x01, 0x00, 0x06, 0x06, 0x01, 0x00, 0x01, 0x00,
    0x01, 0x00, 0xee, 0x63, 0x01, 0x4b,
];

/// A container header is small, but its landmark array has no fixed width, so
/// it is read through a window rather than at a known size. This is the first
/// guess; a header that does not fit is re-read at [`HEADER_WINDOW_MAX`].
const HEADER_WINDOW: usize = 1024;

/// And the ceiling on that retry. A container with more slices than this has
/// landmarks that do not fit, and 64 KiB is roughly sixteen thousand of them.
const HEADER_WINDOW_MAX: usize = 64 * 1024;

/// The largest block this reader will inflate.
///
/// A block header names its own decompressed size, and that number is a file's
/// to choose — so it is a ceiling, not a capacity. See the crate's rule about
/// never reserving what a file asked for: Rust aborts on a failed allocation,
/// so no `Result` can carry it. 1 GiB is far above any real slice (ten thousand
/// records of a few hundred bytes) and far below anything that would abort.
pub const MAX_BLOCK_RAW_SIZE: usize = 1 << 30;

/// Read an ITF8: 0 to 4 leading one-bits say how many bytes follow.
///
/// The value is signed, and negative values (`-1` for "no reference", `-2` for
/// "many") arrive as the full 32-bit two's-complement pattern, which is why the
/// result is cast rather than sign-extended from the payload width.
pub fn read_itf8(cursor: &mut LeCursor<'_>) -> Result<i32> {
    let first = cursor.take(1)?[0];
    let value = if first & 0x80 == 0 {
        u32::from(first)
    } else if first & 0x40 == 0 {
        let rest = cursor.take(1)?;
        (u32::from(first & 0x7f) << 8) | u32::from(rest[0])
    } else if first & 0x20 == 0 {
        let rest = cursor.take(2)?;
        (u32::from(first & 0x3f) << 16) | (u32::from(rest[0]) << 8) | u32::from(rest[1])
    } else if first & 0x10 == 0 {
        let rest = cursor.take(3)?;
        (u32::from(first & 0x1f) << 24)
            | (u32::from(rest[0]) << 16)
            | (u32::from(rest[1]) << 8)
            | u32::from(rest[2])
    } else {
        // The five-byte form: the last byte gives up its high nibble, so the
        // payload is 4+8+8+8+4 bits and not 4+8+8+8+8.
        let rest = cursor.take(4)?;
        (u32::from(first & 0x0f) << 28)
            | (u32::from(rest[0]) << 20)
            | (u32::from(rest[1]) << 12)
            | (u32::from(rest[2]) << 4)
            | u32::from(rest[3] & 0x0f)
    };
    Ok(value as i32)
}

/// Read an LTF8: as ITF8, widened to nine bytes and 64 bits.
pub fn read_ltf8(cursor: &mut LeCursor<'_>) -> Result<i64> {
    let first = cursor.take(1)?[0];
    /// Assemble `n` big-endian bytes onto `high`.
    fn tail(cursor: &mut LeCursor<'_>, high: u64, n: usize) -> Result<u64> {
        let mut value = high;
        for byte in cursor.take(n)? {
            value = (value << 8) | u64::from(*byte);
        }
        Ok(value)
    }
    let value = match first.leading_ones() {
        0 => u64::from(first),
        1 => tail(cursor, u64::from(first & 0x7f), 1)?,
        2 => tail(cursor, u64::from(first & 0x3f), 2)?,
        3 => tail(cursor, u64::from(first & 0x1f), 3)?,
        4 => tail(cursor, u64::from(first & 0x0f), 4)?,
        5 => tail(cursor, u64::from(first & 0x07), 5)?,
        6 => tail(cursor, u64::from(first & 0x03), 6)?,
        7 => tail(cursor, u64::from(first & 0x01), 7)?,
        // 0xFF: the prefix is the whole byte and eight bytes follow.
        _ => tail(cursor, 0, 8)?,
    };
    Ok(value as i64)
}

/// An `array<itf8>`: a count, then that many values.
///
/// The count is checked against what is left in the buffer before anything is
/// reserved, so a file naming four billion landmarks is refused rather than
/// asked for.
pub fn read_itf8_array(cursor: &mut LeCursor<'_>) -> Result<Vec<i32>> {
    let count = read_itf8(cursor)?;
    if count < 0 {
        return Err(Error::corrupt(
            cursor.path(),
            cursor.file_offset(),
            format!("an array of {count} elements"),
        ));
    }
    let count = count as usize;
    // One byte is the shortest an ITF8 gets, so a count above what is left
    // cannot be honoured whatever the values are.
    if count > cursor.remaining() {
        return Err(Error::corrupt(
            cursor.path(),
            cursor.file_offset(),
            format!(
                "an array of {count} elements with {} bytes left",
                cursor.remaining()
            ),
        ));
    }
    let mut out = Vec::with_capacity(count);
    for _ in 0..count {
        out.push(read_itf8(cursor)?);
    }
    Ok(out)
}

/// The first 26 bytes: what the file is, and which version of it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileDefinition {
    pub major: u8,
    pub minor: u8,
    /// Whatever the writer put there — a file name, a checksum, or nothing.
    pub file_id: String,
}

impl FileDefinition {
    /// Parse and version-check the file definition.
    ///
    /// 3.0 and 3.1 are read. 2.x and 1.0 are refused *by name*: they are real
    /// CRAM and this reader could grow into them, so "unsupported version" is
    /// the honest answer and "not a CRAM file" would not be. The two differ
    /// from 3.x in more than a version byte — no CRC32 on container or block
    /// headers, and a per-record tag path (`TC`/`TN`) rather than the `TD`
    /// dictionary — so accepting them here would only move the failure.
    pub fn parse(data: &[u8], path: &str) -> Result<Self> {
        if data.len() < FILE_DEFINITION_SIZE {
            return Err(Error::format(
                path,
                "file is too short to carry a cram file definition",
            ));
        }
        if data[..4] != MAGIC {
            return Err(Error::format(path, "not a cram file"));
        }
        let (major, minor) = (data[4], data[5]);
        if major != 3 {
            return Err(Error::Unsupported(format!(
                "{path}: cram {major}.{minor}; this reader handles 3.0 and 3.1"
            )));
        }
        if minor > 1 {
            return Err(Error::Unsupported(format!(
                "{path}: cram {major}.{minor}; this reader handles 3.0 and 3.1"
            )));
        }
        let id = &data[6..FILE_DEFINITION_SIZE];
        let end = memchr::memchr(0, id).unwrap_or(id.len());
        Ok(Self {
            major,
            minor,
            file_id: String::from_utf8_lossy(&id[..end]).into_owned(),
        })
    }
}

/// A container header, plus where it sits and how long it is.
///
/// `offset` and `header_len` are not fields of the format: they are what turns
/// a landmark — a byte offset *from the end of this header* — into a file
/// offset, which is the only way anything is found in a CRAM.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContainerHeader {
    pub length: i32,
    pub ref_id: i32,
    pub start: i32,
    pub span: i32,
    pub n_records: i32,
    pub record_counter: i64,
    pub bases: i64,
    pub n_blocks: i32,
    pub landmarks: Vec<i32>,
    pub offset: u64,
    pub header_len: usize,
}

impl ContainerHeader {
    /// Where this container's blocks begin.
    pub fn blocks_offset(&self) -> u64 {
        self.offset + self.header_len as u64
    }

    /// Where the next container begins.
    pub fn end_offset(&self) -> u64 {
        self.blocks_offset() + self.length.max(0) as u64
    }

    /// The file offset of the `n`th slice, from its landmark.
    pub fn landmark_offset(&self, landmark: i32) -> u64 {
        self.blocks_offset() + landmark.max(0) as u64
    }

    /// The end-of-file container: no records, unmapped, and that alignment
    /// start.
    ///
    /// All three are checked rather than the start alone, so a real container
    /// that happens to be placed at 4 542 278 is not mistaken for the end of
    /// the file.
    pub fn is_eof(&self) -> bool {
        self.n_records == 0 && self.ref_id == -1 && self.start == EOF_ALIGNMENT_START
    }

    /// Read the container header at `offset`.
    ///
    /// Two passes at most: the landmark array is variable-width, so the window
    /// is a guess, and a header that does not fit it is read again at
    /// a fixed ceiling rather than growing without a bound.
    pub fn read(source: &dyn ByteSource, offset: u64) -> Result<Self> {
        match Self::read_within(source, offset, HEADER_WINDOW) {
            // Only a header that ran off the end of the window is worth a
            // second read. A CRC mismatch is a corrupt header and a wider
            // window cannot mend it, so retrying it is a wasted read that
            // reports the same failure.
            Err(Error::Corrupt { ref what, .. }) if what.contains("ran past the end") => {
                Self::read_within(source, offset, HEADER_WINDOW_MAX)
            }
            other => other,
        }
    }

    fn read_within(source: &dyn ByteSource, offset: u64, window: usize) -> Result<Self> {
        let path = source.path();
        let data = source.read_at(offset, window)?;
        let mut cursor = LeCursor::new(&data, offset, path);
        let length = cursor.read_i32()?;
        let ref_id = read_itf8(&mut cursor)?;
        let start = read_itf8(&mut cursor)?;
        let span = read_itf8(&mut cursor)?;
        let n_records = read_itf8(&mut cursor)?;
        let record_counter = read_ltf8(&mut cursor)?;
        let bases = read_ltf8(&mut cursor)?;
        let n_blocks = read_itf8(&mut cursor)?;
        let landmarks = read_itf8_array(&mut cursor)?;
        // The CRC32 covers every byte of the header before it. Checked here
        // because a container header is the one structure whose corruption
        // sends every later read to the wrong offset.
        let want = cursor.read_u32()?;
        let got = crc32(&data[..cursor.position() - 4]);
        if want != got {
            return Err(Error::corrupt(
                path,
                offset,
                format!("container header checksum is {got:#010x}, not the {want:#010x} it claims"),
            ));
        }
        if length < 0 || n_blocks < 0 {
            return Err(Error::corrupt(
                path,
                offset,
                format!("container declares {length} bytes in {n_blocks} blocks"),
            ));
        }
        Ok(Self {
            length,
            ref_id,
            start,
            span,
            n_records,
            record_counter,
            bases,
            n_blocks,
            landmarks,
            offset,
            header_len: cursor.position(),
        })
    }
}

/// The block compression method, as §8's `method` byte.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompressionMethod {
    Raw,
    Gzip,
    Bzip2,
    Lzma,
    Rans4x8,
    Rans4x16,
    Arith,
    Fqzcomp,
    NameTok,
}

impl CompressionMethod {
    pub fn from_byte(byte: u8, path: &str, offset: u64) -> Result<Self> {
        Ok(match byte {
            0 => Self::Raw,
            1 => Self::Gzip,
            2 => Self::Bzip2,
            3 => Self::Lzma,
            4 => Self::Rans4x8,
            5 => Self::Rans4x16,
            6 => Self::Arith,
            7 => Self::Fqzcomp,
            8 => Self::NameTok,
            other => {
                return Err(Error::corrupt(
                    path,
                    offset,
                    format!("block compression method {other} is not one the format defines"),
                ))
            }
        })
    }

    /// What to call it in an error a user reads.
    pub fn name(self) -> &'static str {
        match self {
            Self::Raw => "raw",
            Self::Gzip => "gzip",
            Self::Bzip2 => "bzip2",
            Self::Lzma => "lzma",
            Self::Rans4x8 => "rans4x8",
            Self::Rans4x16 => "rans4x16",
            Self::Arith => "adaptive arithmetic coding",
            Self::Fqzcomp => "fqzcomp",
            Self::NameTok => "the name tokeniser",
        }
    }
}

/// The block content type, as §8.1.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlockContentType {
    FileHeader,
    CompressionHeader,
    SliceHeader,
    Reserved,
    External,
    Core,
}

impl BlockContentType {
    pub fn from_byte(byte: u8, path: &str, offset: u64) -> Result<Self> {
        Ok(match byte {
            0 => Self::FileHeader,
            1 => Self::CompressionHeader,
            2 => Self::SliceHeader,
            3 => Self::Reserved,
            4 => Self::External,
            5 => Self::Core,
            other => {
                return Err(Error::corrupt(
                    path,
                    offset,
                    format!("block content type {other} is not one the format defines"),
                ))
            }
        })
    }
}

/// One block: its header, and its data with the block compression undone.
#[derive(Debug, Clone)]
pub struct Block {
    pub method: CompressionMethod,
    pub content_type: BlockContentType,
    pub content_id: i32,
    pub data: Bytes,
    /// Bytes this block occupied in the file, header and CRC included, so a
    /// walk of a container's blocks can step to the next without re-parsing.
    pub total_size: usize,
}

impl Block {
    /// Parse the block at the start of `data`, decompressing it.
    ///
    /// `offset` is where `data` begins in the file, for error messages.
    pub fn parse(data: &[u8], offset: u64, path: &str) -> Result<Self> {
        let mut cursor = LeCursor::new(data, offset, path);
        let method = CompressionMethod::from_byte(cursor.take(1)?[0], path, offset)?;
        let content_type = BlockContentType::from_byte(cursor.take(1)?[0], path, offset)?;
        let content_id = read_itf8(&mut cursor)?;
        let compressed_size = read_itf8(&mut cursor)?;
        let raw_size = read_itf8(&mut cursor)?;
        if compressed_size < 0 || raw_size < 0 {
            return Err(Error::corrupt(
                path,
                offset,
                format!("block declares {compressed_size} compressed bytes and {raw_size} raw"),
            ));
        }
        let (compressed_size, raw_size) = (compressed_size as usize, raw_size as usize);
        if raw_size > MAX_BLOCK_RAW_SIZE {
            return Err(Error::corrupt(
                path,
                offset,
                format!("block declares {raw_size} raw bytes, past this reader's {MAX_BLOCK_RAW_SIZE}-byte ceiling"),
            ));
        }
        let body_at = cursor.file_offset();
        let body = cursor.take(compressed_size)?;
        let want = cursor.read_u32()?;
        let got = crc32(&data[..cursor.position() - 4]);
        if want != got {
            return Err(Error::corrupt(
                path,
                offset,
                format!("block checksum is {got:#010x}, not the {want:#010x} it claims"),
            ));
        }

        // §8: a block whose raw size is zero is empty whatever its method byte
        // says. Real files do carry gzip-marked empty blocks, and inflating
        // nothing fails.
        let data = if raw_size == 0 {
            Bytes::new()
        } else {
            super::codecs::decode(method, body, raw_size, path, body_at)?
        };
        Ok(Self {
            method,
            content_type,
            content_id,
            data,
            total_size: cursor.position(),
        })
    }
}

/// CRC32 as the format defines it, which is the one gzip uses.
pub fn crc32(data: &[u8]) -> u32 {
    let mut crc = flate2::Crc::new();
    crc.update(data);
    crc.sum()
}

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

    fn itf8(bytes: &[u8]) -> i32 {
        let mut cursor = LeCursor::new(bytes, 0, "test");
        read_itf8(&mut cursor).expect("itf8")
    }

    fn ltf8(bytes: &[u8]) -> i64 {
        let mut cursor = LeCursor::new(bytes, 0, "test");
        read_ltf8(&mut cursor).expect("ltf8")
    }

    #[test]
    fn itf8_reads_each_of_its_five_widths() {
        assert_eq!(itf8(&[0x00]), 0);
        assert_eq!(itf8(&[0x7f]), 127);
        assert_eq!(itf8(&[0x80, 0x80]), 128);
        assert_eq!(itf8(&[0xbf, 0xff]), 0x3fff);
        assert_eq!(itf8(&[0xc0, 0x40, 0x00]), 0x4000);
        assert_eq!(itf8(&[0xdf, 0xff, 0xff]), 0x1f_ffff);
        assert_eq!(itf8(&[0xe0, 0x20, 0x00, 0x00]), 0x20_0000);
        assert_eq!(itf8(&[0xef, 0xff, 0xff, 0xff]), 0x0fff_ffff);
        assert_eq!(itf8(&[0xf1, 0x00, 0x00, 0x00, 0x00]), 0x1000_0000);
    }

    /// The five-byte form spends only four bits of its last byte. A reader that
    /// takes all eight gets a value sixteen times too large with the low nibble
    /// of the wrong byte in it, and every one of these would still parse.
    #[test]
    fn the_widest_itf8_takes_four_bits_from_its_last_byte() {
        assert_eq!(itf8(&[0xff, 0xff, 0xff, 0xff, 0x0f]), -1);
        assert_eq!(itf8(&[0xff, 0xff, 0xff, 0xff, 0x0e]), -2);
        assert_eq!(itf8(&[0xf7, 0xff, 0xff, 0xff, 0x0f]), i32::MAX);
        assert_eq!(itf8(&[0xf8, 0x00, 0x00, 0x00, 0x00]), i32::MIN);
        // The high nibble of the last byte is not part of the value.
        assert_eq!(itf8(&[0xf0, 0x00, 0x00, 0x00, 0xf1]), 1);
    }

    /// From §9: the EOF container's ref id and alignment start, as the
    /// specification prints them.
    #[test]
    fn the_eof_containers_own_itf8_fields_read_as_the_spec_says() {
        assert_eq!(itf8(&[0xff, 0xff, 0xff, 0xff, 0x0f]), -1);
        assert_eq!(itf8(&[0xe0, 0x45, 0x4f, 0x46]), EOF_ALIGNMENT_START);
    }

    #[test]
    fn ltf8_reads_each_of_its_nine_widths() {
        assert_eq!(ltf8(&[0x00]), 0);
        assert_eq!(ltf8(&[0x7f]), 127);
        assert_eq!(ltf8(&[0x80, 0x80]), 128);
        assert_eq!(ltf8(&[0xc0, 0x40, 0x00]), 0x4000);
        assert_eq!(ltf8(&[0xe0, 0x20, 0x00, 0x00]), 0x20_0000);
        // Unlike ITF8, LTF8's five-byte form spends every bit of its last
        // byte — the two encodings genuinely differ here.
        assert_eq!(ltf8(&[0xf0, 0x10, 0x00, 0x00, 0x00]), 0x1000_0000);
        assert_eq!(ltf8(&[0xf0, 0x00, 0x00, 0x00, 0xff]), 0xff);
        assert_eq!(itf8(&[0xf0, 0x00, 0x00, 0x00, 0xff]), 0x0f);
        assert_eq!(ltf8(&[0xf8, 0x08, 0x00, 0x00, 0x00, 0x00]), 0x8_0000_0000);
        assert_eq!(
            ltf8(&[0xfc, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00]),
            0x400_0000_0000
        );
        assert_eq!(
            ltf8(&[0xfe, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
            0x2_0000_0000_0000
        );
        // 0xFF: the prefix is the whole first byte, eight bytes of payload.
        assert_eq!(
            ltf8(&[0xff, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
            i64::MAX
        );
        assert_eq!(
            ltf8(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
            -1
        );
    }

    #[test]
    fn a_truncated_variable_integer_is_an_error_not_a_short_value() {
        let mut cursor = LeCursor::new(&[0xf0, 0x10], 0, "test");
        assert!(read_itf8(&mut cursor).is_err());
        let mut cursor = LeCursor::new(&[0xff, 0x01], 0, "test");
        assert!(read_ltf8(&mut cursor).is_err());
    }

    #[test]
    fn an_array_longer_than_its_buffer_is_refused_before_it_is_reserved() {
        // 0x7f elements, and two bytes to hold them.
        let mut cursor = LeCursor::new(&[0x7f, 0x00, 0x00], 0, "test");
        assert!(read_itf8_array(&mut cursor).is_err());
    }

    #[test]
    fn the_file_definition_reads_its_version_and_id() {
        let mut data = vec![0u8; FILE_DEFINITION_SIZE];
        data[..4].copy_from_slice(b"CRAM");
        data[4] = 3;
        data[5] = 1;
        data[6..10].copy_from_slice(b"abcd");
        let def = FileDefinition::parse(&data, "test").expect("parses");
        assert_eq!((def.major, def.minor), (3, 1));
        assert_eq!(def.file_id, "abcd");
    }

    #[test]
    fn older_crams_are_refused_by_version_rather_than_as_the_wrong_format() {
        let mut data = vec![0u8; FILE_DEFINITION_SIZE];
        data[..4].copy_from_slice(b"CRAM");
        for (major, minor) in [(1u8, 0u8), (2, 0), (2, 1), (3, 2), (4, 0)] {
            data[4] = major;
            data[5] = minor;
            match FileDefinition::parse(&data, "test") {
                Err(Error::Unsupported(message)) => {
                    assert!(
                        message.contains(&format!("cram {major}.{minor}")),
                        "{message}"
                    );
                }
                other => panic!("cram {major}.{minor} gave {other:?}"),
            }
        }
    }

    /// The EOF container from §9, parsed as a container header rather than
    /// compared byte for byte — which is what checks the reader agrees with the
    /// specification's own worked example, CRC included.
    #[test]
    fn the_spec_eof_container_parses_and_says_it_is_the_end() {
        let source = crate::source::testing::MemorySource::new(EOF_CONTAINER.to_vec());
        let header = ContainerHeader::read(&source, 0).expect("eof container header");
        assert_eq!(header.length, 15);
        assert_eq!(header.ref_id, -1);
        assert_eq!(header.start, EOF_ALIGNMENT_START);
        assert_eq!(header.n_records, 0);
        assert_eq!(header.n_blocks, 1);
        assert!(header.landmarks.is_empty());
        assert!(header.is_eof());
        assert_eq!(header.header_len, 23);

        // And its one block, the empty compression header.
        let block = Block::parse(&EOF_CONTAINER[23..], 23, "test").expect("eof block");
        assert_eq!(block.content_type, BlockContentType::CompressionHeader);
        assert_eq!(block.method, CompressionMethod::Raw);
        assert_eq!(block.data.len(), 6);
        assert_eq!(block.total_size, 15);
    }

    #[test]
    fn a_container_header_with_a_wrong_checksum_is_refused() {
        let mut bytes = EOF_CONTAINER;
        bytes[5] ^= 0xff;
        let source = crate::source::testing::MemorySource::new(bytes.to_vec());
        assert!(ContainerHeader::read(&source, 0).is_err());
    }

    #[test]
    fn a_block_with_a_wrong_checksum_is_refused() {
        let mut bytes = EOF_CONTAINER[23..].to_vec();
        let last = bytes.len() - 1;
        bytes[last] ^= 0xff;
        assert!(Block::parse(&bytes, 0, "test").is_err());
    }
}