Skip to main content

xue/decode/
core.rs

1//! The decode engine: payload residency, decompression and residual replay.
2//!
3//! One [`Core`] serves both readers and both container versions. What differs
4//! between a whole file and a streamed one is only where a payload's bytes
5//! come from, which is what [`PayloadStore`] abstracts; what differs between
6//! v1 and v2 is what a payload *is*, which is what [`Layout`] abstracts. The
7//! integrity checks above both are the same code either way.
8
9use std::collections::HashMap;
10use std::io::Read;
11
12use crate::decode::structure::{Layout, Structure, TiledLayout};
13use crate::format::{
14    crc32, err, Compression, DecodeError, FrameRequest, PlaneEntry, Predictor, TileGeometry,
15    TileRect, MAX_PLANE_LENGTH,
16};
17
18/// Whether a Zstandard frame's own content checksum is consulted.
19///
20/// Inside the container the reconstructed codes are covered by a CRC-32 in
21/// the index, so the frame's checksum is redundant there and is ignored, as
22/// it always was. A chunk decoded outside the container — one inner chunk of
23/// a Zarr store, which carries no CRC of its own — has nothing else, so the
24/// frame must declare a checksum and it must match.
25#[derive(Clone, Copy, PartialEq, Eq)]
26pub(crate) enum ContentChecksum {
27    Ignore,
28    Require,
29}
30
31/// Decompress one Zstandard frame to exactly `expected` bytes.
32///
33/// The decoder is capped one byte above `expected`, so a hostile frame can
34/// neither over-allocate nor run long; a frame shorter than promised is
35/// rejected the same way. With [`ContentChecksum::Require`] the frame header
36/// must set the content-checksum flag and the XXH64 the frame carries must
37/// equal the one computed over the output.
38pub(crate) fn decompress_zstd(
39    raw: &[u8],
40    expected: usize,
41    checksum: ContentChecksum,
42) -> Result<Vec<u8>, DecodeError> {
43    if checksum == ContentChecksum::Require && !zstd_frame_declares_checksum(raw) {
44        return Err(err(
45            "chunk must be a Zstandard frame with a content checksum",
46        ));
47    }
48    let mut decoder = ruzstd::decoding::StreamingDecoder::new(raw)
49        .map_err(|error| err(format!("zstd frame error: {error}")))?;
50    let mut output = Vec::with_capacity(expected);
51    let mut limited = decoder.by_ref().take(expected as u64 + 1);
52    limited
53        .read_to_end(&mut output)
54        .map_err(|error| err(format!("zstd decode error: {error}")))?;
55    if output.len() != expected {
56        return Err(err("decompressed payload length mismatch"));
57    }
58    if checksum == ContentChecksum::Require {
59        let frame = decoder.into_frame_decoder();
60        let stored = frame.get_checksum_from_data();
61        let computed = frame.get_calculated_checksum();
62        if stored.is_none() || stored != computed {
63            return Err(err("zstd content checksum mismatch"));
64        }
65    }
66    Ok(output)
67}
68
69/// The Content_Checksum_flag of a Zstandard frame header: bit 2 of the frame
70/// header descriptor, the byte after the four-byte magic. Read before the
71/// frame is decoded so a frame without one is refused up front.
72fn zstd_frame_declares_checksum(raw: &[u8]) -> bool {
73    const MAGIC: [u8; 4] = [0x28, 0xB5, 0x2F, 0xFD];
74    raw.len() >= 5 && raw[..4] == MAGIC && raw[4] & 0x04 != 0
75}
76
77/// Replay the PREVIOUS predictor inside one chunk: a group's frames are
78/// contiguous on the axis, so the chain never leaves the chunk, and each
79/// frame is a modulo-256 residual against the frame reconstructed just
80/// before it. `stride` is one frame's cell count.
81pub(crate) fn replay_previous(chunk: &mut [u8], frames: usize, stride: usize) {
82    for frame in 1..frames {
83        let (previous, current) = chunk.split_at_mut(frame * stride);
84        let previous = &previous[(frame - 1) * stride..];
85        for (target, base) in current[..stride].iter_mut().zip(previous.iter()) {
86            *target = target.wrapping_add(*base);
87        }
88    }
89}
90
91/// Decode one chunk payload outside any container.
92///
93/// This is the container's own chunk path — one Zstandard frame holding
94/// `frames × height × width` bytes, frame-major and row-major within a
95/// frame, RAW or a PREVIOUS residual chain — applied to bytes that did not
96/// come out of a `.xue` index: an inner chunk of the Zarr store
97/// (`docs/zarr-profile.md`), whose only integrity check is the frame's own
98/// content checksum, which is therefore mandatory here. Only the RAW and
99/// PREVIOUS predictors exist inside a chunk; the plane-level ANCHOR and ZERO
100/// of container v1 are refused.
101///
102/// Nothing is allocated before the shape is validated: a chunk is capped at
103/// [`MAX_PLANE_LENGTH`] bytes in total, the container's own plane limit.
104pub fn decode_chunk(
105    bytes: &[u8],
106    frames: u32,
107    height: u32,
108    width: u32,
109    predictor: Predictor,
110) -> Result<Vec<u8>, DecodeError> {
111    let (total, stride) = chunk_cells(frames, height, width, predictor)?;
112    let mut chunk = decompress_zstd(bytes, total, ContentChecksum::Require)?;
113    if predictor == Predictor::Previous {
114        replay_previous(&mut chunk, frames as usize, stride);
115    }
116    Ok(chunk)
117}
118
119/// [`decode_chunk`] for a chunk of 16-bit codes: the Zstandard frame holds
120/// `frames × height × width` little-endian `u16`s in the same order, and the
121/// PREVIOUS chain is a modulo-65536 residual along the frame axis. The size
122/// limit counts codes, so the frame may decompress to twice
123/// [`MAX_PLANE_LENGTH`] bytes.
124pub fn decode_chunk_u16(
125    bytes: &[u8],
126    frames: u32,
127    height: u32,
128    width: u32,
129    predictor: Predictor,
130) -> Result<Vec<u16>, DecodeError> {
131    let (total, stride) = chunk_cells(frames, height, width, predictor)?;
132    let raw = decompress_zstd(bytes, total * 2, ContentChecksum::Require)?;
133    let mut chunk: Vec<u16> = raw
134        .as_chunks::<2>()
135        .0
136        .iter()
137        .map(|&pair| u16::from_le_bytes(pair))
138        .collect();
139    if predictor == Predictor::Previous {
140        replay_previous_u16(&mut chunk, frames as usize, stride);
141    }
142    Ok(chunk)
143}
144
145/// [`replay_previous`] over 16-bit codes, modulo 65536.
146pub(crate) fn replay_previous_u16(chunk: &mut [u16], frames: usize, stride: usize) {
147    for frame in 1..frames {
148        let (previous, current) = chunk.split_at_mut(frame * stride);
149        let previous = &previous[(frame - 1) * stride..];
150        for (target, base) in current[..stride].iter_mut().zip(previous.iter()) {
151            *target = target.wrapping_add(*base);
152        }
153    }
154}
155
156/// A chunk's shape held to the decoder's rules: non-zero, at most
157/// [`MAX_PLANE_LENGTH`] codes, RAW or PREVIOUS. Returns the code count and one
158/// frame's.
159fn chunk_cells(
160    frames: u32,
161    height: u32,
162    width: u32,
163    predictor: Predictor,
164) -> Result<(usize, usize), DecodeError> {
165    if frames == 0 || height == 0 || width == 0 {
166        return Err(err("chunk shape must be non-zero"));
167    }
168    let stride = u64::from(height) * u64::from(width);
169    let total = stride * u64::from(frames);
170    if total > MAX_PLANE_LENGTH {
171        return Err(err("chunk exceeds the decoded size limit"));
172    }
173    match predictor {
174        Predictor::Raw | Predictor::Previous => {}
175        Predictor::Anchor | Predictor::Zero => {
176            return Err(err(
177                "a chunk is RAW or PREVIOUS; ANCHOR and ZERO are plane predictors",
178            ))
179        }
180    }
181    Ok((total as usize, stride as usize))
182}
183
184/// Where payload bytes live: the whole file, or per-payload sparse buffers
185/// filled in by [`crate::StreamingBundle::insert_range`].
186pub(crate) enum PayloadStore {
187    Full(Vec<u8>),
188    Sparse {
189        payloads: Vec<Option<Vec<u8>>>,
190        resident_bytes: u64,
191    },
192}
193
194impl PayloadStore {
195    /// One payload's compressed bytes, addressed by its position in the index
196    /// and its byte span in the file — the one thing v1 planes and v2 chunks
197    /// have in common.
198    pub(crate) fn payload(&self, position: usize, span: (u64, u64)) -> Result<&[u8], DecodeError> {
199        match self {
200            PayloadStore::Full(data) => Ok(&data[span.0 as usize..span.1 as usize]),
201            PayloadStore::Sparse { payloads, .. } => payloads[position]
202                .as_deref()
203                .ok_or_else(|| err("payload is not resident yet")),
204        }
205    }
206
207    pub(crate) fn is_resident(&self, position: usize, span: (u64, u64)) -> bool {
208        match self {
209            PayloadStore::Full(_) => true,
210            PayloadStore::Sparse { payloads, .. } => {
211                span.0 == span.1 || payloads[position].is_some()
212            }
213        }
214    }
215}
216
217/// Shared decode engine over a [`Structure`] and a [`PayloadStore`].
218pub(crate) struct Core {
219    pub(crate) structure: Structure,
220    pub(crate) store: PayloadStore,
221    /// v1: RAW base planes along a dependency chain.
222    pub(crate) anchor_cache: HashMap<FrameRequest, Vec<u8>>,
223    /// v2: reconstructed chunks of the group currently being read. Scrubbing
224    /// inside a group is then free; moving to another group drops the lot,
225    /// which keeps residency at one group's tiles rather than the file's.
226    pub(crate) chunk_cache: HashMap<usize, Vec<u8>>,
227    cached_group: Option<u32>,
228    pub(crate) output: Vec<u8>,
229}
230
231impl Core {
232    pub(crate) fn new(structure: Structure, store: PayloadStore) -> Self {
233        Core {
234            structure,
235            store,
236            anchor_cache: HashMap::new(),
237            chunk_cache: HashMap::new(),
238            cached_group: None,
239            output: Vec::new(),
240        }
241    }
242
243    pub(crate) fn clear_cache(&mut self) {
244        self.anchor_cache.clear();
245        self.chunk_cache.clear();
246        self.cached_group = None;
247    }
248
249    /// Decompress one payload to exactly `expected` bytes.
250    ///
251    /// The output length is checked against what the structure says it must
252    /// be, and the decoder is capped one byte above it, so a hostile frame
253    /// can neither over-allocate nor run long. The container checks the
254    /// reconstructed codes with its own CRC-32, so the Zstandard content
255    /// checksum is not consulted here.
256    fn decompress(
257        &self,
258        position: usize,
259        span: (u64, u64),
260        compression: Compression,
261        expected: usize,
262    ) -> Result<Vec<u8>, DecodeError> {
263        let raw = self.store.payload(position, span)?;
264        match compression {
265            Compression::None => {
266                if raw.len() != expected {
267                    return Err(err("uncompressed payload length mismatch"));
268                }
269                Ok(raw.to_vec())
270            }
271            Compression::ZstdDict => Err(err(
272                "ZSTD_DICT payloads require an embedded dictionary decoder",
273            )),
274            Compression::Zstd => decompress_zstd(raw, expected, ContentChecksum::Ignore),
275        }
276    }
277
278    // -- v1: plane-major -----------------------------------------------------
279
280    fn plane_entry(&self, request: FrameRequest) -> Result<(usize, PlaneEntry), DecodeError> {
281        let Layout::Planes(planes) = &self.structure.layout else {
282            return Err(err("not a plane-major file"));
283        };
284        let position = planes.entry_position(request)?;
285        Ok((position, planes.entries[position]))
286    }
287
288    fn decompress_plane(
289        &self,
290        position: usize,
291        entry: &PlaneEntry,
292    ) -> Result<Vec<u8>, DecodeError> {
293        let span = (
294            entry.data_offset,
295            entry.data_offset + u64::from(entry.compressed_length),
296        );
297        self.decompress(
298            position,
299            span,
300            entry.compression,
301            entry.decoded_length as usize,
302        )
303    }
304
305    fn checked_plane(&self, entry: &PlaneEntry, plane: Vec<u8>) -> Result<Vec<u8>, DecodeError> {
306        if crc32(&plane) != entry.crc32 {
307            return Err(err(format!(
308                "plane CRC32 mismatch for variable {} hour {}",
309                entry.variable_id, entry.frame_offset
310            )));
311        }
312        let (minimum, maximum) = plane
313            .iter()
314            .fold((u8::MAX, u8::MIN), |(low, high), &value| {
315                (low.min(value), high.max(value))
316            });
317        if minimum != entry.minimum_code || maximum != entry.maximum_code {
318            return Err(err("plane code range mismatch"));
319        }
320        Ok(plane)
321    }
322
323    fn decode_base(&mut self, request: FrameRequest) -> Result<Vec<u8>, DecodeError> {
324        let (position, entry) = self.plane_entry(request)?;
325        let plane = match entry.predictor {
326            Predictor::Zero => vec![0u8; entry.decoded_length as usize],
327            Predictor::Raw => self.decompress_plane(position, &entry)?,
328            _ => return Err(err("dependency chain base must be RAW or ZERO")),
329        };
330        self.checked_plane(&entry, plane)
331    }
332
333    fn decode_frame_v1(&mut self, request: FrameRequest) -> Result<&[u8], DecodeError> {
334        let Layout::Planes(planes) = &self.structure.layout else {
335            return Err(err("not a plane-major file"));
336        };
337        let chain = planes.dependency_chain(request, self.structure.metadata.frame_count)?;
338        let base_request = *chain.last().expect("chain is never empty");
339        if chain.len() == 1 {
340            // Independent plane: decode directly without growing the cache.
341            self.output = self.decode_base(base_request)?;
342            return Ok(&self.output);
343        }
344        if !self.anchor_cache.contains_key(&base_request) {
345            let base = self.decode_base(base_request)?;
346            self.anchor_cache.insert(base_request, base);
347        }
348        let mut plane = self.anchor_cache[&base_request].clone();
349        for link in chain.iter().rev().skip(1) {
350            let (position, entry) = self.plane_entry(*link)?;
351            let residual = self.decompress_plane(position, &entry)?;
352            if residual.len() != plane.len() {
353                return Err(err("residual length mismatch"));
354            }
355            for (target, delta) in plane.iter_mut().zip(residual.iter()) {
356                *target = target.wrapping_add(*delta);
357            }
358            plane = self.checked_plane(&entry, plane)?;
359        }
360        self.output = plane;
361        Ok(&self.output)
362    }
363
364    // -- v2: tiled -----------------------------------------------------------
365
366    pub(crate) fn tiled(&self) -> Result<&TiledLayout, DecodeError> {
367        match &self.structure.layout {
368            Layout::Tiles(tiles) => Ok(tiles),
369            Layout::Planes(_) => Err(err("not a tiled file")),
370        }
371    }
372
373    /// The file's tiling, or `None` for a plane-major v1 file.
374    pub(crate) fn tile_geometry(&self) -> Option<TileGeometry> {
375        match &self.structure.layout {
376            Layout::Tiles(tiles) => Some(tiles.geometry),
377            Layout::Planes(_) => None,
378        }
379    }
380
381    fn tiles(&self) -> Result<&TiledLayout, DecodeError> {
382        self.tiled()
383    }
384
385    /// The frame's index on the axis, and the group holding it.
386    fn frame_position(&self, frame_offset: u16) -> Result<(u32, u32), DecodeError> {
387        let index = self
388            .structure
389            .metadata
390            .offsets
391            .binary_search(&frame_offset)
392            .map_err(|_| err("no plane for the requested variable and forecast hour"))?;
393        Ok(self.tiles()?.frame_group[index])
394    }
395
396    /// One chunk, decompressed and its residual chain replayed.
397    fn build_chunk(&self, position: usize) -> Result<Vec<u8>, DecodeError> {
398        let layout = self.tiles()?;
399        let variable_count = layout.variables.len();
400        let group = (position / (layout.geometry.count() as usize * variable_count)) as u32;
401        let tile = (position / variable_count % layout.geometry.count() as usize) as u32;
402        let variable = layout.variables[position % variable_count];
403        let (height, width) = layout.geometry.shape(tile);
404        let frames = layout.groups[group as usize].frame_count as usize;
405        let expected = layout.decoded_length(group, tile);
406        let mut chunk = self.decompress(
407            position,
408            layout.chunk_span(position),
409            layout.compression,
410            expected,
411        )?;
412        if variable.predictor == Predictor::Previous {
413            replay_previous(&mut chunk, frames, height as usize * width as usize);
414        }
415        if crc32(&chunk) != layout.chunks[position].crc32 {
416            return Err(err(format!("chunk CRC32 mismatch at position {position}")));
417        }
418        Ok(chunk)
419    }
420
421    /// Reconstruct a chunk into the group-local cache if it is not there yet.
422    fn ensure_chunk(&mut self, group: u32, position: usize) -> Result<(), DecodeError> {
423        if self.cached_group != Some(group) {
424            self.chunk_cache.clear();
425            self.cached_group = Some(group);
426        }
427        if self.chunk_cache.contains_key(&position) {
428            return Ok(());
429        }
430        let chunk = self.build_chunk(position)?;
431        self.chunk_cache.insert(position, chunk);
432        Ok(())
433    }
434
435    /// Assemble a frame from the chunks of its group.
436    ///
437    /// `tiles` restricts the work to the tiles a viewport covers; cells no
438    /// tile covered are left as they were, so a caller drawing a partial
439    /// plane must know which rectangle it asked for.
440    fn decode_frame_v2(
441        &mut self,
442        request: FrameRequest,
443        tiles: Option<TileRect>,
444    ) -> Result<&[u8], DecodeError> {
445        let (group, frame_in_group) = self.frame_position(request.frame_offset)?;
446        let variable_position = self.tiles()?.variable_position(request.variable_id)?;
447        let plane_length = self.structure.metadata.plane_length as usize;
448        if self.output.len() != plane_length {
449            self.output = vec![0u8; plane_length];
450        }
451        let grid_width = self.structure.metadata.width as usize;
452        let tile_count = self.tiles()?.geometry.count();
453        for tile in 0..tile_count {
454            let geometry = self.tiles()?.geometry;
455            if tiles.is_some_and(|rect| !rect.contains(&geometry, tile)) {
456                continue;
457            }
458            let position = self.tiles()?.chunk_position(group, tile, variable_position);
459            self.ensure_chunk(group, position)?;
460            let (height, width) = geometry.shape(tile);
461            let (origin_row, origin_column) = geometry.origin(tile);
462            let stride = height as usize * width as usize;
463            let chunk = &self.chunk_cache[&position];
464            let block = &chunk[frame_in_group as usize * stride..][..stride];
465            for row in 0..height as usize {
466                let target = (origin_row as usize + row) * grid_width + origin_column as usize;
467                self.output[target..target + width as usize]
468                    .copy_from_slice(&block[row * width as usize..][..width as usize]);
469            }
470        }
471        Ok(&self.output)
472    }
473
474    /// One cell's code on every frame of the axis.
475    ///
476    /// The cost is one chunk per group of the single tile holding the cell,
477    /// independent of how many frames the axis has — which is the whole point
478    /// of the tiled container. Chunks are read straight through rather than
479    /// cached: each is touched once.
480    pub(crate) fn decode_series(
481        &mut self,
482        variable_id: u8,
483        column: u32,
484        row: u32,
485    ) -> Result<Vec<u8>, DecodeError> {
486        let layout = self.tiles()?;
487        let variable_position = layout.variable_position(variable_id)?;
488        let tile = layout.geometry.tile_of(row, column)?;
489        let (origin_row, origin_column) = layout.geometry.origin(tile);
490        let (_, width) = layout.geometry.shape(tile);
491        let cell = (row - origin_row) as usize * width as usize + (column - origin_column) as usize;
492        let mut series = Vec::with_capacity(self.structure.metadata.frame_count as usize);
493        for group in 0..layout.groups.len() {
494            let layout = self.tiles()?;
495            let frames = layout.groups[group].frame_count as usize;
496            let stride = layout.decoded_length(group as u32, tile) / frames;
497            let position = layout.chunk_position(group as u32, tile, variable_position);
498            let chunk = self.build_chunk(position)?;
499            series.extend((0..frames).map(|frame| chunk[frame * stride + cell]));
500        }
501        Ok(series)
502    }
503
504    // -- dispatch ------------------------------------------------------------
505
506    /// Decode one whole frame into an internal buffer and return it.
507    pub(crate) fn decode_frame(&mut self, request: FrameRequest) -> Result<&[u8], DecodeError> {
508        self.decode_frame_tiles(request, None)
509    }
510
511    pub(crate) fn decode_frame_tiles(
512        &mut self,
513        request: FrameRequest,
514        tiles: Option<TileRect>,
515    ) -> Result<&[u8], DecodeError> {
516        match self.structure.layout {
517            Layout::Planes(_) => {
518                if tiles.is_some() {
519                    return Err(err("a plane-major file has no tiles"));
520                }
521                self.decode_frame_v1(request)
522            }
523            Layout::Tiles(_) => self.decode_frame_v2(request, tiles),
524        }
525    }
526}
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531
532    /// The bytes 1..=12 as one Zstandard frame with a content checksum —
533    /// `zstdcli.compress(bytes(range(1, 13)), level=15, checksum=True)` in
534    /// the Python encoder — and the same frame written without one.
535    const FRAME: [u8; 25] = [
536        0x28, 0xB5, 0x2F, 0xFD, 0x24, 0x0C, 0x61, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
537        0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0xA5, 0xE9, 0x82, 0xA5,
538    ];
539    const FRAME_WITHOUT_CHECKSUM: [u8; 21] = [
540        0x28, 0xB5, 0x2F, 0xFD, 0x20, 0x0C, 0x61, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
541        0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
542    ];
543
544    #[test]
545    fn raw_chunk_is_the_frame_content() {
546        let chunk = decode_chunk(&FRAME, 3, 2, 2, Predictor::Raw).expect("decode");
547        assert_eq!(chunk, (1..=12).collect::<Vec<u8>>());
548    }
549
550    #[test]
551    fn previous_chunk_is_the_running_sum_along_the_frame_axis() {
552        let chunk = decode_chunk(&FRAME, 3, 2, 2, Predictor::Previous).expect("decode");
553        assert_eq!(chunk, vec![1, 2, 3, 4, 6, 8, 10, 12, 15, 18, 21, 24]);
554    }
555
556    #[test]
557    fn running_sum_wraps_modulo_256() {
558        let mut chunk = vec![250, 10, 10];
559        replay_previous(&mut chunk, 3, 1);
560        assert_eq!(chunk, vec![250, 4, 14]);
561    }
562
563    #[test]
564    fn shape_must_match_the_frame_exactly() {
565        assert!(decode_chunk(&FRAME, 2, 2, 2, Predictor::Raw).is_err());
566        assert!(decode_chunk(&FRAME, 4, 2, 2, Predictor::Raw).is_err());
567        assert!(decode_chunk(&FRAME, 0, 2, 2, Predictor::Raw).is_err());
568    }
569
570    #[test]
571    fn content_checksum_is_mandatory_and_verified() {
572        assert!(decode_chunk(&FRAME_WITHOUT_CHECKSUM, 3, 2, 2, Predictor::Raw).is_err());
573        let mut corrupt_checksum = FRAME;
574        corrupt_checksum[24] ^= 0x01;
575        assert!(decode_chunk(&corrupt_checksum, 3, 2, 2, Predictor::Raw).is_err());
576        let mut corrupt_content = FRAME;
577        corrupt_content[12] ^= 0x01;
578        assert!(decode_chunk(&corrupt_content, 3, 2, 2, Predictor::Raw).is_err());
579    }
580
581    #[test]
582    fn plane_predictors_are_refused() {
583        assert!(decode_chunk(&FRAME, 3, 2, 2, Predictor::Anchor).is_err());
584        assert!(decode_chunk(&FRAME, 3, 2, 2, Predictor::Zero).is_err());
585    }
586
587    #[test]
588    fn oversized_shape_is_refused_before_decoding() {
589        assert!(decode_chunk(&FRAME, 255, 65_536, 65_536, Predictor::Raw).is_err());
590    }
591
592    /// Codes as the little-endian payload a uint16 array's chunk holds.
593    fn u16_frame(codes: &[u16]) -> Vec<u8> {
594        let bytes: Vec<u8> = codes.iter().flat_map(|code| code.to_le_bytes()).collect();
595        ruzstd::encoding::compress_to_vec(&bytes[..], ruzstd::encoding::CompressionLevel::Fastest)
596    }
597
598    #[test]
599    fn a_u16_chunk_round_trips_raw_and_previous() {
600        let codes: Vec<u16> = vec![0, 300, 65_535, 1500, 7, 8];
601        let frame = u16_frame(&codes);
602        assert_eq!(
603            decode_chunk_u16(&frame, 3, 1, 2, Predictor::Raw).unwrap(),
604            codes
605        );
606        // Residuals stored mod 65536 replay to the codes, through the wrap.
607        let series: Vec<u16> = vec![65_534, 2, 65_535, 0, 1, 65_000];
608        let mut residuals = series.clone();
609        for frame in 1..3 {
610            for cell in 0..2 {
611                residuals[frame * 2 + cell] =
612                    series[frame * 2 + cell].wrapping_sub(series[(frame - 1) * 2 + cell]);
613            }
614        }
615        let decoded =
616            decode_chunk_u16(&u16_frame(&residuals), 3, 1, 2, Predictor::Previous).unwrap();
617        assert_eq!(decoded, series);
618        // The shape counts codes, not bytes.
619        assert!(decode_chunk_u16(&frame, 6, 1, 2, Predictor::Raw).is_err());
620        assert!(decode_chunk(&frame, 6, 1, 2, Predictor::Raw).is_ok());
621        assert!(decode_chunk_u16(&frame, 3, 1, 2, Predictor::Zero).is_err());
622        assert!(decode_chunk_u16(&FRAME_WITHOUT_CHECKSUM, 3, 1, 2, Predictor::Raw).is_err());
623        assert!(decode_chunk_u16(&FRAME, 255, 65_536, 65_536, Predictor::Raw).is_err());
624    }
625
626    #[test]
627    fn running_sum_wraps_modulo_65536() {
628        let mut chunk = vec![65_530u16, 10, 10];
629        replay_previous_u16(&mut chunk, 3, 1);
630        assert_eq!(chunk, vec![65_530, 4, 14]);
631    }
632
633    #[test]
634    fn not_a_zstd_frame() {
635        assert!(decode_chunk(b"XUE\0\0\0\0\0", 1, 2, 4, Predictor::Raw).is_err());
636    }
637}