Skip to main content

xue/
format.rs

1//! The Xue container's byte layout, shared by the decoder and the encoder.
2//!
3//! `docs/format.md` is the normative spec. This module is the one place the
4//! spec's offsets and widths are written down: the decoder unpacks structures
5//! through it and the native encoder packs them through it, so a field can
6//! never drift between the two halves of the crate.
7//!
8//! Everything here is pure byte conversion. It validates only what a field's
9//! own encoding demands — a magic number, a reserved word, an enum's code —
10//! and never allocates from a file value. Cross-section geometry, the
11//! metadata grid, dependency chains and every other semantic rule stay in
12//! [`crate::decode`], which is what actually reads untrusted files.
13
14use std::fmt;
15
16pub const MAGIC: &[u8; 8] = b"XUE\0\0\0\0\0";
17/// The plane-major container. Still read; no longer written.
18pub const VERSION: u16 = 1;
19/// The tiled container: a payload is a chunk — one tile of one temporal group
20/// for one variable — not a whole plane.
21pub const VERSION_V2: u16 = 2;
22pub const HEADER_SIZE: usize = 80;
23pub const INDEX_MAGIC: &[u8; 4] = b"IDX1";
24pub const INDEX_HEADER_SIZE: usize = 16;
25pub const INDEX_VERSION: u16 = 1;
26pub const ENTRY_SIZE: usize = 40;
27pub const NO_DEPENDENCY: u16 = 0xFFFF;
28pub const FLAG_ZSTD_CHECKSUM: u8 = 0x01;
29
30pub const INDEX_MAGIC_V2: &[u8; 4] = b"IDX2";
31pub const INDEX_HEADER_SIZE_V2: usize = 32;
32pub const INDEX_VERSION_V2: u16 = 2;
33pub const VARIABLE_ENTRY_SIZE: usize = 4;
34pub const GROUP_ENTRY_SIZE: usize = 4;
35pub const CHUNK_ENTRY_SIZE: usize = 8;
36
37/// Safety limit for one decoded plane: 64M points. A chunk is one tile of one
38/// group, so it is bounded by the same limit times the group length, and a
39/// group holds at most 255 frames.
40pub const MAX_PLANE_LENGTH: u64 = 64 * 1024 * 1024;
41/// The coarsest time-axis unit, and the only one schema versions 1 and 2 can
42/// describe. A schemaVersion 3 axis names its own unit, which must divide it.
43pub const HOUR_SECONDS: u32 = 3600;
44
45/// A file that cannot be read as Xue v1, at any layer: a malformed byte
46/// layout here, or a violated structural rule in [`crate::decode`].
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct DecodeError(pub String);
49
50impl fmt::Display for DecodeError {
51    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
52        write!(formatter, "{}", self.0)
53    }
54}
55
56impl std::error::Error for DecodeError {}
57
58pub(crate) fn err(message: impl Into<String>) -> DecodeError {
59    DecodeError(message.into())
60}
61
62// -- primitives --------------------------------------------------------------
63
64pub(crate) fn read_u16(data: &[u8], offset: usize) -> u16 {
65    u16::from_le_bytes([data[offset], data[offset + 1]])
66}
67
68pub(crate) fn read_u32(data: &[u8], offset: usize) -> u32 {
69    u32::from_le_bytes([
70        data[offset],
71        data[offset + 1],
72        data[offset + 2],
73        data[offset + 3],
74    ])
75}
76
77pub(crate) fn read_u64(data: &[u8], offset: usize) -> u64 {
78    let mut bytes = [0u8; 8];
79    bytes.copy_from_slice(&data[offset..offset + 8]);
80    u64::from_le_bytes(bytes)
81}
82
83/// The next multiple of 8 at or above `value`, or `None` on overflow.
84///
85/// Every section boundary in the container is 8-byte aligned, so both halves
86/// round the same way: the decoder turns `None` into a rejected file, the
87/// encoder into a bundle error.
88pub fn align8(value: u64) -> Option<u64> {
89    value.checked_add(7).map(|sum| sum / 8 * 8)
90}
91
92/// Greatest common divisor, used on both sides to reduce a time axis to the
93/// coarsest unit that expresses every offset exactly.
94pub fn gcd(left: u64, right: u64) -> u64 {
95    let (mut left, mut right) = (left, right);
96    while right != 0 {
97        (left, right) = (right, left % right);
98    }
99    left
100}
101
102pub fn crc32(bytes: &[u8]) -> u32 {
103    crc32fast::hash(bytes)
104}
105
106// -- enums -------------------------------------------------------------------
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum Predictor {
110    Raw = 0,
111    Anchor = 1,
112    Previous = 2,
113    Zero = 3,
114}
115
116impl Predictor {
117    pub fn parse(value: u8) -> Result<Self, DecodeError> {
118        match value {
119            0 => Ok(Self::Raw),
120            1 => Ok(Self::Anchor),
121            2 => Ok(Self::Previous),
122            3 => Ok(Self::Zero),
123            other => Err(err(format!("unknown predictor {other}"))),
124        }
125    }
126
127    pub fn code(self) -> u8 {
128        self as u8
129    }
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub enum Compression {
134    None = 0,
135    Zstd = 1,
136    ZstdDict = 2,
137}
138
139impl Compression {
140    pub fn parse(value: u8) -> Result<Self, DecodeError> {
141        match value {
142            0 => Ok(Self::None),
143            1 => Ok(Self::Zstd),
144            2 => Ok(Self::ZstdDict),
145            other => Err(err(format!("unknown compression {other}"))),
146        }
147    }
148
149    pub fn code(self) -> u8 {
150        self as u8
151    }
152}
153
154// -- FixedHeader -------------------------------------------------------------
155
156/// The 80-byte fixed header's section geometry, plus the container version
157/// that says how to read the index below it.
158///
159/// `magic`, `headerSize` and the reserved flags word are checked by
160/// [`FixedHeader::unpack`] and written by [`FixedHeader::pack`], so they are
161/// not fields. Whether the offsets are *consistent with each other* is
162/// [`crate::decode`]'s question, not this module's.
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164pub struct FixedHeader {
165    /// [`VERSION`] or [`VERSION_V2`]; nothing else parses.
166    pub version: u16,
167    pub file_size: u64,
168    pub metadata_offset: u64,
169    pub metadata_length: u64,
170    pub index_offset: u64,
171    pub index_length: u64,
172    pub data_offset: u64,
173    pub dictionary_offset: u64,
174    pub dictionary_length: u64,
175}
176
177impl FixedHeader {
178    pub fn unpack(data: &[u8]) -> Result<Self, DecodeError> {
179        if data.len() < HEADER_SIZE {
180            return Err(err("file is smaller than the fixed header"));
181        }
182        if &data[0..8] != MAGIC {
183            return Err(err("invalid magic, not a Xue file"));
184        }
185        let version = read_u16(data, 8);
186        if version != VERSION && version != VERSION_V2 {
187            return Err(err("unsupported Xue version"));
188        }
189        if read_u16(data, 10) as usize != HEADER_SIZE {
190            return Err(err("headerSize must be 80"));
191        }
192        if read_u32(data, 12) != 0 {
193            return Err(err("header flags must be 0"));
194        }
195        Ok(FixedHeader {
196            version,
197            file_size: read_u64(data, 16),
198            metadata_offset: read_u64(data, 24),
199            metadata_length: read_u64(data, 32),
200            index_offset: read_u64(data, 40),
201            index_length: read_u64(data, 48),
202            data_offset: read_u64(data, 56),
203            dictionary_offset: read_u64(data, 64),
204            dictionary_length: read_u64(data, 72),
205        })
206    }
207
208    pub fn pack(&self) -> [u8; HEADER_SIZE] {
209        let mut buffer = [0u8; HEADER_SIZE];
210        buffer[0..8].copy_from_slice(MAGIC);
211        buffer[8..10].copy_from_slice(&self.version.to_le_bytes());
212        buffer[10..12].copy_from_slice(&(HEADER_SIZE as u16).to_le_bytes());
213        // flags stay zero in both versions.
214        buffer[16..24].copy_from_slice(&self.file_size.to_le_bytes());
215        buffer[24..32].copy_from_slice(&self.metadata_offset.to_le_bytes());
216        buffer[32..40].copy_from_slice(&self.metadata_length.to_le_bytes());
217        buffer[40..48].copy_from_slice(&self.index_offset.to_le_bytes());
218        buffer[48..56].copy_from_slice(&self.index_length.to_le_bytes());
219        buffer[56..64].copy_from_slice(&self.data_offset.to_le_bytes());
220        buffer[64..72].copy_from_slice(&self.dictionary_offset.to_le_bytes());
221        buffer[72..80].copy_from_slice(&self.dictionary_length.to_le_bytes());
222        buffer
223    }
224}
225
226// -- IndexHeader -------------------------------------------------------------
227
228/// The 16-byte index header. Its magic, entry size, version and reserved word
229/// are fixed for v1, so `entry_count` is the only field it carries.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231pub struct IndexHeader {
232    pub entry_count: u32,
233}
234
235impl IndexHeader {
236    pub fn unpack(data: &[u8]) -> Result<Self, DecodeError> {
237        if data.len() < INDEX_HEADER_SIZE {
238            return Err(err("index is smaller than its header"));
239        }
240        if &data[0..4] != INDEX_MAGIC {
241            return Err(err("invalid index magic"));
242        }
243        if read_u16(data, 4) as usize != ENTRY_SIZE {
244            return Err(err("index entrySize must be 40 for v1"));
245        }
246        if read_u16(data, 6) != INDEX_VERSION {
247            return Err(err("index version must be 1"));
248        }
249        let entry_count = read_u32(data, 8);
250        if read_u32(data, 12) != 0 {
251            return Err(err("index reserved must be 0"));
252        }
253        Ok(IndexHeader { entry_count })
254    }
255
256    pub fn pack(&self) -> [u8; INDEX_HEADER_SIZE] {
257        let mut buffer = [0u8; INDEX_HEADER_SIZE];
258        buffer[0..4].copy_from_slice(INDEX_MAGIC);
259        buffer[4..6].copy_from_slice(&(ENTRY_SIZE as u16).to_le_bytes());
260        buffer[6..8].copy_from_slice(&INDEX_VERSION.to_le_bytes());
261        buffer[8..12].copy_from_slice(&self.entry_count.to_le_bytes());
262        // reserved stays zero.
263        buffer
264    }
265}
266
267// -- v2 index ----------------------------------------------------------------
268
269/// The 32-byte v2 index header: the tiling, the partition sizes and the one
270/// compression every chunk uses.
271///
272/// `tileColumns`, `tileRows` and `tileCount` are derived from the metadata
273/// grid and never stored, so the geometry has exactly one encoding.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275pub struct IndexHeaderV2 {
276    pub tile_width: u16,
277    pub tile_height: u16,
278    pub group_count: u16,
279    pub variable_count: u8,
280    pub compression: Compression,
281    pub chunk_count: u32,
282}
283
284impl IndexHeaderV2 {
285    pub fn unpack(data: &[u8]) -> Result<Self, DecodeError> {
286        if data.len() < INDEX_HEADER_SIZE_V2 {
287            return Err(err("index is smaller than its header"));
288        }
289        if &data[0..4] != INDEX_MAGIC_V2 {
290            return Err(err("invalid index magic"));
291        }
292        if read_u16(data, 4) != INDEX_VERSION_V2 {
293            return Err(err("index version must be 2"));
294        }
295        if read_u16(data, 6) as usize != INDEX_HEADER_SIZE_V2 {
296            return Err(err("index headerSize must be 32 for v2"));
297        }
298        if read_u32(data, 20) != 0 || read_u64(data, 24) != 0 {
299            return Err(err("index reserved words must be 0"));
300        }
301        Ok(IndexHeaderV2 {
302            tile_width: read_u16(data, 8),
303            tile_height: read_u16(data, 10),
304            group_count: read_u16(data, 12),
305            variable_count: data[14],
306            compression: Compression::parse(data[15])?,
307            chunk_count: read_u32(data, 16),
308        })
309    }
310
311    pub fn pack(&self) -> [u8; INDEX_HEADER_SIZE_V2] {
312        let mut buffer = [0u8; INDEX_HEADER_SIZE_V2];
313        buffer[0..4].copy_from_slice(INDEX_MAGIC_V2);
314        buffer[4..6].copy_from_slice(&INDEX_VERSION_V2.to_le_bytes());
315        buffer[6..8].copy_from_slice(&(INDEX_HEADER_SIZE_V2 as u16).to_le_bytes());
316        buffer[8..10].copy_from_slice(&self.tile_width.to_le_bytes());
317        buffer[10..12].copy_from_slice(&self.tile_height.to_le_bytes());
318        buffer[12..14].copy_from_slice(&self.group_count.to_le_bytes());
319        buffer[14] = self.variable_count;
320        buffer[15] = self.compression.code();
321        buffer[16..20].copy_from_slice(&self.chunk_count.to_le_bytes());
322        // reserved words stay zero.
323        buffer
324    }
325}
326
327/// One 4-byte variable entry: an id and the predictor every chunk of that
328/// variable is coded with.
329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330pub struct VariableEntry {
331    pub variable_id: u8,
332    pub predictor: Predictor,
333}
334
335impl VariableEntry {
336    pub fn unpack(raw: &[u8]) -> Result<Self, DecodeError> {
337        if raw.len() < VARIABLE_ENTRY_SIZE {
338            return Err(err("variable entry is truncated"));
339        }
340        if read_u16(raw, 2) != 0 {
341            return Err(err("variable entry reserved must be 0"));
342        }
343        let predictor = Predictor::parse(raw[1])?;
344        // A v2 chunk is decompressed whole, so an anchor buys no random
345        // access: one chunk has exactly one valid encoding.
346        if !matches!(predictor, Predictor::Raw | Predictor::Previous) {
347            return Err(err("v2 predictors must be RAW or PREVIOUS"));
348        }
349        Ok(VariableEntry {
350            variable_id: raw[0],
351            predictor,
352        })
353    }
354
355    pub fn pack(&self) -> [u8; VARIABLE_ENTRY_SIZE] {
356        let mut buffer = [0u8; VARIABLE_ENTRY_SIZE];
357        buffer[0] = self.variable_id;
358        buffer[1] = self.predictor.code();
359        buffer
360    }
361}
362
363/// One 4-byte group entry: a run of consecutive frames on the shared axis.
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365pub struct GroupEntry {
366    pub first_frame: u16,
367    pub frame_count: u8,
368}
369
370impl GroupEntry {
371    pub fn unpack(raw: &[u8]) -> Result<Self, DecodeError> {
372        if raw.len() < GROUP_ENTRY_SIZE {
373            return Err(err("group entry is truncated"));
374        }
375        if raw[3] != 0 {
376            return Err(err("group entry reserved must be 0"));
377        }
378        Ok(GroupEntry {
379            first_frame: read_u16(raw, 0),
380            frame_count: raw[2],
381        })
382    }
383
384    pub fn pack(&self) -> [u8; GROUP_ENTRY_SIZE] {
385        let mut buffer = [0u8; GROUP_ENTRY_SIZE];
386        buffer[0..2].copy_from_slice(&self.first_frame.to_le_bytes());
387        buffer[2] = self.frame_count;
388        buffer
389    }
390}
391
392/// One 8-byte chunk entry. A chunk's *offset* is not stored: the physical
393/// order is the spec's and chunks are strictly adjacent, so an offset is the
394/// prefix sum of the lengths before it.
395#[derive(Debug, Clone, Copy, PartialEq, Eq)]
396pub struct ChunkEntry {
397    pub compressed_length: u32,
398    pub crc32: u32,
399}
400
401impl ChunkEntry {
402    pub fn unpack(raw: &[u8]) -> Result<Self, DecodeError> {
403        if raw.len() < CHUNK_ENTRY_SIZE {
404            return Err(err("chunk entry is truncated"));
405        }
406        Ok(ChunkEntry {
407            compressed_length: read_u32(raw, 0),
408            crc32: read_u32(raw, 4),
409        })
410    }
411
412    pub fn pack(&self) -> [u8; CHUNK_ENTRY_SIZE] {
413        let mut buffer = [0u8; CHUNK_ENTRY_SIZE];
414        buffer[0..4].copy_from_slice(&self.compressed_length.to_le_bytes());
415        buffer[4..8].copy_from_slice(&self.crc32.to_le_bytes());
416        buffer
417    }
418}
419
420/// How a grid is cut into tiles: derived arithmetic over the metadata grid
421/// and the index header, stored nowhere.
422///
423/// Tiles start at the grid's first cell and are laid out row-major; the last
424/// column and the last row are clipped to the grid, so a tile size need not
425/// divide the grid. A tile is cells, never degrees — its geographic footprint
426/// follows from the grid block, and the horizontal wrap of a global grid is a
427/// property of the grid, not of any tile.
428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
429pub struct TileGeometry {
430    pub width: u32,
431    pub height: u32,
432    pub tile_width: u32,
433    pub tile_height: u32,
434}
435
436impl TileGeometry {
437    pub fn new(
438        width: u32,
439        height: u32,
440        tile_width: u32,
441        tile_height: u32,
442    ) -> Result<Self, DecodeError> {
443        if tile_width == 0 || tile_height == 0 || tile_width > width || tile_height > height {
444            return Err(err("tile size must be between 1 and the grid dimensions"));
445        }
446        Ok(TileGeometry {
447            width,
448            height,
449            tile_width,
450            tile_height,
451        })
452    }
453
454    pub fn columns(&self) -> u32 {
455        self.width.div_ceil(self.tile_width)
456    }
457
458    pub fn rows(&self) -> u32 {
459        self.height.div_ceil(self.tile_height)
460    }
461
462    pub fn count(&self) -> u32 {
463        self.columns() * self.rows()
464    }
465
466    /// The (row, column) of a tile's north-west cell in the grid.
467    pub fn origin(&self, tile: u32) -> (u32, u32) {
468        (
469            (tile / self.columns()) * self.tile_height,
470            (tile % self.columns()) * self.tile_width,
471        )
472    }
473
474    /// The clipped (height, width) of a tile in cells. Saturating, so a
475    /// tile past the last one is empty rather than an overflow; every tile
476    /// below `count()` starts inside the grid and is unaffected.
477    pub fn shape(&self, tile: u32) -> (u32, u32) {
478        let (row, column) = self.origin(tile);
479        (
480            self.tile_height.min(self.height.saturating_sub(row)),
481            self.tile_width.min(self.width.saturating_sub(column)),
482        )
483    }
484
485    /// The tile containing a grid cell.
486    pub fn tile_of(&self, row: u32, column: u32) -> Result<u32, DecodeError> {
487        if row >= self.height || column >= self.width {
488            return Err(err("cell is outside the grid"));
489        }
490        Ok((row / self.tile_height) * self.columns() + column / self.tile_width)
491    }
492}
493
494/// A rectangle of tiles, the unit a viewport asks for. Inclusive of both ends.
495#[derive(Debug, Clone, Copy, PartialEq, Eq)]
496pub struct TileRect {
497    pub first_column: u32,
498    pub first_row: u32,
499    pub last_column: u32,
500    pub last_row: u32,
501}
502
503impl TileRect {
504    /// The tiles a grid rectangle touches, clamped to the geometry.
505    pub fn covering(
506        geometry: &TileGeometry,
507        row: u32,
508        column: u32,
509        height: u32,
510        width: u32,
511    ) -> Self {
512        let last_row = (row + height.saturating_sub(1)).min(geometry.height - 1);
513        let last_column = (column + width.saturating_sub(1)).min(geometry.width - 1);
514        TileRect {
515            first_column: column.min(geometry.width - 1) / geometry.tile_width,
516            first_row: row.min(geometry.height - 1) / geometry.tile_height,
517            last_column: last_column / geometry.tile_width,
518            last_row: last_row / geometry.tile_height,
519        }
520    }
521
522    pub fn contains(&self, geometry: &TileGeometry, tile: u32) -> bool {
523        let (row, column) = (tile / geometry.columns(), tile % geometry.columns());
524        (self.first_row..=self.last_row).contains(&row)
525            && (self.first_column..=self.last_column).contains(&column)
526    }
527}
528
529// -- PlaneEntry --------------------------------------------------------------
530
531/// One 40-byte index entry: where a plane's payload is, how to undo its
532/// coding, and what the decoded bytes must check out as.
533#[derive(Debug, Clone, Copy, PartialEq, Eq)]
534pub struct PlaneEntry {
535    pub variable_id: u8,
536    pub predictor: Predictor,
537    pub compression: Compression,
538    pub flags: u8,
539    pub frame_offset: u16,
540    pub dependency_offset: u16,
541    pub group_id: u16,
542    pub compressed_length: u32,
543    pub data_offset: u64,
544    pub decoded_length: u32,
545    pub crc32: u32,
546    pub minimum_code: u8,
547    pub maximum_code: u8,
548}
549
550impl PlaneEntry {
551    /// The key a plane is addressed by.
552    pub fn request(&self) -> FrameRequest {
553        FrameRequest {
554            variable_id: self.variable_id,
555            frame_offset: self.frame_offset,
556        }
557    }
558
559    pub fn unpack(raw: &[u8]) -> Result<Self, DecodeError> {
560        if raw.len() < ENTRY_SIZE {
561            return Err(err("index entry is truncated"));
562        }
563        if read_u16(raw, 10) != 0 || raw[34..40].iter().any(|&byte| byte != 0) {
564            return Err(err("index entry reserved fields must be 0"));
565        }
566        Ok(PlaneEntry {
567            variable_id: raw[0],
568            predictor: Predictor::parse(raw[1])?,
569            compression: Compression::parse(raw[2])?,
570            flags: raw[3],
571            frame_offset: read_u16(raw, 4),
572            dependency_offset: read_u16(raw, 6),
573            group_id: read_u16(raw, 8),
574            compressed_length: read_u32(raw, 12),
575            data_offset: read_u64(raw, 16),
576            decoded_length: read_u32(raw, 24),
577            crc32: read_u32(raw, 28),
578            minimum_code: raw[32],
579            maximum_code: raw[33],
580        })
581    }
582
583    pub fn pack(&self) -> [u8; ENTRY_SIZE] {
584        let mut buffer = [0u8; ENTRY_SIZE];
585        buffer[0] = self.variable_id;
586        buffer[1] = self.predictor.code();
587        buffer[2] = self.compression.code();
588        buffer[3] = self.flags;
589        buffer[4..6].copy_from_slice(&self.frame_offset.to_le_bytes());
590        buffer[6..8].copy_from_slice(&self.dependency_offset.to_le_bytes());
591        buffer[8..10].copy_from_slice(&self.group_id.to_le_bytes());
592        // reserved0 stays zero.
593        buffer[12..16].copy_from_slice(&self.compressed_length.to_le_bytes());
594        buffer[16..24].copy_from_slice(&self.data_offset.to_le_bytes());
595        buffer[24..28].copy_from_slice(&self.decoded_length.to_le_bytes());
596        buffer[28..32].copy_from_slice(&self.crc32.to_le_bytes());
597        buffer[32] = self.minimum_code;
598        buffer[33] = self.maximum_code;
599        // reserved1 stays zero.
600        buffer
601    }
602}
603
604/// One plane, addressed the way both the index and the callers address it.
605#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
606pub struct FrameRequest {
607    pub variable_id: u8,
608    pub frame_offset: u16,
609}
610
611#[cfg(test)]
612mod tests {
613    use super::*;
614
615    /// Packing and unpacking are the same table read in two directions, so a
616    /// field that drifts on one side fails to round-trip.
617    #[test]
618    fn headers_round_trip() {
619        let header = FixedHeader {
620            version: VERSION,
621            file_size: 4096,
622            metadata_offset: 80,
623            metadata_length: 301,
624            index_offset: 384,
625            index_length: 96,
626            data_offset: 480,
627            dictionary_offset: 0,
628            dictionary_length: 0,
629        };
630        assert_eq!(
631            FixedHeader::unpack(&header.pack()).expect("valid header"),
632            header
633        );
634        let index = IndexHeader { entry_count: 12 };
635        assert_eq!(
636            IndexHeader::unpack(&index.pack()).expect("valid index header"),
637            index
638        );
639    }
640
641    #[test]
642    fn plane_entries_round_trip() {
643        for (predictor, compression) in [
644            (Predictor::Raw, Compression::Zstd),
645            (Predictor::Anchor, Compression::None),
646            (Predictor::Previous, Compression::ZstdDict),
647            (Predictor::Zero, Compression::None),
648        ] {
649            let entry = PlaneEntry {
650                variable_id: 3,
651                predictor,
652                compression,
653                flags: FLAG_ZSTD_CHECKSUM,
654                frame_offset: 258,
655                dependency_offset: NO_DEPENDENCY,
656                group_id: 7,
657                compressed_length: 1234,
658                data_offset: 8192,
659                decoded_length: 65_160,
660                crc32: 0xDEAD_BEEF,
661                minimum_code: 4,
662                maximum_code: 251,
663            };
664            assert_eq!(
665                PlaneEntry::unpack(&entry.pack()).expect("valid entry"),
666                entry
667            );
668        }
669    }
670
671    /// Every reserved byte a writer must leave zero is a byte a reader must
672    /// refuse to see set — otherwise a later version's field is silently
673    /// ignored by an old decoder.
674    #[test]
675    fn reserved_bytes_are_rejected_when_set() {
676        let entry = PlaneEntry {
677            variable_id: 1,
678            predictor: Predictor::Raw,
679            compression: Compression::Zstd,
680            flags: 0,
681            frame_offset: 0,
682            dependency_offset: NO_DEPENDENCY,
683            group_id: 0,
684            compressed_length: 1,
685            data_offset: 480,
686            decoded_length: 1,
687            crc32: 0,
688            minimum_code: 0,
689            maximum_code: 0,
690        };
691        for byte in [10, 11, 34, 35, 36, 37, 38, 39] {
692            let mut raw = entry.pack();
693            raw[byte] = 1;
694            assert!(PlaneEntry::unpack(&raw).is_err(), "reserved byte {byte}");
695        }
696        let mut header = FixedHeader {
697            version: VERSION_V2,
698            file_size: 480,
699            metadata_offset: 80,
700            metadata_length: 8,
701            index_offset: 88,
702            index_length: 16,
703            data_offset: 104,
704            dictionary_offset: 0,
705            dictionary_length: 0,
706        }
707        .pack();
708        header[12] = 1;
709        assert!(FixedHeader::unpack(&header).is_err(), "header flags");
710        let mut index = IndexHeader { entry_count: 0 }.pack();
711        index[12] = 1;
712        assert!(IndexHeader::unpack(&index).is_err(), "index reserved");
713    }
714
715    #[test]
716    fn v2_index_structures_round_trip() {
717        let header = IndexHeaderV2 {
718            tile_width: 48,
719            tile_height: 52,
720            group_count: 28,
721            variable_count: 2,
722            compression: Compression::Zstd,
723            chunk_count: 23_520,
724        };
725        assert_eq!(
726            IndexHeaderV2::unpack(&header.pack()).expect("valid v2 index header"),
727            header
728        );
729        for predictor in [Predictor::Raw, Predictor::Previous] {
730            let entry = VariableEntry {
731                variable_id: 3,
732                predictor,
733            };
734            assert_eq!(
735                VariableEntry::unpack(&entry.pack()).expect("valid variable entry"),
736                entry
737            );
738        }
739        let group = GroupEntry {
740            first_frame: 120,
741            frame_count: 6,
742        };
743        assert_eq!(
744            GroupEntry::unpack(&group.pack()).expect("valid group entry"),
745            group
746        );
747        let chunk = ChunkEntry {
748            compressed_length: 5_120,
749            crc32: 0xDEAD_BEEF,
750        };
751        assert_eq!(
752            ChunkEntry::unpack(&chunk.pack()).expect("valid chunk entry"),
753            chunk
754        );
755    }
756
757    /// ANCHOR made sense when a reader decoded two planes to reach a frame.
758    /// A v2 chunk is decompressed whole, so allowing it would give one chunk
759    /// two encodings.
760    #[test]
761    fn v2_rejects_anchor_and_zero_predictors() {
762        for code in [Predictor::Anchor.code(), Predictor::Zero.code(), 9] {
763            let raw = [7u8, code, 0, 0];
764            assert!(VariableEntry::unpack(&raw).is_err(), "predictor {code}");
765        }
766        let mut raw = VariableEntry {
767            variable_id: 1,
768            predictor: Predictor::Raw,
769        }
770        .pack();
771        raw[2] = 1;
772        assert!(VariableEntry::unpack(&raw).is_err(), "variable reserved");
773        let mut raw = GroupEntry {
774            first_frame: 0,
775            frame_count: 1,
776        }
777        .pack();
778        raw[3] = 1;
779        assert!(GroupEntry::unpack(&raw).is_err(), "group reserved");
780        for byte in [20, 21, 22, 23, 24, 31] {
781            let mut raw = IndexHeaderV2 {
782                tile_width: 1,
783                tile_height: 1,
784                group_count: 1,
785                variable_count: 1,
786                compression: Compression::Zstd,
787                chunk_count: 1,
788            }
789            .pack();
790            raw[byte] = 1;
791            assert!(
792                IndexHeaderV2::unpack(&raw).is_err(),
793                "index reserved byte {byte}"
794            );
795        }
796    }
797
798    /// 721 rows have no tidy power of two, so clipped tiles are the normal
799    /// case rather than an edge: the last row and column must still describe
800    /// exactly the cells that are left.
801    #[test]
802    fn tile_geometry_clips_the_last_row_and_column() {
803        let geometry = TileGeometry::new(1440, 721, 48, 52).expect("valid geometry");
804        assert_eq!((geometry.columns(), geometry.rows()), (30, 14));
805        assert_eq!(geometry.count(), 420);
806        assert_eq!(geometry.shape(0), (52, 48));
807        // The last tile row covers 721 - 13 * 52 = 45 rows.
808        assert_eq!(geometry.shape(geometry.count() - 1), (45, 48));
809        assert_eq!(geometry.origin(geometry.count() - 1), (676, 1392));
810        // Every cell lands in exactly one tile, and the areas sum to the grid.
811        let area: u32 = (0..geometry.count())
812            .map(|tile| {
813                let (height, width) = geometry.shape(tile);
814                height * width
815            })
816            .sum();
817        assert_eq!(area, 1440 * 721);
818        assert_eq!(geometry.tile_of(0, 0), Ok(0));
819        assert_eq!(geometry.tile_of(720, 1439), Ok(419));
820        assert!(geometry.tile_of(721, 0).is_err());
821        assert!(TileGeometry::new(16, 8, 0, 4).is_err());
822        assert!(TileGeometry::new(16, 8, 17, 4).is_err());
823    }
824
825    #[test]
826    fn tile_rects_cover_the_cells_asked_for() {
827        let geometry = TileGeometry::new(16, 8, 5, 4).expect("valid geometry");
828        let rect = TileRect::covering(&geometry, 3, 4, 2, 7);
829        assert_eq!(
830            rect,
831            TileRect {
832                first_column: 0,
833                first_row: 0,
834                last_column: 2,
835                last_row: 1
836            }
837        );
838        for tile in 0..geometry.count() {
839            let (row, column) = geometry.origin(tile);
840            let (height, width) = geometry.shape(tile);
841            let touched = row < 5 && row + height > 3 && column < 11 && column + width > 4;
842            assert_eq!(rect.contains(&geometry, tile), touched, "tile {tile}");
843        }
844    }
845
846    #[test]
847    fn align8_rounds_up_and_saturates() {
848        assert_eq!(align8(0), Some(0));
849        assert_eq!(align8(1), Some(8));
850        assert_eq!(align8(8), Some(8));
851        assert_eq!(align8(81), Some(88));
852        assert_eq!(align8(u64::MAX), None);
853    }
854
855    #[test]
856    fn gcd_reduces_axis_units() {
857        assert_eq!(gcd(3600, 0), 3600);
858        assert_eq!(gcd(3600, 900), 900);
859        assert_eq!(gcd(10, 4), 2);
860    }
861}