Skip to main content

xue/zarr/
reader.rs

1//! One variable array, read without IO.
2//!
3//! The caller owns the requests: it asks where a shard's index and an inner
4//! chunk sit, fetches those bytes however it likes, and hands them over. What
5//! is held here is what the format says about the bytes — the array's layout,
6//! each shard's verified index, and the decoded tiles of the time chunk being
7//! read — so the browser, the API and a native caller read a store through
8//! one implementation of it.
9//!
10//! A frame is read in three steps: [`ArrayReader::tiles_for`] names the tiles
11//! it needs, the caller hands over the payload of each one not yet decoded
12//! ([`ArrayReader::undecoded_tiles`], [`ArrayReader::feed_chunk`]), and
13//! [`ArrayReader::assemble_frame`] returns the plane. Every plane is a new
14//! buffer, so two frames being read at once never write into each other.
15
16use std::collections::{BTreeMap, BTreeSet};
17
18use super::{
19    decode_frame_chunk, parse_shard_index, place_tile, shard_of, ArrayLayout, ShardIndexEntry,
20};
21use crate::format::{err, DecodeError, TileRect};
22
23/// A variable array being read: its layout, the shard indices handed over so
24/// far and the decoded tiles of one time chunk.
25#[derive(Debug, Clone)]
26pub struct ArrayReader {
27    layout: ArrayLayout,
28    /// Verified indices by shard. A map, not a list of `shard_count` slots:
29    /// a store cut one shard per time chunk has as many shards as time chunks
30    /// and a read touches few of them.
31    indices: BTreeMap<u32, Vec<Option<ShardIndexEntry>>>,
32    /// The time chunk whose tiles `decoded` holds.
33    decoded_time_chunk: Option<u32>,
34    /// Decoded inner chunks of that time chunk by tile, each at the full inner
35    /// shape; `None` for a chunk the shard never held. One time chunk only:
36    /// scrubbing inside it decodes nothing twice, and memory stays at one
37    /// time chunk's tiles.
38    decoded: BTreeMap<u32, Option<Vec<u8>>>,
39}
40
41impl ArrayReader {
42    pub fn new(layout: ArrayLayout) -> ArrayReader {
43        ArrayReader {
44            layout,
45            indices: BTreeMap::new(),
46            decoded_time_chunk: None,
47            decoded: BTreeMap::new(),
48        }
49    }
50
51    pub fn layout(&self) -> &ArrayLayout {
52        &self.layout
53    }
54
55    /// The shard a time chunk lives in.
56    pub fn shard_of(&self, time_chunk: u32) -> Result<u32, DecodeError> {
57        if time_chunk >= self.layout.time_chunks {
58            return Err(err("time chunk is outside the array"));
59        }
60        Ok(shard_of(&self.layout, time_chunk).0)
61    }
62
63    pub fn has_shard_index(&self, shard: u32) -> bool {
64        self.indices.contains_key(&shard)
65    }
66
67    /// Verify one shard's index — its length, its CRC-32C and every entry —
68    /// and hold it. `bytes` is exactly the index, read from whichever end of
69    /// the shard the layout names.
70    pub fn set_shard_index(&mut self, shard: u32, bytes: &[u8]) -> Result<(), DecodeError> {
71        if shard >= self.layout.shard_count {
72            return Err(err("shard is outside the array"));
73        }
74        let index = parse_shard_index(bytes, self.layout.chunks_per_shard as usize)?;
75        self.indices.insert(shard, index);
76        Ok(())
77    }
78
79    /// Where one inner chunk sits in its shard, or `None` for a chunk the
80    /// shard never held, which reads as the fill value. An error until the
81    /// shard's index has been handed over.
82    pub fn chunk_range(
83        &self,
84        time_chunk: u32,
85        tile: u32,
86    ) -> Result<Option<ShardIndexEntry>, DecodeError> {
87        if tile >= self.layout.tile_count {
88            return Err(err("tile is outside the grid"));
89        }
90        let shard = self.shard_of(time_chunk)?;
91        let (_, position) = shard_of(&self.layout, time_chunk);
92        let index = self
93            .indices
94            .get(&shard)
95            .ok_or_else(|| err("shard index is not resident yet"))?;
96        index
97            .get((position + tile) as usize)
98            .copied()
99            .ok_or_else(|| err("tile is outside the shard"))
100    }
101
102    /// The tiles a list of tile rectangles names, ascending, or every tile
103    /// when there is no list. Rectangles may overlap; a tile is named once.
104    pub fn tiles_for(&self, rects: Option<&[TileRect]>) -> Result<Vec<u32>, DecodeError> {
105        let Some(rects) = rects else {
106            return Ok((0..self.layout.tile_count).collect());
107        };
108        let mut tiles = BTreeSet::new();
109        for rect in rects {
110            if rect.last_row >= self.layout.tile_rows
111                || rect.last_column >= self.layout.tile_columns
112            {
113                return Err(err("tile rectangle is outside the grid"));
114            }
115            for row in rect.first_row..=rect.last_row {
116                for column in rect.first_column..=rect.last_column {
117                    tiles.insert(row * self.layout.tile_columns + column);
118                }
119            }
120        }
121        Ok(tiles.into_iter().collect())
122    }
123
124    /// Which of `tiles` are not decoded for `time_chunk`: the ones
125    /// [`ArrayReader::feed_chunk`] still has to be given before a frame of
126    /// that time chunk assembles over them.
127    pub fn undecoded_tiles(&self, time_chunk: u32, tiles: &[u32]) -> Vec<u32> {
128        if self.decoded_time_chunk != Some(time_chunk) {
129            return tiles.to_vec();
130        }
131        tiles
132            .iter()
133            .copied()
134            .filter(|tile| !self.decoded.contains_key(tile))
135            .collect()
136    }
137
138    /// Decode one inner chunk and hold it. `payload` is the chunk's bytes as
139    /// the shard holds them, or `None` for a chunk the shard never held.
140    /// Moving to another time chunk drops the tiles of the one held. Frames
141    /// are planes of bytes, so a `uint16` array is refused here; its cells
142    /// are read with [`super::series_from_chunks`].
143    pub fn feed_chunk(
144        &mut self,
145        time_chunk: u32,
146        tile: u32,
147        payload: Option<&[u8]>,
148    ) -> Result<(), DecodeError> {
149        if time_chunk >= self.layout.time_chunks {
150            return Err(err("time chunk is outside the array"));
151        }
152        if tile >= self.layout.tile_count {
153            return Err(err("tile is outside the grid"));
154        }
155        super::require_map_array(&self.layout)?;
156        let chunk = payload
157            .map(|payload| decode_frame_chunk(&self.layout, payload))
158            .transpose()?;
159        if self.decoded_time_chunk != Some(time_chunk) {
160            self.decoded.clear();
161            self.decoded_time_chunk = Some(time_chunk);
162        }
163        self.decoded.insert(tile, chunk);
164        Ok(())
165    }
166
167    /// One frame as a new plane of `height × width` codes. With `rects` only
168    /// those tiles are written and every cell outside them is zero, which
169    /// says nothing about the data there: a caller draws only what it asked
170    /// for. An error unless every tile named has been fed for the frame's
171    /// time chunk.
172    pub fn assemble_frame(
173        &self,
174        frame_index: u32,
175        rects: Option<&[TileRect]>,
176    ) -> Result<Vec<u8>, DecodeError> {
177        if frame_index >= self.layout.frame_count {
178            return Err(err("frame is outside the array"));
179        }
180        let time_chunk = frame_index / self.layout.time_chunk;
181        let tiles = self.tiles_for(rects)?;
182        let held = (self.decoded_time_chunk == Some(time_chunk)).then_some(&self.decoded);
183        // Sized by the layout, which holds a plane to the decoded size limit.
184        let mut plane = vec![0u8; self.layout.height as usize * self.layout.width as usize];
185        let frame_in_chunk = frame_index % self.layout.time_chunk;
186        for tile in tiles {
187            let chunk = held
188                .and_then(|decoded| decoded.get(&tile))
189                .ok_or_else(|| err("chunk is not resident yet"))?;
190            place_tile(
191                &mut plane,
192                &self.layout,
193                tile,
194                chunk.as_deref(),
195                frame_in_chunk,
196            )?;
197        }
198        Ok(plane)
199    }
200
201    /// Drop the decoded tiles; the shard indices stay.
202    pub fn clear_cache(&mut self) {
203        self.decoded.clear();
204        self.decoded_time_chunk = None;
205    }
206}