1use 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#[derive(Debug, Clone)]
26pub struct ArrayReader {
27 layout: ArrayLayout,
28 indices: BTreeMap<u32, Vec<Option<ShardIndexEntry>>>,
32 decoded_time_chunk: Option<u32>,
34 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 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 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 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 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 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 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 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 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 pub fn clear_cache(&mut self) {
203 self.decoded.clear();
204 self.decoded_time_chunk = None;
205 }
206}