Skip to main content

xue/
zarr.rs

1//! Reading the Xue Zarr profile.
2//!
3//! `docs/zarr-profile.md` is normative. A store is one Zarr v3 group with one
4//! sharded `uint8` array per variable (`uint16` for a widened variable of a
5//! series store): on profile 1 it holds one bundle, its
6//! `attributes.xue` the bundle metadata verbatim; on profile 2 (a shared
7//! store) it holds every bundle of one resolution tier, each one's metadata
8//! verbatim under `attributes.xue_bundles[<bundle id>]`. This module is the format's read side in Rust: the two
9//! metadata documents, the shard index, the arithmetic that maps a frame and a
10//! tile to a byte span, the geographic cell a point probes, and the codebook
11//! that turns a stored code into a physical value.
12//!
13//! It is deliberately IO-free — it takes `&str` / `&[u8]` and returns values —
14//! so the same code serves the native worker and, through wasm-bindgen, the
15//! browser. The container decoder in [`crate::decode`] shares its metadata
16//! validation: [`parse_bundle_metadata`] calls the container's own
17//! `parse_metadata`, so a group the container would refuse is refused here too.
18//! The chunk payload itself is decoded by [`crate::decode_chunk`], the same
19//! Zstandard + `PREVIOUS` residual path the `.xue` reader uses.
20
21use serde_json::Value;
22
23mod reader;
24
25pub use reader::ArrayReader;
26
27use crate::decode::metadata::{parse_gaussian, parse_projection};
28use crate::format::{err, DecodeError, Predictor, TileGeometry, MAX_PLANE_LENGTH};
29use crate::projection::{GaussianRows, LambertConformal};
30
31/// Bytes of one `(offset, nbytes)` pair in a shard index.
32pub(crate) const INDEX_ENTRY_BYTES: usize = 16;
33/// The CRC-32C trailer of a shard index.
34pub(crate) const INDEX_CHECKSUM_BYTES: usize = 4;
35/// The array-to-array delta codec's name in an inner codec chain.
36pub const DELTA_CODEC: &str = "xue.delta";
37/// Padding frames and cells are this many bytes per value.
38const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
39
40// -- grid ----------------------------------------------------------------------
41
42/// A regular latitude/longitude grid. With `gaussian`, the rows are really a
43/// Gaussian grid's: the regular fields stay the equidistant approximation a
44/// renderer samples with, and the true latitudes are what a point read reports.
45#[derive(Debug, Clone, Copy, PartialEq)]
46pub struct RegularGrid {
47    pub width: u32,
48    pub height: u32,
49    pub first_longitude: f64,
50    pub first_latitude: f64,
51    pub longitude_step: f64,
52    pub latitude_step: f64,
53    /// Whether a longitude wraps around the antimeridian (a global or
54    /// antimeridian-crossing grid).
55    pub wraps: bool,
56    pub gaussian: Option<GaussianRows>,
57}
58
59/// A grid on a map projection: the first cell's centre and the steps, in
60/// projected metres, `dy` negative because rows run north to south.
61#[derive(Debug, Clone, Copy, PartialEq)]
62pub struct LambertGrid {
63    pub width: u32,
64    pub height: u32,
65    pub projection: LambertConformal,
66    pub x0: f64,
67    pub y0: f64,
68    pub dx: f64,
69    pub dy: f64,
70}
71
72/// The bundle's grid, in the container's row-major, north-to-south,
73/// west-to-east order.
74#[derive(Debug, Clone, Copy, PartialEq)]
75pub enum Grid {
76    Regular(RegularGrid),
77    Lambert(LambertGrid),
78}
79
80impl Grid {
81    pub fn width(&self) -> u32 {
82        match self {
83            Grid::Regular(grid) => grid.width,
84            Grid::Lambert(grid) => grid.width,
85        }
86    }
87
88    pub fn height(&self) -> u32 {
89        match self {
90            Grid::Regular(grid) => grid.height,
91            Grid::Lambert(grid) => grid.height,
92        }
93    }
94
95    /// The grid a metadata document declares. A projected grid is complete or
96    /// refused. A regular grid takes the defaults `web/src/features/probe/probe.ts::geoGrid`
97    /// applies to a missing field, since metadata published before the fields
98    /// were all written must keep reading.
99    pub fn from_metadata(value: &Value) -> Result<Grid, DecodeError> {
100        let grid = value.get("grid").unwrap_or(&Value::Null);
101        let width = number(grid, "width").unwrap_or(0.0);
102        let height = number(grid, "height").unwrap_or(0.0);
103        if let Some(block) = grid.get("projection") {
104            let block = parse_projection(block)?;
105            return Ok(Grid::Lambert(LambertGrid {
106                width: width as u32,
107                height: height as u32,
108                projection: block.projection,
109                x0: block.x0,
110                y0: block.y0,
111                dx: block.dx,
112                dy: block.dy,
113            }));
114        }
115        let longitude_step = number(grid, "longitudeStep").unwrap_or(0.25);
116        let wraps = grid
117            .get("wrapLongitude")
118            .and_then(|v| v.as_bool())
119            .unwrap_or_else(|| (width * longitude_step - 360.0).abs() < 1e-6);
120        let gaussian = grid
121            .get("gaussian")
122            .map(|block| parse_gaussian(block, height as u64))
123            .transpose()?;
124        Ok(Grid::Regular(RegularGrid {
125            width: width as u32,
126            height: height as u32,
127            first_longitude: number(grid, "firstLongitude").unwrap_or(-180.0),
128            first_latitude: number(grid, "firstLatitude").unwrap_or(90.0),
129            longitude_step,
130            latitude_step: number(grid, "latitudeStep").unwrap_or(-0.25),
131            wraps,
132            gaussian,
133        }))
134    }
135}
136
137/// The cell a point probes: the grid index and the cell's own coordinates.
138#[derive(Debug, Clone, Copy, PartialEq)]
139pub struct ProbeCell {
140    pub column: u32,
141    pub row: u32,
142    pub longitude: f64,
143    pub latitude: f64,
144}
145
146fn number(value: &Value, key: &str) -> Option<f64> {
147    value.get(key).and_then(|v| v.as_f64())
148}
149
150fn wrap(value: f64, modulus: f64) -> f64 {
151    ((value % modulus) + modulus) % modulus
152}
153
154fn normalize_longitude(longitude: f64) -> f64 {
155    wrap(longitude + 180.0, 360.0) - 180.0
156}
157
158/// The cell a point reads, or `None` when it is off the grid (a regional
159/// model's rectangle, a projected footprint, a satellite disk). On a regular
160/// grid the rules are the shell probe's and the fragment shader's
161/// (`web/src/features/probe/probe.ts::probeCell`).
162pub fn probe_cell(grid: &Grid, longitude: f64, latitude: f64) -> Option<ProbeCell> {
163    if !longitude.is_finite() || !latitude.is_finite() {
164        return None;
165    }
166    match grid {
167        Grid::Regular(regular) => probe_regular(regular, longitude, latitude),
168        Grid::Lambert(lambert) => probe_lambert(lambert, longitude, latitude),
169    }
170}
171
172fn probe_regular(grid: &RegularGrid, longitude: f64, latitude: f64) -> Option<ProbeCell> {
173    if grid.width == 0
174        || grid.height == 0
175        || grid.longitude_step == 0.0
176        || grid.latitude_step == 0.0
177    {
178        return None;
179    }
180    let delta = wrap(longitude - grid.first_longitude, 360.0);
181    // `Math.round` rounds half toward +Infinity, not away from zero.
182    let column = (delta / grid.longitude_step + 0.5).floor();
183    let column = if grid.wraps {
184        wrap(column, f64::from(grid.width))
185    } else if column < 0.0 || column >= f64::from(grid.width) {
186        return None;
187    } else {
188        column
189    };
190    let row = ((latitude - grid.first_latitude) / grid.latitude_step + 0.5).floor();
191    let row = match grid.gaussian {
192        Some(gaussian) => gaussian_row(grid, gaussian, row, latitude)?,
193        None if row < 0.0 || row >= f64::from(grid.height) => return None,
194        None => row as u32,
195    };
196    regular_cell(grid, column as u32, row)
197}
198
199/// The Gaussian row nearest `latitude`. `guess` is the row the equidistant
200/// fields give, within a small fraction of a row of the true one, so its
201/// neighbours settle it without building the latitude table. Past a grid edge
202/// a point belongs to the edge row for half a row's spacing, as on a regular
203/// grid, except that the whole Gaussian grid's outer rows own the polar caps.
204fn gaussian_row(
205    grid: &RegularGrid,
206    gaussian: GaussianRows,
207    guess: f64,
208    latitude: f64,
209) -> Option<u32> {
210    if !(-90.0..=90.0).contains(&latitude) {
211        return None;
212    }
213    let last = grid.height - 1;
214    let centre = guess.clamp(0.0, f64::from(last)) as u32;
215    let mut nearest = (centre, gaussian.latitude(centre)?);
216    for row in [centre.saturating_sub(1), centre.saturating_add(1).min(last)] {
217        let candidate = gaussian.latitude(row)?;
218        if (latitude - candidate).abs() < (latitude - nearest.1).abs() {
219            nearest = (row, candidate);
220        }
221    }
222    let (row, centre_latitude) = nearest;
223    let north = latitude > centre_latitude;
224    let outer = (north && row == 0) || (!north && row == last);
225    if !outer || gaussian.reaches_pole(row, north) {
226        return Some(row);
227    }
228    let half_row = if last == 0 {
229        (grid.latitude_step / 2.0).abs()
230    } else {
231        let inner = if row == 0 { 1 } else { last - 1 };
232        (centre_latitude - gaussian.latitude(inner)?).abs() / 2.0
233    };
234    ((latitude - centre_latitude).abs() <= half_row).then_some(row)
235}
236
237fn probe_lambert(grid: &LambertGrid, longitude: f64, latitude: f64) -> Option<ProbeCell> {
238    if !(-90.0..=90.0).contains(&latitude) {
239        return None;
240    }
241    let (x, y) = grid.projection.forward_wrapped(longitude, latitude);
242    let column = ((x - grid.x0) / grid.dx + 0.5).floor();
243    let row = ((y - grid.y0) / grid.dy + 0.5).floor();
244    // Written to refuse a NaN too: the far pole of a cone projects to infinity.
245    if !(column >= 0.0
246        && column < f64::from(grid.width)
247        && row >= 0.0
248        && row < f64::from(grid.height))
249    {
250        return None;
251    }
252    lambert_cell(grid, column as u32, row as u32)
253}
254
255/// A cell addressed by its indices, with its centre; `None` outside the grid.
256/// The inverse of [`probe_cell`]: probing the centre returns the same cell.
257pub fn grid_cell(grid: &Grid, column: u32, row: u32) -> Option<ProbeCell> {
258    match grid {
259        Grid::Regular(regular) => regular_cell(regular, column, row),
260        Grid::Lambert(lambert) => lambert_cell(lambert, column, row),
261    }
262}
263
264fn regular_cell(grid: &RegularGrid, column: u32, row: u32) -> Option<ProbeCell> {
265    if column >= grid.width || row >= grid.height {
266        return None;
267    }
268    let latitude = match grid.gaussian {
269        Some(gaussian) => gaussian.latitude(row)?,
270        None => grid.first_latitude + f64::from(row) * grid.latitude_step,
271    };
272    Some(ProbeCell {
273        column,
274        row,
275        longitude: normalize_longitude(
276            grid.first_longitude + f64::from(column) * grid.longitude_step,
277        ),
278        latitude,
279    })
280}
281
282fn lambert_cell(grid: &LambertGrid, column: u32, row: u32) -> Option<ProbeCell> {
283    if column >= grid.width || row >= grid.height {
284        return None;
285    }
286    let (longitude, latitude) = grid.projection.inverse(
287        grid.x0 + f64::from(column) * grid.dx,
288        grid.y0 + f64::from(row) * grid.dy,
289    );
290    Some(ProbeCell {
291        column,
292        row,
293        longitude: normalize_longitude(longitude),
294        latitude,
295    })
296}
297
298// -- quantisation --------------------------------------------------------------
299
300/// A codebook: how a stored code maps back to a physical value
301/// (`docs/bundle.md`, "Codebooks"). Its code keys are integers up to 65535;
302/// which of them fit is the width of the array or container that holds them.
303#[derive(Debug, Clone, Copy, PartialEq)]
304pub enum Quantization {
305    Linear {
306        offset: f64,
307        scale: f64,
308        minimum_code: f64,
309        maximum_code: f64,
310        nodata_code: f64,
311    },
312    Log1p {
313        trace: f64,
314        scale: f64,
315        maximum: f64,
316        minimum_code: f64,
317        maximum_code: f64,
318        zero_code: f64,
319        overflow_code: f64,
320        nodata_code: f64,
321    },
322}
323
324impl Quantization {
325    /// The step a linear codebook quantises against, for a response's
326    /// informational `quantization.step`.
327    pub fn step(&self) -> Option<f64> {
328        match self {
329            Quantization::Linear { scale, .. } => Some(*scale),
330            Quantization::Log1p { .. } => None,
331        }
332    }
333
334    /// The codebook's no-data code.
335    pub fn nodata_code(&self) -> f64 {
336        match *self {
337            Quantization::Linear { nodata_code, .. } | Quantization::Log1p { nodata_code, .. } => {
338                nodata_code
339            }
340        }
341    }
342
343    /// Every code key the codebook names.
344    fn codes(&self) -> Vec<f64> {
345        match *self {
346            Quantization::Linear {
347                minimum_code,
348                maximum_code,
349                nodata_code,
350                ..
351            } => vec![minimum_code, maximum_code, nodata_code],
352            Quantization::Log1p {
353                minimum_code,
354                maximum_code,
355                zero_code,
356                overflow_code,
357                nodata_code,
358                ..
359            } => vec![
360                minimum_code,
361                maximum_code,
362                zero_code,
363                overflow_code,
364                nodata_code,
365            ],
366        }
367    }
368}
369
370/// Code → physical value, or `None` for a missing/overflow code
371/// (`web/src/render/palettes.ts::decodeValue`, and the schema v3 block beside it).
372pub fn decode_value(quantization: &Quantization, code: u16) -> Option<f64> {
373    let code = f64::from(code);
374    match *quantization {
375        Quantization::Linear {
376            offset,
377            scale,
378            maximum_code,
379            nodata_code,
380            ..
381        } => {
382            if code == nodata_code || code > maximum_code {
383                None
384            } else {
385                Some(offset + code * scale)
386            }
387        }
388        Quantization::Log1p {
389            trace,
390            scale,
391            maximum,
392            minimum_code,
393            maximum_code,
394            zero_code,
395            overflow_code,
396            nodata_code,
397        } => {
398            if code == nodata_code {
399                return None;
400            }
401            if code == zero_code {
402                return Some(0.0);
403            }
404            if code > overflow_code {
405                return None;
406            }
407            let lo = (trace / scale).ln_1p();
408            let hi = (maximum / scale).ln_1p();
409            let unit = (code - minimum_code) / (maximum_code - minimum_code);
410            Some(scale * (lo + unit * (hi - lo)).exp_m1())
411        }
412    }
413}
414
415pub(crate) fn parse_quantization(value: &Value) -> Result<Quantization, DecodeError> {
416    let kind = value.get("type").and_then(|v| v.as_str());
417    let number = |key: &str| -> Result<f64, DecodeError> {
418        value
419            .get(key)
420            .and_then(|v| v.as_f64())
421            .ok_or_else(|| err(format!("quantization {key} is invalid")))
422    };
423    // A code key is an integer a uint16 can hold; whether it also fits a
424    // uint8 is the holding array's rule ([`check_codebook`]).
425    let code = |key: &str| -> Result<f64, DecodeError> {
426        number(key).and_then(|code| {
427            if code.fract() == 0.0 && (0.0..=f64::from(u16::MAX)).contains(&code) {
428                Ok(code)
429            } else {
430                Err(err(format!(
431                    "quantization {key} is not a code in 0..=65535"
432                )))
433            }
434        })
435    };
436    match kind {
437        Some("linear") => Ok(Quantization::Linear {
438            offset: number("offset")?,
439            scale: number("scale")?,
440            minimum_code: code("minimumCode")?,
441            maximum_code: code("maximumCode")?,
442            nodata_code: code("nodataCode")?,
443        }),
444        Some("log1p") => Ok(Quantization::Log1p {
445            trace: number("trace")?,
446            scale: number("scale")?,
447            maximum: number("maximum")?,
448            minimum_code: code("minimumCode")?,
449            maximum_code: code("maximumCode")?,
450            zero_code: code("zeroCode")?,
451            overflow_code: code("overflowCode")?,
452            nodata_code: code("nodataCode")?,
453        }),
454        _ => Err(err("unsupported bundle quantization")),
455    }
456}
457
458// -- bundle metadata -----------------------------------------------------------
459
460/// One variable in the group's metadata.
461#[derive(Debug, Clone)]
462pub struct VariableMetadata {
463    pub numeric_id: u8,
464    pub id: String,
465    pub label: Option<String>,
466    pub unit: Option<String>,
467    pub quantization: Quantization,
468}
469
470/// The bundle metadata a store's group carries in `attributes.xue`, reduced to
471/// what a reader needs: the grid, the materialized time axis and the variables
472/// with their codebooks.
473#[derive(Debug, Clone)]
474pub struct BundleMetadata {
475    pub schema_version: u8,
476    pub run_time: Option<String>,
477    pub unit_seconds: u32,
478    pub offsets: Vec<u16>,
479    pub grid: Grid,
480    pub variables: Vec<VariableMetadata>,
481}
482
483/// Parse and validate a bundle metadata JSON document. Validation is the
484/// container decoder's own (`crate::decode::metadata`), so the two readers
485/// agree on what is a valid document; the geo and codebook fields the API
486/// needs are read off the same object afterwards.
487pub fn parse_bundle_metadata(text: &str) -> Result<BundleMetadata, DecodeError> {
488    let validated = crate::decode::metadata::parse_metadata(text.as_bytes())?;
489    let value: Value = serde_json::from_str(text).map_err(|_| err("metadata is not valid JSON"))?;
490    let object = value
491        .as_object()
492        .ok_or_else(|| err("metadata must be a JSON object"))?;
493    let variables = object
494        .get("variables")
495        .and_then(|v| v.as_array())
496        .ok_or_else(|| err("metadata variables missing"))?;
497    let mut parsed = Vec::with_capacity(variables.len());
498    for variable in variables {
499        let numeric_id = variable
500            .get("numericId")
501            .and_then(|v| v.as_u64())
502            .filter(|&id| (1..=255).contains(&id))
503            .ok_or_else(|| err("variable numericId is invalid"))?;
504        let id = variable
505            .get("id")
506            .and_then(|v| v.as_str())
507            .ok_or_else(|| err("variable id is invalid"))?;
508        let quantization = parse_quantization(
509            variable
510                .get("quantization")
511                .ok_or_else(|| err("variable quantization missing"))?,
512        )?;
513        parsed.push(VariableMetadata {
514            numeric_id: numeric_id as u8,
515            id: id.to_owned(),
516            label: variable
517                .get("label")
518                .and_then(|v| v.as_str())
519                .map(str::to_owned),
520            unit: variable
521                .get("unit")
522                .and_then(|v| v.as_str())
523                .map(str::to_owned),
524            quantization,
525        });
526    }
527    Ok(BundleMetadata {
528        schema_version: validated.schema_version,
529        run_time: object
530            .get("runTime")
531            .and_then(|v| v.as_str())
532            .map(str::to_owned),
533        unit_seconds: validated.unit_seconds,
534        offsets: validated.offsets.clone(),
535        grid: Grid::from_metadata(&value)?,
536        variables: parsed,
537    })
538}
539
540/// The `xue_profile` of a store holding one bundle, its metadata in
541/// `attributes.xue`.
542pub const PROFILE_SINGLE: u32 = 1;
543/// The `xue_profile` of a shared store: every bundle of one resolution tier
544/// in one group, each bundle's metadata under `attributes.xue_bundles[id]`.
545pub const PROFILE_SHARED: u32 = 2;
546
547/// A parsed group document, reduced to one bundle: the metadata, its compact
548/// re-serialization, the profile version and, on a shared store, the id the
549/// bundle was selected by.
550#[derive(Debug, Clone)]
551pub struct ZarrGroup {
552    pub metadata: BundleMetadata,
553    pub metadata_json: String,
554    pub profile: u32,
555    /// The bundle id selected out of a shared (profile 2) group; `None` on a
556    /// single-bundle store, whose group does not name its bundle.
557    pub bundle: Option<String>,
558}
559
560/// The profile's four branches (`docs/zarr-profile.md`): a bundle's grid
561/// store, a radar's polar store, a river's network store and a run's column
562/// store.
563#[derive(Debug, Clone, Copy, PartialEq, Eq)]
564pub enum StoreKind {
565    Grid,
566    Polar,
567    Network,
568    Column,
569}
570
571/// The group attribute that names each branch. A grid store names it with
572/// `xue` (one bundle) or `xue_bundles` (a shared store), never both.
573const BRANCH_BLOCKS: [(&str, StoreKind); 5] = [
574    ("xue", StoreKind::Grid),
575    ("xue_bundles", StoreKind::Grid),
576    ("xue_polar", StoreKind::Polar),
577    ("xue_network", StoreKind::Network),
578    ("xue_columns", StoreKind::Column),
579];
580
581/// A Zarr v3 group document's attributes, and the branch they declare: exactly
582/// one of `xue`, `xue_bundles`, `xue_polar`, `xue_network` and `xue_columns` is
583/// present, or the group is none of the profile's.
584pub(crate) fn group_branch(
585    text: &str,
586) -> Result<(StoreKind, serde_json::Map<String, Value>), DecodeError> {
587    let value: Value =
588        serde_json::from_str(text).map_err(|_| err("group metadata is not valid JSON"))?;
589    let (kind, attributes) = document_branch(&value)?;
590    Ok((kind, attributes.clone()))
591}
592
593/// [`group_branch`] over a document already parsed.
594pub(crate) fn document_branch(
595    value: &Value,
596) -> Result<(StoreKind, &serde_json::Map<String, Value>), DecodeError> {
597    if value.get("zarr_format").and_then(|v| v.as_u64()) != Some(3)
598        || value.get("node_type").and_then(|v| v.as_str()) != Some("group")
599    {
600        return Err(err("not a Zarr v3 group"));
601    }
602    let Some(Value::Object(attributes)) = value.get("attributes") else {
603        return Err(err("group attributes missing"));
604    };
605    let mut present = BRANCH_BLOCKS
606        .iter()
607        .filter(|(key, _)| attributes.contains_key(*key))
608        .map(|&(_, kind)| kind);
609    match (present.next(), present.next()) {
610        (Some(kind), None) => Ok((kind, attributes)),
611        (None, _) => Err(err("group attributes carry no xue metadata block")),
612        (Some(_), Some(_)) => Err(err(
613            "group attributes carry more than one of xue, xue_bundles, xue_polar, xue_network and xue_columns",
614        )),
615    }
616}
617
618/// Which branch of the profile a store's group document declares.
619pub fn store_kind(text: &str) -> Result<StoreKind, DecodeError> {
620    group_branch(text).map(|(kind, _)| kind)
621}
622
623/// A grid store's attributes and its profile, held to the block that profile
624/// carries: `xue` on profile 1, a non-empty `xue_bundles` object on profile 2.
625/// Any other version is one this reader does not implement.
626fn grid_group(text: &str) -> Result<(u32, serde_json::Map<String, Value>), DecodeError> {
627    let (kind, attributes) = group_branch(text)?;
628    if kind != StoreKind::Grid {
629        return Err(err("group is not a grid store"));
630    }
631    let profile = attributes
632        .get("xue_profile")
633        .and_then(|v| v.as_u64())
634        .ok_or_else(|| err("group attributes carry no xue_profile version"))?;
635    match profile {
636        1 => {
637            if !attributes.get("xue").is_some_and(Value::is_object) {
638                return Err(err("group attributes carry no xue metadata block"));
639            }
640            Ok((PROFILE_SINGLE, attributes))
641        }
642        2 => {
643            let held = attributes
644                .get("xue_bundles")
645                .and_then(|v| v.as_object())
646                .ok_or_else(|| err("a profile 2 group carries no xue_bundles object"))?;
647            if held.is_empty() {
648                return Err(err("a profile 2 group's xue_bundles holds no bundle"));
649            }
650            Ok((PROFILE_SHARED, attributes))
651        }
652        other => Err(err(format!("xue_profile {other} is not implemented"))),
653    }
654}
655
656/// One bundle's metadata block out of a grid store's attributes: `xue` on a
657/// single-bundle store, whatever `bundle` says, since that group holds one
658/// bundle and does not name it; `xue_bundles[bundle]` on a shared one, which
659/// is refused without a bundle named, since nothing else in it says whose
660/// metadata a reader would be holding.
661fn group_block<'a>(
662    attributes: &'a serde_json::Map<String, Value>,
663    profile: u32,
664    bundle: Option<&str>,
665) -> Result<&'a Value, DecodeError> {
666    if profile == PROFILE_SINGLE {
667        return Ok(&attributes["xue"]);
668    }
669    let bundle = bundle.ok_or_else(|| {
670        err("a shared (profile 2) group holds several bundles; open it by bundle id")
671    })?;
672    let metadata = attributes["xue_bundles"]
673        .get(bundle)
674        .ok_or_else(|| err(format!("shared group holds no bundle {bundle:?}")))?;
675    if !metadata.is_object() {
676        return Err(err(format!(
677            "shared group's bundle {bundle:?} is not an object"
678        )));
679    }
680    Ok(metadata)
681}
682
683fn group_of(
684    metadata: &Value,
685    profile: u32,
686    bundle: Option<&str>,
687) -> Result<ZarrGroup, DecodeError> {
688    let metadata_json =
689        serde_json::to_string(metadata).map_err(|_| err("xue metadata is not serializable"))?;
690    let parsed = parse_bundle_metadata(&metadata_json)?;
691    Ok(ZarrGroup {
692        metadata: parsed,
693        metadata_json,
694        profile,
695        bundle: bundle.map(str::to_owned),
696    })
697}
698
699/// The root `zarr.json` of a single-bundle (profile 1) store
700/// (`docs/zarr-profile.md`, "Attributes"). A shared store holds several
701/// bundles and is refused here: open it with [`parse_group_metadata_for`].
702pub fn parse_group_metadata(text: &str) -> Result<ZarrGroup, DecodeError> {
703    let (profile, attributes) = grid_group(text)?;
704    group_of(group_block(&attributes, profile, None)?, profile, None)
705}
706
707/// One bundle's view of a store's root `zarr.json`, whichever profile wrote
708/// it: on a shared (profile 2) store, `attributes.xue_bundles[bundle]`; on a
709/// single-bundle (profile 1) store, `attributes.xue`, with `bundle` ignored,
710/// since that group holds one bundle and does not name it. A reader opens a
711/// store by `(path, bundle id)` and the manifest entry gives it both.
712pub fn parse_group_metadata_for(text: &str, bundle: &str) -> Result<ZarrGroup, DecodeError> {
713    let (profile, attributes) = grid_group(text)?;
714    let selected = (profile == PROFILE_SHARED).then_some(bundle);
715    group_of(
716        group_block(&attributes, profile, Some(bundle))?,
717        profile,
718        selected,
719    )
720}
721
722/// The group document read no further than its envelope: the profile, and
723/// the selected bundle's metadata block as compact JSON, selected as
724/// [`parse_group_metadata_for`] selects it and refused without a bundle named
725/// on a shared store. The block itself is not validated here. This is for a
726/// reader that holds the block to the metadata rules with a validator of its
727/// own, as the shell does; every other caller wants [`parse_group_metadata_for`].
728///
729/// The JSON keeps the document's key order only where `serde_json` keeps
730/// insertion order (the `encoder` feature turns that on); otherwise the keys
731/// come out sorted.
732pub fn group_metadata_json(text: &str, bundle: Option<&str>) -> Result<(u32, String), DecodeError> {
733    let (profile, attributes) = grid_group(text)?;
734    let block = group_block(&attributes, profile, bundle)?;
735    let metadata_json =
736        serde_json::to_string(block).map_err(|_| err("xue metadata is not serializable"))?;
737    Ok((profile, metadata_json))
738}
739
740/// The bundle ids a store's group holds: every key of `xue_bundles` on a
741/// shared store, `None` on a single-bundle store, whose group does not name
742/// its bundle. They come in the group's order only where `serde_json` keeps
743/// insertion order (the `encoder` feature turns that on); otherwise sorted.
744pub fn group_bundle_ids(text: &str) -> Result<Option<Vec<String>>, DecodeError> {
745    let (profile, attributes) = grid_group(text)?;
746    if profile == PROFILE_SINGLE {
747        return Ok(None);
748    }
749    Ok(Some(
750        attributes["xue_bundles"]
751            .as_object()
752            .map(|held| held.keys().cloned().collect())
753            .unwrap_or_default(),
754    ))
755}
756
757// -- array metadata ------------------------------------------------------------
758
759/// Where a shard's index sits within the object.
760#[derive(Debug, Clone, Copy, PartialEq, Eq)]
761pub enum IndexLocation {
762    Start,
763    End,
764}
765
766/// The code width a variable array declares in `data_type`. Every map,
767/// column and network array is `uint8`; a series store's widened variable is
768/// `uint16`, little-endian on disk.
769#[derive(Debug, Clone, Copy, PartialEq, Eq)]
770pub enum DataType {
771    U8,
772    U16,
773}
774
775impl DataType {
776    /// The `data_type` string a document spells it with.
777    pub fn name(self) -> &'static str {
778        match self {
779            DataType::U8 => "uint8",
780            DataType::U16 => "uint16",
781        }
782    }
783
784    /// The largest code the type holds.
785    pub fn max_code(self) -> u16 {
786        match self {
787            DataType::U8 => u16::from(u8::MAX),
788            DataType::U16 => u16::MAX,
789        }
790    }
791
792    fn from_name(name: &str) -> Option<DataType> {
793        match name {
794            "uint8" => Some(DataType::U8),
795            "uint16" => Some(DataType::U16),
796            _ => None,
797        }
798    }
799}
800
801/// How one variable's array is cut (`docs/zarr-profile.md`, "Array
802/// metadata"). `time_chunk`, `tile_height` and `tile_width` are the inner
803/// chunk; `shard_frames` is the outer chunk's time extent, a positive multiple
804/// of the time chunk.
805#[derive(Debug, Clone, Copy, PartialEq)]
806pub struct ArrayLayout {
807    pub frame_count: u32,
808    pub height: u32,
809    pub width: u32,
810    pub time_chunk: u32,
811    pub tile_height: u32,
812    pub tile_width: u32,
813    pub tile_rows: u32,
814    pub tile_columns: u32,
815    pub tile_count: u32,
816    pub time_chunks: u32,
817    pub shard_frames: u32,
818    pub shard_count: u32,
819    pub chunks_per_shard: u32,
820    pub delta: bool,
821    pub index_location: IndexLocation,
822    pub data_type: DataType,
823    pub fill_value: u16,
824}
825
826fn positive_ints(value: &Value, count: usize, what: &str) -> Result<Vec<u64>, DecodeError> {
827    let list = value
828        .as_array()
829        .filter(|list| list.len() == count)
830        .ok_or_else(|| err(format!("{what} must list {count} entries")))?;
831    let mut out = Vec::with_capacity(count);
832    for item in list {
833        let number = item
834            .as_u64()
835            .filter(|&number| number > 0)
836            .ok_or_else(|| err(format!("{what} must be positive integers")))?;
837        out.push(number);
838    }
839    Ok(out)
840}
841
842fn codec_names(value: &Value, what: &str) -> Result<Vec<String>, DecodeError> {
843    let list = value
844        .as_array()
845        .ok_or_else(|| err(format!("{what} must be a list")))?;
846    let mut names = Vec::with_capacity(list.len());
847    for item in list {
848        let name = item
849            .as_object()
850            .and_then(|codec| codec.get("name"))
851            .and_then(|name| name.as_str())
852            .ok_or_else(|| err(format!("{what} entry is not an object")))?;
853        names.push(name.to_owned());
854    }
855    Ok(names)
856}
857
858/// The fields every sharded array of the profile shares — a grid
859/// variable, a network store's `streamflow`, a column store's array — once the
860/// document is held to the codec rules: a regular chunk grid, the default key encoding, exactly one
861/// `sharding_indexed` codec, an inner chain of `[bytes, zstd]` or
862/// `[xue.delta{axis: 0}, bytes, zstd]`, index codecs `[bytes, crc32c]`
863/// little-endian at the `start` or `end`, and a fill value the data type
864/// holds. The shapes are checked for their rank and for being positive; how
865/// they relate is each branch's own rule.
866#[derive(Debug, Clone)]
867pub(crate) struct ShardedArray {
868    pub(crate) value: Value,
869    pub(crate) shape: Vec<u64>,
870    pub(crate) shard_shape: Vec<u64>,
871    pub(crate) inner_shape: Vec<u64>,
872    pub(crate) delta: bool,
873    pub(crate) index_location: IndexLocation,
874    pub(crate) data_type: DataType,
875    pub(crate) fill_value: u16,
876}
877
878/// A `uint8` sharded array: what the network and column branches hold.
879pub(crate) fn parse_sharded_array(text: &str, rank: usize) -> Result<ShardedArray, DecodeError> {
880    let value: Value =
881        serde_json::from_str(text).map_err(|_| err("array metadata is not valid JSON"))?;
882    sharded_array(value, rank)
883}
884
885/// [`parse_sharded_array`] over a document already parsed, as one out of a
886/// group's consolidated metadata is.
887pub(crate) fn sharded_array(value: Value, rank: usize) -> Result<ShardedArray, DecodeError> {
888    sharded_array_of(value, rank, &[DataType::U8])
889}
890
891/// A sharded array of one of the `widths` named.
892pub(crate) fn sharded_array_of(
893    value: Value,
894    rank: usize,
895    widths: &[DataType],
896) -> Result<ShardedArray, DecodeError> {
897    if value.get("zarr_format").and_then(|v| v.as_u64()) != Some(3)
898        || value.get("node_type").and_then(|v| v.as_str()) != Some("array")
899    {
900        return Err(err("not a Zarr v3 array"));
901    }
902    let data_type = value
903        .get("data_type")
904        .and_then(|v| v.as_str())
905        .and_then(DataType::from_name)
906        .filter(|data_type| widths.contains(data_type))
907        .ok_or_else(|| {
908            let names: Vec<&str> = widths.iter().map(|width| width.name()).collect();
909            err(format!("array data type must be {}", names.join(" or ")))
910        })?;
911    let shape = positive_ints(
912        value
913            .get("shape")
914            .ok_or_else(|| err("array shape missing"))?,
915        rank,
916        "array shape",
917    )?;
918    let chunk_grid = value
919        .get("chunk_grid")
920        .and_then(|v| v.as_object())
921        .ok_or_else(|| err("chunk grid missing"))?;
922    if chunk_grid.get("name").and_then(|v| v.as_str()) != Some("regular") {
923        return Err(err("chunk grid must be regular"));
924    }
925    let shard_shape = positive_ints(
926        chunk_grid
927            .get("configuration")
928            .and_then(|v| v.get("chunk_shape"))
929            .ok_or_else(|| err("chunk shape missing"))?,
930        rank,
931        "chunk shape",
932    )?;
933    let key_encoding = value
934        .get("chunk_key_encoding")
935        .and_then(|v| v.as_object())
936        .ok_or_else(|| err("chunk key encoding missing"))?;
937    if key_encoding.get("name").and_then(|v| v.as_str()) != Some("default") {
938        return Err(err("chunk key encoding must be default"));
939    }
940    // A configuration is optional and so is its separator, but one that is
941    // present must say `/`: anything else names objects this reader never
942    // asks for.
943    match key_encoding.get("configuration") {
944        None => {}
945        Some(Value::Object(configuration)) => match configuration.get("separator") {
946            None => {}
947            Some(Value::String(separator)) if separator == "/" => {}
948            Some(_) => return Err(err("chunk key separator must be /")),
949        },
950        Some(_) => return Err(err("chunk key encoding configuration is not an object")),
951    }
952    let fill_value = value
953        .get("fill_value")
954        .and_then(|v| v.as_u64())
955        .filter(|&fill| fill <= u64::from(data_type.max_code()))
956        .ok_or_else(|| err(format!("fill value must be a {} code", data_type.name())))?;
957
958    let outer = codec_names(
959        value.get("codecs").ok_or_else(|| err("codecs missing"))?,
960        "codecs",
961    )?;
962    if outer != ["sharding_indexed"] {
963        return Err(err("array must carry exactly one sharding_indexed codec"));
964    }
965    let sharding = value
966        .get("codecs")
967        .and_then(|v| v.as_array())
968        .and_then(|list| list.first())
969        .and_then(|codec| codec.get("configuration"))
970        .and_then(|v| v.as_object())
971        .ok_or_else(|| err("sharding configuration missing"))?;
972    let inner_shape = positive_ints(
973        sharding
974            .get("chunk_shape")
975            .ok_or_else(|| err("inner chunk shape missing"))?,
976        rank,
977        "inner chunk shape",
978    )?;
979    let inner = codec_names(
980        sharding
981            .get("codecs")
982            .ok_or_else(|| err("inner codecs missing"))?,
983        "inner codecs",
984    )?;
985    let inner_names: Vec<&str> = inner.iter().map(String::as_str).collect();
986    let bytes_codec = sharding
987        .get("codecs")
988        .and_then(|v| v.as_array())
989        .and_then(|list| {
990            list.iter()
991                .find(|codec| codec.get("name").and_then(|v| v.as_str()) == Some("bytes"))
992        });
993    // Codes wider than a byte are little-endian and must say so; a uint8
994    // array's `bytes` carries no configuration, and one that is there must
995    // say little-endian too.
996    match bytes_codec.and_then(|codec| codec.get("configuration")) {
997        None if data_type == DataType::U8 => {}
998        None => return Err(err("a uint16 array's bytes codec must say endian little")),
999        Some(configuration) => {
1000            if configuration.get("endian").and_then(|v| v.as_str()) != Some("little") {
1001                return Err(err("array bytes codec must be little-endian"));
1002            }
1003        }
1004    }
1005    let delta = if inner_names == [DELTA_CODEC, "bytes", "zstd"] {
1006        let axis = sharding
1007            .get("codecs")
1008            .and_then(|v| v.as_array())
1009            .and_then(|list| list.first())
1010            .and_then(|codec| codec.get("configuration"))
1011            .and_then(|v| v.get("axis"))
1012            .and_then(|v| v.as_u64());
1013        if axis != Some(0) {
1014            return Err(err("xue.delta must run along axis 0"));
1015        }
1016        true
1017    } else if inner_names == ["bytes", "zstd"] {
1018        false
1019    } else {
1020        return Err(err("inner codec chain is not one this profile reads"));
1021    };
1022    let index = codec_names(
1023        sharding
1024            .get("index_codecs")
1025            .ok_or_else(|| err("index codecs missing"))?,
1026        "index codecs",
1027    )?;
1028    if index != ["bytes", "crc32c"] {
1029        return Err(err("index codecs must be [bytes, crc32c]"));
1030    }
1031    // Little-endian is the `bytes` codec's default only where it carries no
1032    // configuration at all; one that is there has to say so.
1033    let little = match sharding
1034        .get("index_codecs")
1035        .and_then(|v| v.as_array())
1036        .and_then(|list| list.first())
1037        .and_then(|codec| codec.get("configuration"))
1038    {
1039        None => true,
1040        Some(configuration) => {
1041            configuration.get("endian").and_then(|v| v.as_str()) == Some("little")
1042        }
1043    };
1044    if !little {
1045        return Err(err("shard index must be little-endian"));
1046    }
1047    let index_location = match sharding.get("index_location") {
1048        None | Some(Value::Null) => IndexLocation::End,
1049        Some(Value::String(location)) if location == "start" => IndexLocation::Start,
1050        Some(Value::String(location)) if location == "end" => IndexLocation::End,
1051        Some(other) => return Err(err(format!("unknown index location {other}"))),
1052    };
1053    Ok(ShardedArray {
1054        value,
1055        shape,
1056        shard_shape,
1057        inner_shape,
1058        delta,
1059        index_location,
1060        data_type,
1061        // Bounded by the data type above.
1062        fill_value: fill_value as u16,
1063    })
1064}
1065
1066/// A variable array's document: how the array is cut, and the bundle it says
1067/// it belongs to.
1068#[derive(Debug, Clone, PartialEq)]
1069pub struct ArrayDocument {
1070    pub layout: ArrayLayout,
1071    /// `attributes.xue.bundle`, which a shared store's arrays carry; `None`
1072    /// where the array declares none.
1073    pub bundle: Option<String>,
1074}
1075
1076/// The array's `zarr.json`, held to the profile: `uint8` (or `uint16`, a
1077/// series store's widened variable), three dimensions, a regular chunk grid,
1078/// exactly one `sharding_indexed` codec, an inner chain of `[bytes, zstd]` or
1079/// `[xue.delta{axis: 0}, bytes, zstd]`, index codecs `[bytes, crc32c]`
1080/// little-endian, and an outer chunk of whole time chunks of whole tiles.
1081/// Where the array carries its variable's codebook
1082/// (`attributes.xue.variable.quantization`) it is held to [`check_codebook`];
1083/// a `uint16` array must carry one.
1084pub fn parse_array_metadata(text: &str) -> Result<ArrayLayout, DecodeError> {
1085    parse_array_document(text).map(|document| document.layout)
1086}
1087
1088/// [`parse_array_metadata`], with the bundle the array names.
1089///
1090/// Every size a reader later allocates from is bounded here: a plane and an
1091/// inner chunk by the container's own limit on a decoded plane, and a shard's
1092/// index by the same limit in bytes.
1093pub fn parse_array_document(text: &str) -> Result<ArrayDocument, DecodeError> {
1094    let ShardedArray {
1095        value,
1096        shape,
1097        shard_shape,
1098        inner_shape,
1099        delta,
1100        index_location,
1101        data_type,
1102        fill_value,
1103    } = sharded_array_of(
1104        serde_json::from_str(text).map_err(|_| err("array metadata is not valid JSON"))?,
1105        3,
1106        &[DataType::U8, DataType::U16],
1107    )?;
1108    let [frames, height, width] = [shape[0], shape[1], shape[2]];
1109    let [time_chunk, tile_height, tile_width] = [inner_shape[0], inner_shape[1], inner_shape[2]];
1110    let within = |cells: Option<u64>| cells.is_some_and(|cells| cells <= MAX_PLANE_LENGTH);
1111    let shard_frames = shard_shape[0];
1112    if frames.max(shard_frames) > u64::from(u32::MAX) || !within(height.checked_mul(width)) {
1113        return Err(err("array shape exceeds the decoded size limit"));
1114    }
1115    if !within(
1116        tile_height
1117            .checked_mul(tile_width)
1118            .and_then(|cells| cells.checked_mul(time_chunk)),
1119    ) {
1120        return Err(err("inner chunk exceeds the decoded size limit"));
1121    }
1122    // Bounded above: a tile is at least one cell, so there are no more tiles
1123    // along an axis than cells.
1124    let tile_rows = height.div_ceil(tile_height);
1125    let tile_columns = width.div_ceil(tile_width);
1126    let tile_count = tile_rows * tile_columns;
1127    if shard_frames % time_chunk != 0
1128        || shard_shape[1] != tile_rows * tile_height
1129        || shard_shape[2] != tile_columns * tile_width
1130    {
1131        return Err(err("outer chunk must be whole time chunks of whole tiles"));
1132    }
1133    let chunks_per_shard = (shard_frames / time_chunk)
1134        .checked_mul(tile_count)
1135        .filter(|&count| count.saturating_mul(INDEX_ENTRY_BYTES as u64) <= MAX_PLANE_LENGTH)
1136        .ok_or_else(|| err("shard index exceeds the decoded size limit"))?;
1137    // Every value below is under one of the limits above, or counts
1138    // something one of them bounds.
1139    let layout = ArrayLayout {
1140        frame_count: frames as u32,
1141        height: height as u32,
1142        width: width as u32,
1143        time_chunk: time_chunk as u32,
1144        tile_height: tile_height as u32,
1145        tile_width: tile_width as u32,
1146        tile_rows: tile_rows as u32,
1147        tile_columns: tile_columns as u32,
1148        tile_count: tile_count as u32,
1149        time_chunks: frames.div_ceil(time_chunk) as u32,
1150        shard_frames: shard_frames as u32,
1151        shard_count: frames.div_ceil(shard_frames) as u32,
1152        chunks_per_shard: chunks_per_shard as u32,
1153        delta,
1154        index_location,
1155        data_type,
1156        fill_value,
1157    };
1158    match array_codebook(&value)? {
1159        Some(quantization) => check_codebook(&layout, &quantization)?,
1160        None if data_type == DataType::U16 => {
1161            return Err(err("a uint16 array must carry its variable's quantization"))
1162        }
1163        None => {}
1164    }
1165    Ok(ArrayDocument {
1166        layout,
1167        bundle: array_bundle(&value)?,
1168    })
1169}
1170
1171/// `attributes.xue.variable.quantization`, where an array carries one.
1172fn array_codebook(array: &Value) -> Result<Option<Quantization>, DecodeError> {
1173    array
1174        .get("attributes")
1175        .and_then(|attributes| attributes.get("xue"))
1176        .and_then(|xue| xue.get("variable"))
1177        .and_then(|variable| variable.get("quantization"))
1178        .map(parse_quantization)
1179        .transpose()
1180}
1181
1182/// Hold a codebook to the array whose codes it reads: the array's fill value
1183/// is the codebook's `nodataCode`, and every code key fits the array's data
1184/// type. A reader dequantizing an array with metadata held elsewhere (the
1185/// group's) checks that block against the array with this.
1186pub fn check_codebook(
1187    layout: &ArrayLayout,
1188    quantization: &Quantization,
1189) -> Result<(), DecodeError> {
1190    if quantization.nodata_code() != f64::from(layout.fill_value) {
1191        return Err(err("array fill_value must be the codebook's nodataCode"));
1192    }
1193    let max = f64::from(layout.data_type.max_code());
1194    if quantization.codes().into_iter().any(|code| code > max) {
1195        return Err(err(format!(
1196            "a codebook on a {} array names a code past {max}",
1197            layout.data_type.name()
1198        )));
1199    }
1200    Ok(())
1201}
1202
1203/// `attributes.xue.bundle`, where an array carries one. Anything else in the
1204/// attributes is informational and left alone.
1205fn array_bundle(array: &Value) -> Result<Option<String>, DecodeError> {
1206    let Some(bundle) = array
1207        .get("attributes")
1208        .and_then(|attributes| attributes.get("xue"))
1209        .and_then(|xue| xue.get("bundle"))
1210    else {
1211        return Ok(None);
1212    };
1213    match bundle.as_str() {
1214        Some(id) if !id.is_empty() => Ok(Some(id.to_owned())),
1215        _ => Err(err("array attributes name no bundle id")),
1216    }
1217}
1218
1219// -- shard index ---------------------------------------------------------------
1220
1221/// The CRC-32C (Castagnoli) checksum the `crc32c` codec puts over a shard
1222/// index — a different polynomial from the container's CRC-32/IEEE.
1223pub fn crc32c(bytes: &[u8]) -> u32 {
1224    let mut crc = 0xffff_ffffu32;
1225    for &byte in bytes {
1226        crc ^= u32::from(byte);
1227        for _ in 0..8 {
1228            let mask = (crc & 1).wrapping_neg();
1229            crc = (crc >> 1) ^ (0x82f6_3b78 & mask);
1230        }
1231    }
1232    !crc
1233}
1234
1235/// The byte length of a shard's index: one pair per inner chunk plus the
1236/// checksum.
1237pub fn shard_index_length(chunk_count: usize) -> usize {
1238    INDEX_ENTRY_BYTES * chunk_count + INDEX_CHECKSUM_BYTES
1239}
1240
1241/// One inner chunk's byte span within its shard.
1242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1243pub struct ShardIndexEntry {
1244    pub offset: u64,
1245    pub length: u64,
1246}
1247
1248/// The `(offset, nbytes)` pairs of one shard, CRC-32C verified. `None` marks an
1249/// inner chunk the shard never held — the all-ones sentinel — which reads as
1250/// the fill value. `bytes` is exactly the index.
1251pub fn parse_shard_index(
1252    bytes: &[u8],
1253    chunk_count: usize,
1254) -> Result<Vec<Option<ShardIndexEntry>>, DecodeError> {
1255    let expected = shard_index_length(chunk_count);
1256    if bytes.len() != expected {
1257        return Err(err(format!(
1258            "shard index is {} bytes, not {expected}",
1259            bytes.len()
1260        )));
1261    }
1262    let entries = &bytes[..INDEX_ENTRY_BYTES * chunk_count];
1263    let checksum = u32::from_le_bytes(
1264        bytes[INDEX_ENTRY_BYTES * chunk_count..]
1265            .try_into()
1266            .map_err(|_| err("shard index checksum is malformed"))?,
1267    );
1268    if checksum != crc32c(entries) {
1269        return Err(err("shard index CRC-32C mismatch"));
1270    }
1271    let mut index = Vec::with_capacity(chunk_count);
1272    for position in 0..chunk_count {
1273        let pair = &entries[position * INDEX_ENTRY_BYTES..][..INDEX_ENTRY_BYTES];
1274        let offset = u64::from_le_bytes(pair[..8].try_into().unwrap());
1275        let length = u64::from_le_bytes(pair[8..].try_into().unwrap());
1276        if offset == u64::MAX && length == u64::MAX {
1277            index.push(None);
1278            continue;
1279        }
1280        if offset > MAX_SAFE_INTEGER || length > MAX_SAFE_INTEGER {
1281            return Err(err("shard index entry exceeds the safe integer range"));
1282        }
1283        if length == 0 {
1284            return Err(err("shard index names an empty chunk"));
1285        }
1286        index.push(Some(ShardIndexEntry { offset, length }));
1287    }
1288    Ok(index)
1289}
1290
1291// -- geometry ------------------------------------------------------------------
1292
1293/// The object holding shard `s` of a variable's array: the default chunk key
1294/// encoding, with the two grid dimensions at chunk 0 because a shard spans the
1295/// whole grid.
1296pub fn shard_path(variable_id: &str, shard: u32) -> String {
1297    format!("{variable_id}/c/{shard}/0/0")
1298}
1299
1300/// Which shard a time chunk lives in, and the position of its first tile in
1301/// that shard's index (row-major over the inner chunk grid).
1302pub fn shard_of(layout: &ArrayLayout, time_chunk: u32) -> (u32, u32) {
1303    let per_shard = layout.shard_frames / layout.time_chunk;
1304    (
1305        time_chunk / per_shard,
1306        (time_chunk % per_shard) * layout.tile_count,
1307    )
1308}
1309
1310impl ArrayLayout {
1311    /// The grid's tiling, the container's arithmetic over the same cells.
1312    /// Built from the parsed fields directly: a store's chunk may exceed a
1313    /// small grid, which `TileGeometry::new` refuses for a container.
1314    pub fn tiles(&self) -> TileGeometry {
1315        TileGeometry {
1316            width: self.width,
1317            height: self.height,
1318            tile_width: self.tile_width,
1319            tile_height: self.tile_height,
1320        }
1321    }
1322}
1323
1324/// The row and column a tile starts at.
1325pub fn tile_origin(layout: &ArrayLayout, tile: u32) -> (u32, u32) {
1326    layout.tiles().origin(tile)
1327}
1328
1329/// A tile's clipped shape: what of it lies inside the grid.
1330pub fn tile_shape(layout: &ArrayLayout, tile: u32) -> (u32, u32) {
1331    layout.tiles().shape(tile)
1332}
1333
1334/// The tile a cell falls in.
1335pub fn tile_of(layout: &ArrayLayout, row: u32, column: u32) -> Result<u32, DecodeError> {
1336    layout.tiles().tile_of(row, column)
1337}
1338
1339/// How many of a time chunk's frames lie on the axis: fewer than the chunk
1340/// shape on the last one, none past it.
1341pub fn frames_in_time_chunk(layout: &ArrayLayout, time_chunk: u32) -> u32 {
1342    let first = u64::from(time_chunk) * u64::from(layout.time_chunk);
1343    u64::from(layout.frame_count)
1344        .saturating_sub(first)
1345        .min(u64::from(layout.time_chunk)) as u32
1346}
1347
1348/// The predictor an inner chunk of this array decodes with.
1349pub fn chunk_predictor(layout: &ArrayLayout) -> Predictor {
1350    if layout.delta {
1351        Predictor::Previous
1352    } else {
1353        Predictor::Raw
1354    }
1355}
1356
1357/// One inner chunk's payload decoded to codes at the full inner shape,
1358/// `time_chunk × tile_height × tile_width`, padding included: the container's
1359/// chunk path, with the Zstandard frame's content checksum required. Codes
1360/// come out as `u16` whatever the array's width, so a series reader reads
1361/// both widths through one path.
1362pub fn decode_inner_chunk(layout: &ArrayLayout, payload: &[u8]) -> Result<Vec<u16>, DecodeError> {
1363    let (frames, height, width, predictor) = (
1364        layout.time_chunk,
1365        layout.tile_height,
1366        layout.tile_width,
1367        chunk_predictor(layout),
1368    );
1369    match layout.data_type {
1370        DataType::U8 => Ok(
1371            crate::decode_chunk(payload, frames, height, width, predictor)?
1372                .into_iter()
1373                .map(u16::from)
1374                .collect(),
1375        ),
1376        DataType::U16 => crate::decode_chunk_u16(payload, frames, height, width, predictor),
1377    }
1378}
1379
1380/// A map frame is a plane of bytes, which only a `uint8` array fills.
1381fn require_map_array(layout: &ArrayLayout) -> Result<(), DecodeError> {
1382    match layout.data_type {
1383        DataType::U8 => Ok(()),
1384        DataType::U16 => Err(err(
1385            "a uint16 array is a series array: read it as a series, not as map frames",
1386        )),
1387    }
1388}
1389
1390/// [`decode_inner_chunk`] for a map frame: the bytes of a `uint8` array's
1391/// chunk, refused on a `uint16` one.
1392pub fn decode_frame_chunk(layout: &ArrayLayout, payload: &[u8]) -> Result<Vec<u8>, DecodeError> {
1393    require_map_array(layout)?;
1394    crate::decode_chunk(
1395        payload,
1396        layout.time_chunk,
1397        layout.tile_height,
1398        layout.tile_width,
1399        chunk_predictor(layout),
1400    )
1401}
1402
1403/// Copy frame `frame_in_chunk` of one decoded inner chunk into a plane of
1404/// `height × width` codes, trimming the padding past the grid's edge. `chunk`
1405/// is `None` for a chunk the shard never held, which is the fill value
1406/// throughout. `chunk` is [`decode_frame_chunk`]'s; a `uint16` array has no
1407/// map frame and is refused.
1408pub fn place_tile(
1409    plane: &mut [u8],
1410    layout: &ArrayLayout,
1411    tile: u32,
1412    chunk: Option<&[u8]>,
1413    frame_in_chunk: u32,
1414) -> Result<(), DecodeError> {
1415    require_map_array(layout)?;
1416    // Bounded by the data type, which the check above holds to uint8.
1417    let fill = layout.fill_value as u8;
1418    let stride = layout.tile_height as usize * layout.tile_width as usize;
1419    if plane.len() != layout.height as usize * layout.width as usize {
1420        return Err(err("plane buffer does not fit the grid"));
1421    }
1422    if tile >= layout.tile_count || frame_in_chunk >= layout.time_chunk {
1423        return Err(err("tile or frame is outside the inner chunk grid"));
1424    }
1425    if chunk.is_some_and(|chunk| chunk.len() != stride * layout.time_chunk as usize) {
1426        return Err(err("decoded chunk does not fit the inner chunk shape"));
1427    }
1428    let (origin_row, origin_column) = tile_origin(layout, tile);
1429    let (rows, columns) = tile_shape(layout, tile);
1430    let columns = columns as usize;
1431    for row in 0..rows as usize {
1432        let target = (origin_row as usize + row) * layout.width as usize + origin_column as usize;
1433        let cells = &mut plane[target..target + columns];
1434        match chunk {
1435            None => cells.fill(fill),
1436            Some(chunk) => {
1437                let source = frame_in_chunk as usize * stride + row * layout.tile_width as usize;
1438                cells.copy_from_slice(&chunk[source..source + columns]);
1439            }
1440        }
1441    }
1442    Ok(())
1443}
1444
1445/// A cell's place in the inner chunk grid: the tile it falls in, and its
1446/// offset within one frame of that tile's decoded chunk.
1447#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1448pub struct TileCell {
1449    pub tile: u32,
1450    pub offset: usize,
1451}
1452
1453/// Where a grid cell sits in its tile's chunks.
1454pub fn tile_cell(layout: &ArrayLayout, row: u32, column: u32) -> Result<TileCell, DecodeError> {
1455    let tile = tile_of(layout, row, column)?;
1456    let (origin_row, origin_column) = tile_origin(layout, tile);
1457    Ok(TileCell {
1458        tile,
1459        offset: (row - origin_row) as usize * layout.tile_width as usize
1460            + (column - origin_column) as usize,
1461    })
1462}
1463
1464impl TileCell {
1465    /// The cell's code on frame `frame_in_chunk` of its tile's decoded chunk
1466    /// ([`decode_inner_chunk`]).
1467    pub fn code(
1468        &self,
1469        layout: &ArrayLayout,
1470        chunk: &[u16],
1471        frame_in_chunk: u32,
1472    ) -> Result<u16, DecodeError> {
1473        let stride = layout.tile_height as usize * layout.tile_width as usize;
1474        if frame_in_chunk >= layout.time_chunk {
1475            return Err(err("frame is outside the time chunk"));
1476        }
1477        chunk
1478            .get(frame_in_chunk as usize * stride + self.offset)
1479            .copied()
1480            .ok_or_else(|| err("decoded chunk does not fit the inner chunk shape"))
1481    }
1482}
1483
1484/// One cell's code on every frame of the axis, in axis order. `chunks` holds
1485/// the payload of the cell's tile ([`tile_cell`]) in each time chunk, in
1486/// order, `None` for a chunk the shard never held, which reads as the fill
1487/// value. Each chunk is decoded and let go: a series touches every one once.
1488/// Codes come out as `u16` for either width.
1489pub fn series_from_chunks<'a>(
1490    layout: &ArrayLayout,
1491    row: u32,
1492    column: u32,
1493    chunks: impl IntoIterator<Item = Option<&'a [u8]>>,
1494) -> Result<Vec<u16>, DecodeError> {
1495    let cell = tile_cell(layout, row, column)?;
1496    // Grown as chunks arrive, never sized from the frame count alone.
1497    let mut series = Vec::new();
1498    let mut time_chunk = 0u32;
1499    for payload in chunks {
1500        if time_chunk >= layout.time_chunks {
1501            return Err(err("a series takes one chunk per time chunk"));
1502        }
1503        let frames = frames_in_time_chunk(layout, time_chunk);
1504        match payload {
1505            None => series.extend(std::iter::repeat_n(layout.fill_value, frames as usize)),
1506            Some(payload) => {
1507                let chunk = decode_inner_chunk(layout, payload)?;
1508                for frame in 0..frames {
1509                    series.push(cell.code(layout, &chunk, frame)?);
1510                }
1511            }
1512        }
1513        time_chunk += 1;
1514    }
1515    if time_chunk != layout.time_chunks {
1516        return Err(err("a series takes one chunk per time chunk"));
1517    }
1518    Ok(series)
1519}
1520
1521// -- time ----------------------------------------------------------------------
1522
1523/// Parse an ISO 8601 instant to milliseconds since the Unix epoch, without a
1524/// date library: the same arithmetic `Date.parse` does for the forms the
1525/// pipeline emits.
1526pub fn parse_iso(text: &str) -> Option<f64> {
1527    let bytes = text.as_bytes();
1528    if bytes.len() < 20 {
1529        return None;
1530    }
1531    let digit = |start: usize, len: usize| -> Option<i64> {
1532        let part = text.get(start..start + len)?;
1533        part.bytes()
1534            .all(|b| b.is_ascii_digit())
1535            .then(|| part.parse().ok())?
1536    };
1537    let year = digit(0, 4)?;
1538    if bytes[4] != b'-' || bytes[7] != b'-' {
1539        return None;
1540    }
1541    let month = digit(5, 2)?;
1542    let day = digit(8, 2)?;
1543    let separator = bytes[10];
1544    if separator != b'T' && separator != b't' && separator != b' ' {
1545        return None;
1546    }
1547    let hour = digit(11, 2)?;
1548    if bytes[13] != b':' {
1549        return None;
1550    }
1551    let minute = digit(14, 2)?;
1552    let mut index = 16;
1553    let mut second = 0i64;
1554    if bytes.get(16) == Some(&b':') {
1555        second = digit(17, 2)?;
1556        index = 19;
1557    }
1558    let mut millis = 0i64;
1559    if bytes.get(index) == Some(&b'.') {
1560        let start = index + 1;
1561        let mut end = start;
1562        while end < bytes.len() && bytes[end].is_ascii_digit() {
1563            end += 1;
1564        }
1565        let digits = &text[start..end];
1566        let scale = 10i64.pow((3 - digits.len().min(3)) as u32);
1567        let value: i64 = digits.get(..digits.len().min(3))?.parse().ok()?;
1568        millis = value * scale;
1569        index = end;
1570    }
1571    // The numeric spelling (`2026-09-25T06:00:00Z`) is what the pipeline
1572    // publishes; the offset forms are accepted too.
1573    let offset_minutes = match bytes.get(index) {
1574        None | Some(b'Z') | Some(b'z') => 0i64,
1575        Some(b'+') | Some(b'-') => {
1576            let sign = if bytes[index] == b'+' { 1 } else { -1 };
1577            let oh = digit(index + 1, 2)?;
1578            if bytes.get(index + 3) != Some(&b':') {
1579                return None;
1580            }
1581            let om = digit(index + 4, 2)?;
1582            sign * (oh * 60 + om)
1583        }
1584        _ => return None,
1585    };
1586    let days = days_from_civil(year, month, day)?;
1587    let seconds = days * 86_400 + hour * 3600 + minute * 60 + second - offset_minutes * 60;
1588    Some((seconds * 1000 + millis) as f64)
1589}
1590
1591/// Days since 1970-01-01 for a proleptic Gregorian date (Howard Hinnant's
1592/// `days_from_civil`).
1593fn days_from_civil(year: i64, month: i64, day: i64) -> Option<i64> {
1594    if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
1595        return None;
1596    }
1597    let year = if month <= 2 { year - 1 } else { year };
1598    let era = if year >= 0 { year } else { year - 399 } / 400;
1599    let year_of_era = year - era * 400;
1600    let day_of_year = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
1601    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
1602    Some(era * 146_097 + day_of_era - 719_468)
1603}
1604
1605/// A run directory under the data root. Accepts the STAC Item id form with a
1606/// 4-digit round (`mrms.2026092509.1455` → `mrms.2026092509/1455`), the run
1607/// directory itself (`mrms.2026092509/1455`), or a plain run id
1608/// (`gfs.2026092506`). `None` is a spelling no run directory may take.
1609pub fn run_directory(run: &str) -> Option<String> {
1610    let valid = !run.is_empty()
1611        && run
1612            .bytes()
1613            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'/' | b'-'));
1614    if !valid {
1615        return None;
1616    }
1617    // No empty or all-dot path segment: `run=../x` is not a run directory, and
1618    // a run never has a `//`.
1619    if run
1620        .split('/')
1621        .any(|segment| segment.is_empty() || segment.bytes().all(|byte| byte == b'.'))
1622    {
1623        return None;
1624    }
1625    if run.contains('/') {
1626        return Some(run.to_owned());
1627    }
1628    let parts: Vec<&str> = run.split('.').collect();
1629    let last = parts.last().copied().unwrap_or_default();
1630    if parts.len() >= 2 && last.len() == 4 && last.bytes().all(|byte| byte.is_ascii_digit()) {
1631        Some(format!("{}/{}", parts[..parts.len() - 1].join("."), last))
1632    } else {
1633        Some(run.to_owned())
1634    }
1635}
1636
1637/// Frame indices to read: all of them, or the one nearest the requested valid
1638/// time. `run_time` settles where offset 0 sits; without it the axis starts at
1639/// the epoch, as the shell's probe does.
1640pub fn frame_indices(
1641    offsets: &[u16],
1642    unit_seconds: u32,
1643    run_time: Option<&str>,
1644    time: Option<&str>,
1645) -> Result<Vec<u32>, DecodeError> {
1646    let Some(time) = time else {
1647        return Ok((0..offsets.len() as u32).collect());
1648    };
1649    let target =
1650        parse_iso(time).ok_or_else(|| err(format!("time must be ISO 8601, got {time}")))?;
1651    let run_ms = run_time.and_then(parse_iso).unwrap_or(0.0);
1652    let unit_ms = f64::from(unit_seconds) * 1000.0;
1653    let mut best = 0usize;
1654    let mut best_distance = f64::INFINITY;
1655    for (index, &offset) in offsets.iter().enumerate() {
1656        let distance = (run_ms + f64::from(offset) * unit_ms - target).abs();
1657        if distance < best_distance {
1658            best_distance = distance;
1659            best = index;
1660        }
1661    }
1662    Ok(vec![best as u32])
1663}
1664
1665/// The ISO 8601 instants of the selected frames.
1666pub fn axis_times(
1667    offsets: &[u16],
1668    unit_seconds: u32,
1669    run_time: Option<&str>,
1670    indices: &[u32],
1671) -> Vec<String> {
1672    let run_ms = run_time.and_then(parse_iso).unwrap_or(0.0);
1673    let unit_ms = f64::from(unit_seconds) * 1000.0;
1674    indices
1675        .iter()
1676        .map(|&index| {
1677            let offset = offsets.get(index as usize).copied().unwrap_or_default();
1678            format_iso_millis(run_ms + f64::from(offset) * unit_ms)
1679        })
1680        .collect()
1681}
1682
1683/// Format milliseconds since the Unix epoch as `YYYY-MM-DDTHH:MM:SS.sssZ`, the
1684/// spelling `Date#toISOString` produces.
1685pub fn format_iso_millis(millis: f64) -> String {
1686    let total = millis.floor() as i64;
1687    let seconds = total.div_euclid(1000);
1688    let millis_part = total.rem_euclid(1000);
1689    let days = seconds.div_euclid(86_400);
1690    let time = seconds.rem_euclid(86_400);
1691    let (year, month, day) = civil_from_days(days);
1692    let (hour, minute, second) = (time / 3600, (time % 3600) / 60, time % 60);
1693    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{millis_part:03}Z")
1694}
1695
1696/// The inverse of [`days_from_civil`].
1697fn civil_from_days(days: i64) -> (i64, i64, i64) {
1698    let days = days + 719_468;
1699    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
1700    let day_of_era = days - era * 146_097;
1701    let year_of_era =
1702        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
1703    let year = year_of_era + era * 400;
1704    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
1705    let mp = (5 * day_of_year + 2) / 153;
1706    let day = day_of_year - (153 * mp + 2) / 5 + 1;
1707    let month = if mp < 10 { mp + 3 } else { mp - 9 };
1708    (if month <= 2 { year + 1 } else { year }, month, day)
1709}
1710
1711#[cfg(test)]
1712mod tests {
1713    use super::*;
1714    use serde_json::json;
1715
1716    fn array_document(overrides: impl FnOnce(&mut Value)) -> String {
1717        let mut document = json!({
1718            "zarr_format": 3,
1719            "node_type": "array",
1720            "shape": [121, 73, 144],
1721            "data_type": "uint8",
1722            "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": [126, 80, 144]}},
1723            "chunk_key_encoding": {"name": "default"},
1724            "fill_value": 255,
1725            "codecs": [{
1726                "name": "sharding_indexed",
1727                "configuration": {
1728                    "chunk_shape": [6, 16, 16],
1729                    "codecs": [{"name": "bytes"}, {"name": "zstd", "configuration": {"level": 15, "checksum": true}}],
1730                    "index_codecs": [{"name": "bytes", "configuration": {"endian": "little"}}, {"name": "crc32c"}],
1731                    "index_location": "end"
1732                }
1733            }],
1734            "attributes": {},
1735            "dimension_names": ["time", "latitude", "longitude"]
1736        });
1737        overrides(&mut document);
1738        serde_json::to_string(&document).unwrap()
1739    }
1740
1741    fn build_index(entries: &[Option<(u64, u64)>]) -> Vec<u8> {
1742        let mut bytes = vec![0u8; shard_index_length(entries.len())];
1743        for (position, entry) in entries.iter().enumerate() {
1744            let (offset, length) = entry.unwrap_or((u64::MAX, u64::MAX));
1745            bytes[position * 16..position * 16 + 8].copy_from_slice(&offset.to_le_bytes());
1746            bytes[position * 16 + 8..position * 16 + 16].copy_from_slice(&length.to_le_bytes());
1747        }
1748        let count = entries.len() * 16;
1749        let checksum = crc32c(&bytes[..count]);
1750        bytes[count..count + 4].copy_from_slice(&checksum.to_le_bytes());
1751        bytes
1752    }
1753
1754    #[test]
1755    fn crc32c_is_castagnoli() {
1756        assert_eq!(crc32c(b"123456789"), 0xe306_9283);
1757        assert_eq!(crc32c(&[]), 0);
1758    }
1759
1760    #[test]
1761    fn reads_the_profile_layout() {
1762        let layout = parse_array_metadata(&array_document(|_| {})).unwrap();
1763        assert_eq!(layout.frame_count, 121);
1764        assert_eq!(layout.height, 73);
1765        assert_eq!(layout.width, 144);
1766        assert_eq!(layout.time_chunk, 6);
1767        assert_eq!(layout.tile_height, 16);
1768        assert_eq!(layout.tile_width, 16);
1769        assert_eq!(layout.tile_rows, 5);
1770        assert_eq!(layout.tile_columns, 9);
1771        assert_eq!(layout.tile_count, 45);
1772        assert_eq!(layout.time_chunks, 21);
1773        assert_eq!(layout.shard_frames, 126);
1774        assert_eq!(layout.shard_count, 1);
1775        assert_eq!(layout.chunks_per_shard, 945);
1776        assert!(!layout.delta);
1777        assert_eq!(layout.index_location, IndexLocation::End);
1778        assert_eq!(layout.fill_value, 255);
1779        assert_eq!(tile_shape(&layout, 44), (9, 16));
1780        assert_eq!(tile_of(&layout, 72, 143).unwrap(), 44);
1781        assert_eq!(shard_of(&layout, 0), (0, 0));
1782        assert_eq!(shard_of(&layout, 20), (0, 900));
1783    }
1784
1785    #[test]
1786    fn reads_a_legacy_shard_per_time_chunk_and_refuses_a_partial_one() {
1787        let legacy = parse_array_metadata(&array_document(|document| {
1788            document["chunk_grid"]["configuration"]["chunk_shape"] = json!([6, 80, 144]);
1789        }))
1790        .unwrap();
1791        assert_eq!(legacy.shard_frames, 6);
1792        assert_eq!(legacy.shard_count, 21);
1793        assert_eq!(legacy.chunks_per_shard, 45);
1794        assert_eq!(shard_of(&legacy, 20), (20, 0));
1795        let two = parse_array_metadata(&array_document(|document| {
1796            document["chunk_grid"]["configuration"]["chunk_shape"] = json!([12, 80, 144]);
1797        }))
1798        .unwrap();
1799        assert_eq!(shard_of(&two, 7), (3, 45));
1800        assert!(parse_array_metadata(&array_document(|document| {
1801            document["chunk_grid"]["configuration"]["chunk_shape"] = json!([9, 80, 144]);
1802        }))
1803        .is_err());
1804    }
1805
1806    #[test]
1807    fn accepts_delta_and_an_index_at_the_start() {
1808        let layout = parse_array_metadata(&array_document(|document| {
1809            document["codecs"][0]["configuration"]["codecs"] =
1810                json!([{"name": "xue.delta", "configuration": {"axis": 0}}, {"name": "bytes"}, {"name": "zstd"}]);
1811            document["codecs"][0]["configuration"]["index_location"] = json!("start");
1812        }))
1813        .unwrap();
1814        assert!(layout.delta);
1815        assert_eq!(layout.index_location, IndexLocation::Start);
1816    }
1817
1818    #[test]
1819    fn rejects_documents_off_the_profile() {
1820        for edit in [
1821            |d: &mut Value| d["data_type"] = json!("float32"),
1822            |d: &mut Value| d["codecs"] = json!([{"name": "bytes"}, {"name": "zstd"}]),
1823            |d: &mut Value| {
1824                d["codecs"][0]["configuration"]["index_codecs"] = json!([{"name": "bytes"}]);
1825            },
1826            |d: &mut Value| d["codecs"][0]["configuration"]["index_location"] = json!("middle"),
1827            |d: &mut Value| d["chunk_grid"]["configuration"]["chunk_shape"] = json!([126, 73, 144]),
1828        ] {
1829            assert!(parse_array_metadata(&array_document(edit)).is_err());
1830        }
1831    }
1832
1833    #[test]
1834    fn rejects_configuration_that_is_present_and_wrong() {
1835        for edit in [
1836            |d: &mut Value| d["chunk_key_encoding"]["configuration"] = json!(null),
1837            |d: &mut Value| d["chunk_key_encoding"]["configuration"] = json!({"separator": "."}),
1838            |d: &mut Value| d["chunk_key_encoding"]["configuration"] = json!({"separator": 5}),
1839            |d: &mut Value| {
1840                d["codecs"][0]["configuration"]["index_codecs"][0]["configuration"] = json!({})
1841            },
1842            |d: &mut Value| {
1843                d["codecs"][0]["configuration"]["index_codecs"][0]["configuration"] =
1844                    json!({"endian": "big"});
1845            },
1846            |d: &mut Value| {
1847                d["codecs"][0]["configuration"]["index_codecs"][0]["configuration"] = json!(7)
1848            },
1849            |d: &mut Value| d["codecs"][0]["configuration"]["index_location"] = json!(5),
1850            |d: &mut Value| d["codecs"][0]["configuration"]["index_location"] = json!(true),
1851        ] {
1852            let text = array_document(edit);
1853            assert!(parse_array_metadata(&text).is_err(), "{text} was accepted");
1854        }
1855        // Absent, the same fields take the codec's defaults.
1856        for edit in [
1857            |d: &mut Value| d["chunk_key_encoding"]["configuration"] = json!({}),
1858            |d: &mut Value| d["chunk_key_encoding"]["configuration"] = json!({"separator": "/"}),
1859            |d: &mut Value| {
1860                d["codecs"][0]["configuration"]["index_codecs"] =
1861                    json!([{"name": "bytes"}, {"name": "crc32c"}])
1862            },
1863            |d: &mut Value| d["codecs"][0]["configuration"]["index_location"] = json!(null),
1864            |d: &mut Value| {
1865                d["codecs"][0]["configuration"]
1866                    .as_object_mut()
1867                    .unwrap()
1868                    .remove("index_location");
1869            },
1870        ] {
1871            let layout = parse_array_metadata(&array_document(edit)).unwrap();
1872            assert_eq!(layout.index_location, IndexLocation::End);
1873        }
1874    }
1875
1876    #[test]
1877    fn refuses_shapes_past_what_a_reader_may_allocate() {
1878        const BIG: u64 = 1 << 32;
1879        for edit in [
1880            // A height that would read as 720 once cut to 32 bits.
1881            |d: &mut Value| {
1882                d["shape"] = json!([121, BIG + 720, 144]);
1883                d["chunk_grid"]["configuration"]["chunk_shape"] = json!([126, 720, 144]);
1884                d["codecs"][0]["configuration"]["chunk_shape"] = json!([6, 720, 16]);
1885            },
1886            // A tile height that would read as zero.
1887            |d: &mut Value| d["codecs"][0]["configuration"]["chunk_shape"] = json!([6, BIG, 16]),
1888            |d: &mut Value| d["codecs"][0]["configuration"]["chunk_shape"] = json!([BIG, 16, 16]),
1889            |d: &mut Value| d["shape"] = json!([BIG, 73, 144]),
1890            // More cells than a decoded plane may hold.
1891            |d: &mut Value| {
1892                d["shape"] = json!([121, 16_000, 16_000]);
1893                d["chunk_grid"]["configuration"]["chunk_shape"] = json!([126, 16_000, 16_000]);
1894            },
1895            // A shard whose index alone passes the limit.
1896            |d: &mut Value| {
1897                d["shape"] = json!([121, 8_000, 8_000]);
1898                d["chunk_grid"]["configuration"]["chunk_shape"] = json!([126, 8_000, 8_000]);
1899                d["codecs"][0]["configuration"]["chunk_shape"] = json!([6, 1, 1]);
1900            },
1901        ] {
1902            let text = array_document(edit);
1903            assert!(parse_array_metadata(&text).is_err(), "{text} was accepted");
1904        }
1905    }
1906
1907    /// A series store's widened variable: uint16, little-endian bytes, its
1908    /// codebook's no-data code as the fill.
1909    fn uint16_document(edit: impl FnOnce(&mut Value)) -> String {
1910        array_document(|d| {
1911            d["data_type"] = json!("uint16");
1912            d["fill_value"] = json!(65_535);
1913            d["codecs"][0]["configuration"]["codecs"] = json!([
1914                {"name": "xue.delta", "configuration": {"axis": 0}},
1915                {"name": "bytes", "configuration": {"endian": "little"}},
1916                {"name": "zstd", "configuration": {"level": 15, "checksum": true}}
1917            ]);
1918            d["attributes"] = json!({"xue": {"variable": {"numericId": 1, "id": "tmp2m",
1919                "quantization": {"type": "linear", "offset": -90.0, "scale": 0.1,
1920                    "minimumCode": 0, "maximumCode": 1500, "nodataCode": 65_535}}}});
1921            edit(d);
1922        })
1923    }
1924
1925    #[test]
1926    fn reads_a_uint16_array() {
1927        let layout = parse_array_metadata(&uint16_document(|_| {})).unwrap();
1928        assert_eq!(layout.data_type, DataType::U16);
1929        assert_eq!(layout.fill_value, 65_535);
1930        assert!(layout.delta);
1931        let narrow = parse_array_metadata(&array_document(|_| {})).unwrap();
1932        assert_eq!(narrow.data_type, DataType::U8);
1933        // A chunk the shard never held is the 16-bit fill on every frame.
1934        let series =
1935            series_from_chunks(&layout, 0, 0, (0..layout.time_chunks).map(|_| None)).unwrap();
1936        assert_eq!(series, vec![65_535; layout.frame_count as usize]);
1937        // A uint16 chunk decodes as one, the delta replayed modulo 65536.
1938        // The first frame is no-data, so the second frame's residuals wrap
1939        // past 65535 to its codes.
1940        let codes: Vec<u16> = (0..6 * 16 * 16)
1941            .map(|i| if i < 256 { 65_535 } else { (i % 1501) as u16 })
1942            .collect();
1943        let mut residuals = codes.clone();
1944        for i in 256..codes.len() {
1945            residuals[i] = codes[i].wrapping_sub(codes[i - 256]);
1946        }
1947        let bytes: Vec<u8> = residuals
1948            .iter()
1949            .flat_map(|code| code.to_le_bytes())
1950            .collect();
1951        let payload = ruzstd::encoding::compress_to_vec(
1952            &bytes[..],
1953            ruzstd::encoding::CompressionLevel::Fastest,
1954        );
1955        let chunk = decode_inner_chunk(&layout, &payload).unwrap();
1956        assert_eq!(chunk, codes);
1957        let cell = tile_cell(&layout, 0, 3).unwrap();
1958        assert_eq!(cell.code(&layout, &chunk, 1).unwrap(), 259);
1959        // It has no map frame.
1960        assert!(decode_frame_chunk(&layout, &payload).is_err());
1961        let mut plane = vec![0u8; 73 * 144];
1962        assert!(place_tile(&mut plane, &layout, 0, None, 0).is_err());
1963    }
1964
1965    #[test]
1966    fn rejects_uint16_arrays_off_the_profile() {
1967        for edit in [
1968            |d: &mut Value| d["fill_value"] = json!(255),
1969            |d: &mut Value| d["fill_value"] = json!(65_536),
1970            |d: &mut Value| {
1971                d["attributes"]["xue"]["variable"]["quantization"]["nodataCode"] = json!(65_536)
1972            },
1973            |d: &mut Value| {
1974                d["attributes"]["xue"]["variable"]["quantization"]["minimumCode"] = json!(0.5)
1975            },
1976            |d: &mut Value| {
1977                d["codecs"][0]["configuration"]["codecs"][1]["configuration"] =
1978                    json!({"endian": "big"})
1979            },
1980            |d: &mut Value| d["codecs"][0]["configuration"]["codecs"][1] = json!({"name": "bytes"}),
1981            |d: &mut Value| d["attributes"] = json!({}),
1982            |d: &mut Value| d["data_type"] = json!("int16"),
1983        ] {
1984            let text = uint16_document(edit);
1985            assert!(parse_array_metadata(&text).is_err(), "{text} was accepted");
1986        }
1987        // The network and column branches stay uint8.
1988        let value: Value = serde_json::from_str(&uint16_document(|_| {})).unwrap();
1989        assert!(sharded_array(value, 3).is_err());
1990        // A uint8 array's codebook must fit a byte.
1991        let wide = array_document(|d| {
1992            d["attributes"] = json!({"xue": {"variable": {"quantization": {"type": "linear",
1993                "offset": 0.0, "scale": 1.0, "minimumCode": 0, "maximumCode": 1500, "nodataCode": 255}}}});
1994        });
1995        assert!(parse_array_metadata(&wide).is_err());
1996        let big = array_document(|d| {
1997            d["codecs"][0]["configuration"]["codecs"][0] =
1998                json!({"name": "bytes", "configuration": {"endian": "big"}});
1999        });
2000        assert!(parse_array_metadata(&big).is_err());
2001    }
2002
2003    #[test]
2004    fn an_array_names_its_bundle_or_none() {
2005        assert_eq!(
2006            parse_array_document(&array_document(|_| {}))
2007                .unwrap()
2008                .bundle,
2009            None
2010        );
2011        let named = array_document(|d| {
2012            d["attributes"] = json!({"xue": {"bundle": "tmp2m", "predictor": "raw"}})
2013        });
2014        assert_eq!(
2015            parse_array_document(&named).unwrap().bundle.as_deref(),
2016            Some("tmp2m")
2017        );
2018        let unnamed = array_document(|d| d["attributes"] = json!({"xue": {"predictor": "raw"}}));
2019        assert_eq!(parse_array_document(&unnamed).unwrap().bundle, None);
2020        let absent = array_document(|d| {
2021            d.as_object_mut().unwrap().remove("attributes");
2022        });
2023        assert_eq!(parse_array_document(&absent).unwrap().bundle, None);
2024        for bundle in [json!(7), json!(""), json!(null)] {
2025            let text = array_document(|d| d["attributes"] = json!({"xue": {"bundle": bundle}}));
2026            assert!(parse_array_document(&text).is_err(), "{text} was accepted");
2027        }
2028    }
2029
2030    #[test]
2031    fn a_group_gives_one_bundle_block_without_reading_it() {
2032        // Not a valid bundle metadata document: this entry point leaves the
2033        // block to the caller's validator.
2034        let single = json!({"zarr_format": 3, "node_type": "group",
2035            "attributes": {"xue_profile": 1, "xue": {"anything": [1, 2.5]}}})
2036        .to_string();
2037        assert_eq!(
2038            group_metadata_json(&single, None).unwrap(),
2039            (PROFILE_SINGLE, r#"{"anything":[1,2.5]}"#.to_owned())
2040        );
2041        assert_eq!(
2042            group_metadata_json(&single, Some("whichever")).unwrap(),
2043            group_metadata_json(&single, None).unwrap()
2044        );
2045        let shared = json!({"zarr_format": 3, "node_type": "group",
2046            "attributes": {"xue_profile": 2, "xue_bundles": {"tmp2m": {"a": 1}, "prate": {"a": 2}, "gust": 3}}})
2047        .to_string();
2048        assert_eq!(
2049            group_metadata_json(&shared, Some("prate")).unwrap(),
2050            (PROFILE_SHARED, r#"{"a":2}"#.to_owned())
2051        );
2052        assert!(group_metadata_json(&shared, None).is_err());
2053        assert!(group_metadata_json(&shared, Some("tmp")).is_err());
2054        assert!(group_metadata_json(&shared, Some("gust")).is_err());
2055        assert!(group_metadata_json(&shared, Some("constructor")).is_err());
2056    }
2057
2058    #[test]
2059    fn a_reader_places_chunks_through_the_indices_it_was_given() {
2060        // Two shards of one time chunk each would not hold 121 frames; cut the
2061        // axis to twelve so the array is two shards of 45 tiles.
2062        let layout = parse_array_metadata(&array_document(|d| {
2063            d["shape"] = json!([12, 73, 144]);
2064            d["chunk_grid"]["configuration"]["chunk_shape"] = json!([6, 80, 144]);
2065        }))
2066        .unwrap();
2067        assert_eq!((layout.shard_count, layout.chunks_per_shard), (2, 45));
2068        let mut reader = ArrayReader::new(layout);
2069        assert_eq!(reader.shard_of(0).unwrap(), 0);
2070        assert_eq!(reader.shard_of(1).unwrap(), 1);
2071        assert!(reader.shard_of(2).is_err());
2072
2073        // Nothing is answered about a shard whose index was never handed over.
2074        assert!(!reader.has_shard_index(1));
2075        assert!(reader.chunk_range(1, 0).is_err());
2076
2077        let mut entries = vec![None; 45];
2078        entries[0] = Some((0, 40));
2079        entries[44] = Some((40, 7));
2080        let index = build_index(&entries);
2081        assert!(reader.set_shard_index(2, &index).is_err());
2082        let mut corrupt = index.clone();
2083        corrupt[3] ^= 1;
2084        assert!(reader.set_shard_index(1, &corrupt).is_err());
2085        assert!(reader
2086            .set_shard_index(1, &index[..index.len() - 16])
2087            .is_err());
2088        assert!(!reader.has_shard_index(1));
2089
2090        reader.set_shard_index(1, &index).unwrap();
2091        assert!(reader.has_shard_index(1));
2092        assert!(!reader.has_shard_index(0));
2093        assert_eq!(
2094            reader.chunk_range(1, 0).unwrap(),
2095            Some(ShardIndexEntry {
2096                offset: 0,
2097                length: 40
2098            })
2099        );
2100        assert_eq!(reader.chunk_range(1, 1).unwrap(), None);
2101        assert_eq!(
2102            reader.chunk_range(1, 44).unwrap(),
2103            Some(ShardIndexEntry {
2104                offset: 40,
2105                length: 7
2106            })
2107        );
2108        assert!(reader.chunk_range(1, 45).is_err());
2109        assert!(reader.chunk_range(0, 0).is_err());
2110    }
2111
2112    #[test]
2113    fn reads_the_shard_index_and_verifies_its_checksum() {
2114        let entries = [Some((0, 40)), None, Some((40, 7))];
2115        let parsed = parse_shard_index(&build_index(&entries), 3).unwrap();
2116        assert_eq!(
2117            parsed[0],
2118            Some(ShardIndexEntry {
2119                offset: 0,
2120                length: 40
2121            })
2122        );
2123        assert_eq!(parsed[1], None);
2124        assert_eq!(
2125            parsed[2],
2126            Some(ShardIndexEntry {
2127                offset: 40,
2128                length: 7
2129            })
2130        );
2131
2132        let mut corrupt = build_index(&entries);
2133        corrupt[3] ^= 1;
2134        assert!(parse_shard_index(&corrupt, 3).is_err());
2135        assert!(parse_shard_index(&build_index(&entries)[1..], 3).is_err());
2136        assert!(parse_shard_index(&build_index(&[Some((0, 0))]), 1).is_err());
2137    }
2138
2139    #[test]
2140    fn probes_cells_as_the_shell_does() {
2141        let grid = Grid::Regular(RegularGrid {
2142            width: 1440,
2143            height: 721,
2144            first_longitude: -180.0,
2145            first_latitude: 90.0,
2146            longitude_step: 0.25,
2147            latitude_step: -0.25,
2148            wraps: true,
2149            gaussian: None,
2150        });
2151        let cell = probe_cell(&grid, 139.7, 35.7).unwrap();
2152        assert_eq!(cell.column, 1279);
2153        assert_eq!(cell.row, 217);
2154        assert!((cell.longitude - 139.75).abs() < 1e-9);
2155        assert!((cell.latitude - 35.75).abs() < 1e-9);
2156        assert!(probe_cell(&grid, -180.1, 0.0).is_some());
2157
2158        let addressed = grid_cell(&grid, 1279, 217).unwrap();
2159        assert_eq!(addressed, cell);
2160        assert_eq!(
2161            probe_cell(&grid, addressed.longitude, addressed.latitude),
2162            Some(addressed)
2163        );
2164        assert!(grid_cell(&grid, 1440, 0).is_none());
2165        assert!(grid_cell(&grid, 0, 721).is_none());
2166    }
2167
2168    fn hrrr() -> Grid {
2169        Grid::Lambert(LambertGrid {
2170            width: 1799,
2171            height: 1059,
2172            projection: LambertConformal {
2173                radius: 6371229.0,
2174                standard_parallel_1: 38.5,
2175                standard_parallel_2: 38.5,
2176                latitude_of_origin: 38.5,
2177                central_meridian: -97.5,
2178            },
2179            x0: -2697520.143,
2180            y0: 1586693.847,
2181            dx: 3000.0,
2182            dy: -3000.0,
2183        })
2184    }
2185
2186    #[test]
2187    fn probes_a_lambert_grid_through_the_projection() {
2188        let grid = hrrr();
2189        for (column, row) in [
2190            (0, 0),
2191            (1798, 0),
2192            (0, 1058),
2193            (1798, 1058),
2194            (899, 529),
2195            (1200, 300),
2196        ] {
2197            let cell = grid_cell(&grid, column, row).unwrap();
2198            assert_eq!((cell.column, cell.row), (column, row));
2199            assert_eq!(probe_cell(&grid, cell.longitude, cell.latitude), Some(cell));
2200        }
2201        // Denver is well inside, whichever way its longitude is spelled.
2202        let denver = probe_cell(&grid, -104.99, 39.74).unwrap();
2203        assert!((denver.longitude + 104.99).abs() < 0.03);
2204        assert!((denver.latitude - 39.74).abs() < 0.03);
2205        assert_eq!(probe_cell(&grid, 255.01, 39.74), Some(denver));
2206        // The corner of the old rectangle the cone never covered, the other
2207        // side of the world, both poles and a latitude that is none.
2208        for (longitude, latitude) in [
2209            (-134.0, 21.2),
2210            (139.7, 35.7),
2211            (0.0, 90.0),
2212            (0.0, -90.0),
2213            (-97.5, 91.0),
2214        ] {
2215            assert_eq!(
2216                probe_cell(&grid, longitude, latitude),
2217                None,
2218                "{longitude} {latitude}"
2219            );
2220        }
2221        assert!(grid_cell(&grid, 1799, 0).is_none());
2222        assert!(grid_cell(&grid, 0, 1059).is_none());
2223    }
2224
2225    /// A crop of the n = 95 grid, its regular fields the equidistant ones GDAL
2226    /// reports: the true end rows and an even step between them.
2227    fn gaussian_grid(first_row: u32, row_stride: u32, height: u32) -> Grid {
2228        let first = crate::projection::gaussian_latitude(95, 0);
2229        let step = -2.0 * first / 189.0;
2230        Grid::Regular(RegularGrid {
2231            width: 384,
2232            height,
2233            first_longitude: 0.0,
2234            first_latitude: first + f64::from(first_row) * step,
2235            longitude_step: 0.9375,
2236            latitude_step: step * f64::from(row_stride),
2237            wraps: true,
2238            gaussian: Some(GaussianRows {
2239                n: 95,
2240                first_row,
2241                row_stride,
2242            }),
2243        })
2244    }
2245
2246    #[test]
2247    fn a_gaussian_grid_reports_and_selects_true_latitudes() {
2248        let grid = gaussian_grid(0, 1, 190);
2249        let Grid::Regular(regular) = grid else {
2250            unreachable!()
2251        };
2252        let cell = grid_cell(&grid, 0, 47).unwrap();
2253        assert_eq!(cell.latitude, crate::projection::gaussian_latitude(95, 47));
2254        assert_ne!(
2255            cell.latitude,
2256            regular.first_latitude + 47.0 * regular.latitude_step
2257        );
2258        for row in [0, 1, 94, 95, 188, 189] {
2259            let cell = grid_cell(&grid, 7, row).unwrap();
2260            assert_eq!(probe_cell(&grid, cell.longitude, cell.latitude), Some(cell));
2261        }
2262        // The outer rows own the polar caps.
2263        assert_eq!(probe_cell(&grid, 10.0, 90.0).unwrap().row, 0);
2264        assert_eq!(probe_cell(&grid, 10.0, -90.0).unwrap().row, 189);
2265        assert_eq!(probe_cell(&grid, 10.0, 90.5), None);
2266    }
2267
2268    #[test]
2269    fn a_cropped_gaussian_grid_stops_half_a_row_past_its_edge() {
2270        let grid = gaussian_grid(10, 2, 20);
2271        let first = grid_cell(&grid, 0, 0).unwrap();
2272        assert_eq!(first.latitude, crate::projection::gaussian_latitude(95, 10));
2273        let last = grid_cell(&grid, 0, 19).unwrap();
2274        assert_eq!(last.latitude, crate::projection::gaussian_latitude(95, 48));
2275        assert_eq!(probe_cell(&grid, 0.0, first.latitude + 0.9).unwrap().row, 0);
2276        assert_eq!(probe_cell(&grid, 0.0, first.latitude + 1.0), None);
2277        assert_eq!(probe_cell(&grid, 0.0, last.latitude - 0.9).unwrap().row, 19);
2278        assert_eq!(probe_cell(&grid, 0.0, last.latitude - 1.0), None);
2279        assert_eq!(probe_cell(&grid, 0.0, 89.0), None);
2280    }
2281
2282    #[test]
2283    fn a_grid_is_read_from_its_metadata() {
2284        let projected: Value = serde_json::from_str(
2285            r#"{"grid": {"width": 1799, "height": 1059, "wrapLongitude": false, "projection": {
2286                "kind": "lambert-conformal", "radius": 6371229.0,
2287                "standardParallel1": 38.5, "standardParallel2": 38.5,
2288                "latitudeOfOrigin": 38.5, "centralMeridian": -97.5,
2289                "x0": -2697520.143, "y0": 1586693.847, "dx": 3000.0, "dy": -3000.0}}}"#,
2290        )
2291        .unwrap();
2292        assert_eq!(Grid::from_metadata(&projected).unwrap(), hrrr());
2293
2294        let mut incomplete = projected.clone();
2295        incomplete["grid"]["projection"]
2296            .as_object_mut()
2297            .unwrap()
2298            .remove("x0");
2299        assert!(Grid::from_metadata(&incomplete).is_err());
2300
2301        let older: Value =
2302            serde_json::from_str(r#"{"grid": {"width": 1440, "height": 721}}"#).unwrap();
2303        let Grid::Regular(regular) = Grid::from_metadata(&older).unwrap() else {
2304            panic!("a grid without a projection is regular");
2305        };
2306        assert_eq!(
2307            (regular.first_longitude, regular.latitude_step),
2308            (-180.0, -0.25)
2309        );
2310        assert!(regular.wraps);
2311        assert_eq!(regular.gaussian, None);
2312    }
2313
2314    #[test]
2315    fn a_v4_group_opens_and_a_v3_labelled_one_does_not() {
2316        let metadata = |version: u64| -> String {
2317            format!(
2318                r#"{{"zarr_format": 3, "node_type": "group", "attributes": {{"xue_profile": 1, "xue": {{
2319                    "schemaVersion": {version}, "runTime": "2026-11-05T00:00:00Z",
2320                    "time": {{"unitSeconds": 3600, "firstFrameOffset": 0, "frameStep": 1, "frameCount": 2}},
2321                    "grid": {{"width": 1799, "height": 1059, "wrapLongitude": false, "projection": {{
2322                        "kind": "lambert-conformal", "radius": 6371229.0,
2323                        "standardParallel1": 38.5, "standardParallel2": 38.5,
2324                        "latitudeOfOrigin": 38.5, "centralMeridian": -97.5,
2325                        "x0": -2697520.143, "y0": 1586693.847, "dx": 3000.0, "dy": -3000.0}}}},
2326                    "variables": [{{"numericId": 1, "id": "tmp2m", "label": "t", "unit": "C",
2327                        "parameter": {{"discipline": 0, "parameterCategory": 0, "parameterNumber": 0,
2328                            "typeOfFirstFixedSurface": 103, "scaleFactorOfFirstFixedSurface": 0,
2329                            "scaledValueOfFirstFixedSurface": 2}},
2330                        "quantization": {{"type": "linear", "offset": -60.0, "scale": 0.5,
2331                            "minimumCode": 0, "maximumCode": 220, "nodataCode": 255}}}}]
2332                }}}}}}"#
2333            )
2334        };
2335        let group = parse_group_metadata(&metadata(4)).unwrap();
2336        assert_eq!(group.metadata.schema_version, 4);
2337        assert_eq!(group.metadata.grid, hrrr());
2338        assert_eq!(group.metadata.grid.width(), 1799);
2339        assert!(parse_group_metadata(&metadata(3)).is_err());
2340    }
2341
2342    #[test]
2343    fn decodes_linear_and_log_codebooks() {
2344        let linear = Quantization::Linear {
2345            offset: -60.0,
2346            scale: 0.5,
2347            minimum_code: 0.0,
2348            maximum_code: 220.0,
2349            nodata_code: 255.0,
2350        };
2351        assert_eq!(decode_value(&linear, 163), Some(21.5));
2352        assert_eq!(decode_value(&linear, 255), None);
2353        assert_eq!(decode_value(&linear, 221), None);
2354
2355        let log = Quantization::Log1p {
2356            trace: 0.01,
2357            scale: 0.05,
2358            maximum: 128.0,
2359            minimum_code: 1.0,
2360            maximum_code: 253.0,
2361            zero_code: 0.0,
2362            overflow_code: 254.0,
2363            nodata_code: 255.0,
2364        };
2365        assert_eq!(decode_value(&log, 0), Some(0.0));
2366        assert_eq!(decode_value(&log, 255), None);
2367        // 254 is the overflow code the profile defines, not a missing one.
2368        assert!(decode_value(&log, 254).is_some());
2369        assert!(decode_value(&log, 1).unwrap() < decode_value(&log, 253).unwrap());
2370    }
2371
2372    #[test]
2373    fn run_directories_take_every_spelling() {
2374        assert_eq!(
2375            run_directory("gfs.2026092506").as_deref(),
2376            Some("gfs.2026092506")
2377        );
2378        assert_eq!(
2379            run_directory("mrms.2026092509.1455").as_deref(),
2380            Some("mrms.2026092509/1455")
2381        );
2382        assert_eq!(
2383            run_directory("mrms.2026092509/1455").as_deref(),
2384            Some("mrms.2026092509/1455")
2385        );
2386        assert_eq!(run_directory("../etc/passwd"), None);
2387        assert_eq!(run_directory(""), None);
2388    }
2389
2390    #[test]
2391    fn frame_selection_picks_the_nearest_instant() {
2392        let offsets = [0u16, 6, 12, 18];
2393        assert_eq!(
2394            frame_indices(&offsets, 3600, Some("2026-09-25T00:00:00Z"), None).unwrap(),
2395            vec![0, 1, 2, 3]
2396        );
2397        assert_eq!(
2398            frame_indices(
2399                &offsets,
2400                3600,
2401                Some("2026-09-25T00:00:00Z"),
2402                Some("2026-09-25T07:00:00Z")
2403            )
2404            .unwrap(),
2405            vec![1]
2406        );
2407        assert!(frame_indices(&offsets, 3600, None, Some("not-a-time")).is_err());
2408    }
2409
2410    #[test]
2411    fn axis_times_are_iso_instants() {
2412        assert_eq!(
2413            axis_times(&[0, 6], 3600, Some("2026-09-25T00:00:00Z"), &[0, 1]),
2414            vec!["2026-09-25T00:00:00.000Z", "2026-09-25T06:00:00.000Z"]
2415        );
2416    }
2417
2418    #[test]
2419    fn formats_and_parses_iso_instants() {
2420        assert_eq!(parse_iso("2026-09-25T06:00:00Z"), Some(1_790_316_000_000.0));
2421        assert_eq!(
2422            parse_iso("2026-09-25T06:00:00.000Z"),
2423            Some(1_790_316_000_000.0)
2424        );
2425        assert_eq!(
2426            format_iso_millis(1_790_316_000_000.0),
2427            "2026-09-25T06:00:00.000Z"
2428        );
2429        assert_eq!(format_iso_millis(0.0), "1970-01-01T00:00:00.000Z");
2430    }
2431}
2432
2433#[cfg(test)]
2434mod schema_tie_tests {
2435    //! The group and array fields this reader reads, and the metadata fields
2436    //! it reads beside the decoder's own validation, are the ones
2437    //! `docs/schemas/` names: `store-group`, `polar-group`, `network-group`,
2438    //! `column-group`, `store-array` and `bundle-metadata`.
2439    use super::{StoreKind, BRANCH_BLOCKS};
2440    use crate::schematie::assert_named;
2441
2442    #[test]
2443    fn every_branch_block_is_named_by_its_schema() {
2444        for (block, kind) in BRANCH_BLOCKS {
2445            let (schema, pointer) = match kind {
2446                StoreKind::Grid => ("store-group", "/$defs/Attributes"),
2447                StoreKind::Polar => ("polar-group", "/properties/attributes"),
2448                StoreKind::Network => ("network-group", "/properties/attributes"),
2449                StoreKind::Column => ("column-group", "/properties/attributes"),
2450            };
2451            assert_named(schema, pointer, &[block]);
2452        }
2453        assert_named("store-group", "/$defs/Attributes", &["xue_profile"]);
2454        for schema in [
2455            "store-group",
2456            "polar-group",
2457            "network-group",
2458            "column-group",
2459        ] {
2460            assert_named(schema, "", &["zarr_format", "node_type", "attributes"]);
2461        }
2462    }
2463
2464    #[test]
2465    fn the_array_fields_read_are_the_schemas() {
2466        assert_named(
2467            "store-array",
2468            "",
2469            &[
2470                "zarr_format",
2471                "node_type",
2472                "data_type",
2473                "shape",
2474                "chunk_grid",
2475                "chunk_key_encoding",
2476                "fill_value",
2477                "codecs",
2478                "dimension_names",
2479                "attributes",
2480            ],
2481        );
2482        assert_named(
2483            "store-array",
2484            "/properties/chunk_grid",
2485            &["name", "configuration"],
2486        );
2487        assert_named(
2488            "store-array",
2489            "/properties/chunk_grid/properties/configuration",
2490            &["chunk_shape"],
2491        );
2492        assert_named(
2493            "store-array",
2494            "/properties/chunk_key_encoding",
2495            &["name", "configuration"],
2496        );
2497        assert_named(
2498            "store-array",
2499            "/properties/chunk_key_encoding/properties/configuration",
2500            &["separator"],
2501        );
2502        assert_named("store-array", "/$defs/Codec", &["name", "configuration"]);
2503        assert_named("store-array", "/$defs/Attributes", &["xue", "xue_network"]);
2504        assert_named("store-array", "/$defs/NetworkArrayBlock", &["variable"]);
2505        assert_named(
2506            "store-array",
2507            "/$defs/GridArrayBlock",
2508            &["bundle", "variable"],
2509        );
2510    }
2511
2512    #[test]
2513    fn the_metadata_fields_read_are_the_schemas() {
2514        assert_named("bundle-metadata", "", &["runTime", "variables", "grid"]);
2515        assert_named(
2516            "bundle-metadata",
2517            "/$defs/Grid",
2518            &[
2519                "width",
2520                "height",
2521                "firstLongitude",
2522                "firstLatitude",
2523                "longitudeStep",
2524                "latitudeStep",
2525                "wrapLongitude",
2526                "projection",
2527                "gaussian",
2528            ],
2529        );
2530        assert_named(
2531            "bundle-metadata",
2532            "/$defs/Variable",
2533            &["numericId", "id", "label", "unit", "quantization"],
2534        );
2535        assert_named(
2536            "bundle-metadata",
2537            "/$defs/LinearQuantization",
2538            &[
2539                "type",
2540                "offset",
2541                "scale",
2542                "minimumCode",
2543                "maximumCode",
2544                "nodataCode",
2545            ],
2546        );
2547        assert_named(
2548            "bundle-metadata",
2549            "/$defs/LogQuantization",
2550            &[
2551                "type",
2552                "trace",
2553                "scale",
2554                "maximum",
2555                "minimumCode",
2556                "maximumCode",
2557                "zeroCode",
2558                "overflowCode",
2559                "nodataCode",
2560            ],
2561        );
2562    }
2563
2564    #[test]
2565    fn the_network_block_read_is_the_schemas() {
2566        assert_named("network-group", "", &["consolidated_metadata"]);
2567        assert_named("store-group", "/$defs/ConsolidatedMetadata", &["metadata"]);
2568        assert_named(
2569            "network-group",
2570            "/$defs/Network",
2571            &[
2572                "version",
2573                "model",
2574                "product",
2575                "runTime",
2576                "time",
2577                "geometry",
2578                "variables",
2579            ],
2580        );
2581        assert_named(
2582            "network-group",
2583            "/$defs/Geometry",
2584            &[
2585                "path",
2586                "byteLength",
2587                "crc32",
2588                "featureCount",
2589                "rowGroupRows",
2590            ],
2591        );
2592        assert_named(
2593            "store-array",
2594            "/$defs/NetworkVariable",
2595            &["numericId", "id", "label", "unit", "quantization"],
2596        );
2597        assert_named(
2598            "bundle-metadata",
2599            "/$defs/Time",
2600            &[
2601                "unitSeconds",
2602                "firstFrameOffset",
2603                "frameCount",
2604                "frameStep",
2605                "frameOffsets",
2606            ],
2607        );
2608    }
2609}