Skip to main content

lib_jsl_file_io/
hdf5.rs

1//! A reader for HDF5 files (the format under MATLAB v7.3 `.mat` files and NetCDF-4 `.nc` files):
2//! groups, datasets, attributes and their data, without the HDF5 library.
3//!
4//! Supported: superblock versions 0 to 3 (and a user block, as MATLAB writes); object headers of
5//! version 1 and 2 with continuation blocks; groups by symbol table (version 1 B-tree and local
6//! heap) or by link messages; datasets with compact, contiguous or chunked storage (the version 1
7//! B-tree chunk index and the single-chunk, implicit, fixed-array, extensible-array and version 2
8//! B-tree indexes of layout versions 4 and 5) and the deflate, shuffle, Fletcher-32 and LZF filters;
9//! fixed-point, floating-point, string, bitfield, enumeration, compound, array, reference and
10//! variable-length datatypes (also those committed to the file); fill values; attributes in the object
11//! header, and dense link and attribute storage (a fractal heap indexed by a version 2 B-tree, which
12//! groups of the newest format switch to beyond eight links or attributes). Not supported (reported as
13//! errors): external and virtual storage, the shared message heap, the other filters, and writing.
14//!
15//! See the book entry [Scientific data files](https://jwkunz.github.io/lib_jsl/book/foundations/scientific-files.html#hdf5-files).
16
17use crate::deflate::zlib_decompress;
18use lib_jsl_core::ErrorsJSL;
19use std::collections::{HashMap, HashSet};
20use std::path::Path;
21
22fn bad(msg: &'static str) -> ErrorsJSL {
23    ErrorsJSL::InvalidInputRange(msg)
24}
25
26/// The value of an element of an HDF5 datatype.
27#[derive(Clone, Debug, PartialEq)]
28#[non_exhaustive]
29pub enum H5Value {
30    Int(i64),
31    UInt(u64),
32    Float(f64),
33    Str(String),
34    /// A reference to an object, by the address of its header (see [`Hdf5File::object_at`]).
35    Reference(u64),
36    /// A compound value: its members in order.
37    Compound(Vec<(String, H5Value)>),
38    /// An enumeration value: its integer and, when known, its name.
39    Enum(i64, Option<String>),
40    /// A variable-length sequence (not of characters).
41    Sequence(Vec<H5Value>),
42}
43
44/// The class of an HDF5 datatype, with what is needed to decode its elements.
45#[derive(Clone, Debug, PartialEq)]
46#[non_exhaustive]
47pub enum H5Type {
48    Int { size: usize, signed: bool, big_endian: bool },
49    Float { size: usize, big_endian: bool },
50    /// A fixed-length string of `size` bytes.
51    FixedString { size: usize },
52    /// A variable-length string (stored in the global heap).
53    VarString,
54    Reference,
55    Compound { size: usize, members: Vec<(String, usize, H5Type)> },
56    Enum { base: Box<H5Type>, names: Vec<(String, i64)> },
57    /// A variable-length sequence of the base type.
58    VarSequence(Box<H5Type>),
59    /// A bitfield of `size` bytes.
60    Bitfield { size: usize },
61    /// A fixed-size array (row-major) of the base type, as a compound member or a dataset's element.
62    Array { dims: Vec<usize>, base: Box<H5Type> },
63    /// Opaque bytes.
64    Opaque { size: usize },
65}
66
67impl H5Type {
68    /// The size of an element in bytes.
69    pub fn size(&self) -> usize {
70        match self {
71            H5Type::Int { size, .. } | H5Type::Float { size, .. } | H5Type::FixedString { size } | H5Type::Compound { size, .. } | H5Type::Bitfield { size } | H5Type::Opaque { size } => *size,
72            H5Type::VarString | H5Type::VarSequence(_) => 16,
73            H5Type::Reference => 8,
74            H5Type::Enum { base, .. } => base.size(),
75            H5Type::Array { dims, base } => dims.iter().product::<usize>() * base.size(),
76        }
77    }
78}
79
80/// An attribute or the data of a dataset: its shape (HDF5's, row-major; empty for a scalar), its
81/// type and its elements in row-major order.
82#[derive(Clone, Debug, PartialEq)]
83pub struct H5Array {
84    pub shape: Vec<usize>,
85    pub dtype: H5Type,
86    pub values: Vec<H5Value>,
87}
88
89impl H5Array {
90    /// The elements as `f64` (integers, floats and enumerations; `None` for other types).
91    pub fn to_f64(&self) -> Option<Vec<f64>> {
92        self.values
93            .iter()
94            .map(|v| match v {
95                H5Value::Int(i) | H5Value::Enum(i, _) => Some(*i as f64),
96                H5Value::UInt(u) => Some(*u as f64),
97                H5Value::Float(f) => Some(*f),
98                _ => None,
99            })
100            .collect()
101    }
102
103    /// The elements as strings, if they are all strings.
104    pub fn to_strings(&self) -> Option<Vec<String>> {
105        self.values.iter().map(|v| if let H5Value::Str(s) = v { Some(s.clone()) } else { None }).collect()
106    }
107}
108
109/// A group: a named collection of groups and datasets, in the order the file lists them.
110#[derive(Clone, Debug)]
111pub struct H5Group {
112    pub attributes: Vec<(String, H5Array)>,
113    pub members: Vec<(String, H5Object)>,
114}
115
116/// A dataset: its attributes and its data.
117#[derive(Clone, Debug)]
118pub struct H5Dataset {
119    pub attributes: Vec<(String, H5Array)>,
120    pub data: H5Array,
121    /// The maximum shape the dataset was created with, `None` in a position for an unlimited
122    /// dimension (empty if the file does not record it).
123    pub max_shape: Vec<Option<usize>>,
124}
125
126/// An object of the file.
127#[derive(Clone, Debug)]
128pub enum H5Object {
129    Group(H5Group),
130    Dataset(H5Dataset),
131}
132
133impl H5Object {
134    pub fn attributes(&self) -> &[(String, H5Array)] {
135        match self {
136            H5Object::Group(g) => &g.attributes,
137            H5Object::Dataset(d) => &d.attributes,
138        }
139    }
140
141    /// An attribute by name.
142    pub fn attribute(&self, name: &str) -> Option<&H5Array> {
143        self.attributes().iter().find(|(n, _)| n == name).map(|(_, a)| a)
144    }
145}
146
147impl H5Group {
148    /// A member by name.
149    pub fn get(&self, name: &str) -> Option<&H5Object> {
150        self.members.iter().find(|(n, _)| n == name).map(|(_, o)| o)
151    }
152
153    /// A member by a `/`-separated path.
154    pub fn path(&self, path: &str) -> Option<&H5Object> {
155        let mut parts = path.split('/').filter(|p| !p.is_empty());
156        let mut cur = self.get(parts.next()?)?;
157        for p in parts {
158            match cur {
159                H5Object::Group(g) => cur = g.get(p)?,
160                H5Object::Dataset(_) => return None,
161            }
162        }
163        Some(cur)
164    }
165}
166
167/// A parsed HDF5 file: the tree of objects under the root group, and the object a reference
168/// points to.
169#[derive(Clone, Debug)]
170pub struct Hdf5File {
171    pub root: H5Group,
172    /// The objects by the address of their headers, for references: those reachable from the root.
173    objects: HashMap<u64, H5Object>,
174    /// The link name each object was first reached by.
175    names: HashMap<u64, String>,
176}
177
178impl Hdf5File {
179    /// The name (the last component of the first path to it) of the object a reference points to.
180    pub fn name_of(&self, reference: u64) -> Option<&str> {
181        self.names.get(&reference).map(String::as_str)
182    }
183
184    /// The object a reference points to.
185    pub fn object_at(&self, reference: u64) -> Option<&H5Object> {
186        self.objects.get(&reference)
187    }
188}
189
190// ---------------------------------------------------------------------------- low-level parsing
191
192struct Reader<'a> {
193    b: &'a [u8],
194    /// The base address: addresses in the file are relative to it (after a user block).
195    base: usize,
196    offset_size: usize,
197    length_size: usize,
198}
199
200fn le(bytes: &[u8]) -> u64 {
201    bytes.iter().rev().fold(0u64, |a, &b| (a << 8) | b as u64)
202}
203
204impl<'a> Reader<'a> {
205    fn slice(&self, addr: usize, len: usize) -> Result<&'a [u8], ErrorsJSL> {
206        let start = self.base.checked_add(addr).ok_or_else(|| bad("HDF5: address overflow"))?;
207        let end = start.checked_add(len).filter(|&e| e <= self.b.len()).ok_or_else(|| bad("HDF5: truncated file or bad address"))?;
208        Ok(&self.b[start..end])
209    }
210
211    fn uint(&self, addr: usize, n: usize) -> Result<u64, ErrorsJSL> {
212        Ok(le(self.slice(addr, n)?))
213    }
214
215    fn offset(&self, addr: usize) -> Result<u64, ErrorsJSL> {
216        self.uint(addr, self.offset_size)
217    }
218
219    fn undefined(&self, v: u64) -> bool {
220        v == u64::MAX >> (64 - 8 * self.offset_size.min(8) as u32)
221    }
222}
223
224/// A cursor over a message's bytes.
225struct Cur<'a> {
226    b: &'a [u8],
227    p: usize,
228}
229
230impl<'a> Cur<'a> {
231    fn take(&mut self, n: usize) -> Result<&'a [u8], ErrorsJSL> {
232        let end = self.p.checked_add(n).filter(|&e| e <= self.b.len()).ok_or_else(|| bad("HDF5: truncated message"))?;
233        let s = &self.b[self.p..end];
234        self.p = end;
235        Ok(s)
236    }
237    fn u(&mut self, n: usize) -> Result<u64, ErrorsJSL> {
238        Ok(le(self.take(n)?))
239    }
240}
241
242#[derive(Clone, Debug)]
243struct Message {
244    kind: u16,
245    data: Vec<u8>,
246}
247
248/// The body of a shared message (flag bit 1): committed datatypes and the like are stored in another
249/// object's header, whose message of the same kind is the body. Messages in the shared message heap
250/// (files with a shared object header message table) are not read.
251fn resolve_shared(r: &Reader, kind: u16, body: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
252    let mut c = Cur { b: body, p: 0 };
253    let version = c.u(1)?;
254    let ty = c.u(1)?;
255    let addr = match version {
256        1 => {
257            c.take(6)?;
258            c.u(r.offset_size)?
259        }
260        2 => c.u(r.offset_size)?,
261        3 if ty == 2 => c.u(r.offset_size)?,
262        3 if ty == 3 => return Ok(c.take(body.len() - 2)?.to_vec()),
263        _ => return Err(bad("HDF5: messages in the shared message heap are not supported")),
264    };
265    let target = read_messages(r, addr as usize)?;
266    target.into_iter().find(|m| m.kind == kind).map(|m| m.data).ok_or_else(|| bad("HDF5: a shared message whose object has no message of that kind"))
267}
268
269/// All the messages of the object header at `addr`, following continuations.
270fn read_messages(r: &Reader, addr: usize) -> Result<Vec<Message>, ErrorsJSL> {
271    let mut out = Vec::new();
272    let head = r.slice(addr, 4)?;
273    if head == b"OHDR" {
274        let version = r.uint(addr + 4, 1)?;
275        if version != 2 {
276            return Err(bad("HDF5: unsupported object header version"));
277        }
278        let flags = r.uint(addr + 5, 1)? as u8;
279        let mut p = addr + 6;
280        if flags & 0x20 != 0 {
281            p += 16; // access, modification, change and birth times
282        }
283        if flags & 0x10 != 0 {
284            p += 4; // maximum compact and minimum dense attribute counts
285        }
286        let size_bytes = 1usize << (flags & 3);
287        let chunk0 = r.uint(p, size_bytes)? as usize;
288        p += size_bytes;
289        let track_order = flags & 4 != 0;
290        let mut chunks = vec![(p, chunk0)];
291        let mut seen = 0;
292        while let Some((start, len)) = chunks.pop() {
293            seen += 1;
294            if seen > 1000 {
295                return Err(bad("HDF5: too many continuation blocks"));
296            }
297            let data = r.slice(start, len)?;
298            let mut q = 0;
299            // Messages fill the chunk up to its 4-byte checksum.
300            while q + 4 + usize::from(track_order) * 2 <= len.saturating_sub(4) {
301                let kind = data[q] as u16;
302                let size = u16::from_le_bytes([data[q + 1], data[q + 2]]) as usize;
303                let msg_flags = data[q + 3];
304                q += 4 + usize::from(track_order) * 2;
305                if kind == 0 && size == 0 {
306                    continue;
307                }
308                let body = data.get(q..q + size).ok_or_else(|| bad("HDF5: truncated object header message"))?;
309                q += size;
310                if kind == 0x10 {
311                    let mut c = Cur { b: body, p: 0 };
312                    let a = c.u(r.offset_size)? as usize;
313                    let l = c.u(r.length_size)? as usize;
314                    // A continuation block of version 2 starts with "OCHK" and ends with a checksum.
315                    if r.slice(a, 4)? != b"OCHK" {
316                        return Err(bad("HDF5: bad continuation block"));
317                    }
318                    chunks.push((a + 4, l - 4));
319                    // The chunk's own length excludes the signature; the checksum is within it.
320                } else if msg_flags & 2 != 0 {
321                    out.push(Message { kind, data: resolve_shared(r, kind, body)? });
322                } else {
323                    out.push(Message { kind, data: body.to_vec() });
324                }
325            }
326        }
327    } else {
328        let version = r.uint(addr, 1)?;
329        if version != 1 {
330            return Err(bad("HDF5: unsupported object header version"));
331        }
332        let count = r.uint(addr + 2, 2)? as usize;
333        let size = r.uint(addr + 8, 4)? as usize;
334        let mut chunks = vec![(addr + 16, size)];
335        let mut n = 0;
336        while let Some((start, len)) = chunks.pop() {
337            let data = r.slice(start, len)?;
338            let mut q = 0;
339            while q + 8 <= len && n < count {
340                let kind = u16::from_le_bytes([data[q], data[q + 1]]);
341                let size = u16::from_le_bytes([data[q + 2], data[q + 3]]) as usize;
342                let msg_flags = data[q + 4];
343                q += 8;
344                n += 1;
345                let body = data.get(q..q + size).ok_or_else(|| bad("HDF5: truncated object header message"))?;
346                q += size;
347                if kind == 0x10 {
348                    let mut c = Cur { b: body, p: 0 };
349                    let a = c.u(r.offset_size)? as usize;
350                    let l = c.u(r.length_size)? as usize;
351                    chunks.push((a, l));
352                } else if kind != 0 {
353                    let data = if msg_flags & 2 != 0 { resolve_shared(r, kind, body)? } else { body.to_vec() };
354                    out.push(Message { kind, data });
355                }
356            }
357        }
358    }
359    Ok(out)
360}
361
362fn parse_datatype(c: &mut Cur) -> Result<H5Type, ErrorsJSL> {
363    let first = c.u(1)? as u8;
364    let (class, version) = (first & 0x0f, first >> 4);
365    let bits = c.u(3)? as u32;
366    let size = c.u(4)? as usize;
367    Ok(match class {
368        0 => {
369            c.take(4)?; // bit offset and precision
370            H5Type::Int { size, signed: bits & 8 != 0, big_endian: bits & 1 != 0 }
371        }
372        1 => {
373            c.take(12)?;
374            H5Type::Float { size, big_endian: bits & 1 != 0 }
375        }
376        3 => H5Type::FixedString { size },
377        4 => {
378            c.take(4)?;
379            H5Type::Bitfield { size }
380        }
381        5 => {
382            let tag_len = (bits & 0xff) as usize;
383            c.take(tag_len)?;
384            H5Type::Opaque { size }
385        }
386        6 => {
387            let n = (bits & 0xffff) as usize;
388            let mut members = Vec::new();
389            for _ in 0..n {
390                let start = c.p;
391                let name_end = c.b[start..].iter().position(|&b| b == 0).ok_or_else(|| bad("HDF5: unterminated member name"))?;
392                let name = String::from_utf8_lossy(&c.b[start..start + name_end]).into_owned();
393                c.p = start + if version < 3 { (name_end + 1).div_ceil(8) * 8 } else { name_end + 1 };
394                let offset = if version >= 3 {
395                    // The offset takes as many bytes as the compound's size needs.
396                    let bytes = (size.max(1).ilog2() as usize) / 8 + 1;
397                    c.u(bytes.min(4))? as usize
398                } else {
399                    c.u(4)? as usize
400                };
401                if version == 1 {
402                    c.take(4 + 4 + 4 + 16)?; // dimensionality, reserved, permutation, sizes
403                }
404                let t = parse_datatype(c)?;
405                members.push((name, offset, t));
406            }
407            H5Type::Compound { size, members }
408        }
409        7 => H5Type::Reference,
410        8 => {
411            let n = (bits & 0xffff) as usize;
412            let base = parse_datatype(c)?;
413            let mut names = Vec::new();
414            for _ in 0..n {
415                let start = c.p;
416                let end = c.b[start..].iter().position(|&b| b == 0).ok_or_else(|| bad("HDF5: unterminated enum name"))?;
417                names.push(String::from_utf8_lossy(&c.b[start..start + end]).into_owned());
418                c.p = start + if version < 3 { (end + 1).div_ceil(8) * 8 } else { end + 1 };
419            }
420            let mut out = Vec::new();
421            for name in names {
422                let raw = c.take(base.size())?;
423                let signed = matches!(base, H5Type::Int { signed: true, .. });
424                out.push((name, int_from(raw, signed, matches!(base, H5Type::Int { big_endian: true, .. }))));
425            }
426            H5Type::Enum { base: Box::new(base), names: out }
427        }
428        9 => {
429            let is_string = bits & 0xf == 1;
430            let base = parse_datatype(c)?;
431            if is_string { H5Type::VarString } else { H5Type::VarSequence(Box::new(base)) }
432        }
433        10 => {
434            // Array: version 2 has reserved bytes and permutation indices, version 3 does not.
435            let nd = c.u(1)? as usize;
436            if version < 3 {
437                c.take(3)?;
438            }
439            let dims = (0..nd).map(|_| c.u(4).map(|v| v as usize)).collect::<Result<Vec<_>, _>>()?;
440            if version < 3 {
441                c.take(4 * nd)?;
442            }
443            let base = parse_datatype(c)?;
444            if dims.iter().product::<usize>().checked_mul(base.size()) != Some(size) {
445                return Err(bad("HDF5: an array datatype whose size does not match its dimensions"));
446            }
447            H5Type::Array { dims, base: Box::new(base) }
448        }
449        _ => return Err(bad("HDF5: unsupported datatype class")),
450    })
451}
452
453fn int_from(raw: &[u8], signed: bool, big: bool) -> i64 {
454    let mut bytes = raw.to_vec();
455    if big {
456        bytes.reverse();
457    }
458    let u = le(&bytes);
459    let bits = 8 * bytes.len().min(8);
460    if signed && bits < 64 && u >> (bits - 1) & 1 == 1 { (u as i64) - (1i64 << bits) } else { u as i64 }
461}
462
463fn parse_dataspace(data: &[u8], r: &Reader) -> Result<Vec<usize>, ErrorsJSL> {
464    let mut c = Cur { b: data, p: 0 };
465    let version = c.u(1)?;
466    let rank = c.u(1)? as usize;
467    let flags = c.u(1)?;
468    let kind = if version >= 2 { c.u(1)? } else { c.take(1)?; 1 };
469    if version == 1 {
470        c.take(4)?;
471    }
472    if kind == 2 {
473        return Ok(vec![0]); // null dataspace: no elements
474    }
475    let _ = flags;
476    (0..rank).map(|_| c.u(r.length_size).map(|v| v as usize)).collect()
477}
478
479/// The maximum dimensions of a dataspace (`None` for an unlimited one), if it records them.
480fn dataspace_max(data: &[u8], r: &Reader) -> Option<Vec<Option<usize>>> {
481    let mut c = Cur { b: data, p: 0 };
482    let version = c.u(1).ok()?;
483    let rank = c.u(1).ok()? as usize;
484    let flags = c.u(1).ok()?;
485    if version >= 2 {
486        c.u(1).ok()?;
487    } else {
488        c.take(1).ok()?;
489    }
490    if version == 1 {
491        c.take(4).ok()?;
492    }
493    if flags & 1 == 0 {
494        return None;
495    }
496    c.take(rank * r.length_size).ok()?;
497    let unlimited = if r.length_size == 8 { u64::MAX } else { u32::MAX as u64 };
498    (0..rank).map(|_| c.u(r.length_size).ok().map(|v| if v == unlimited { None } else { Some(v as usize) })).collect()
499}
500
501/// A fixed-point or other raw element as a [`H5Value`].
502fn decode_element(raw: &[u8], t: &H5Type, r: &Reader) -> Result<H5Value, ErrorsJSL> {
503    Ok(match t {
504        H5Type::Int { signed, big_endian, .. } => {
505            let v = int_from(raw, *signed, *big_endian);
506            if *signed || raw.len() < 8 { H5Value::Int(v) } else { H5Value::UInt(v as u64) }
507        }
508        H5Type::Float { size, big_endian } => {
509            let mut b = raw.to_vec();
510            if *big_endian {
511                b.reverse();
512            }
513            match size {
514                4 => H5Value::Float(f32::from_le_bytes(b[..4].try_into().expect("4")) as f64),
515                8 => H5Value::Float(f64::from_le_bytes(b[..8].try_into().expect("8"))),
516                2 => H5Value::Float(half(u16::from_le_bytes([b[0], b[1]]))),
517                _ => return Err(bad("HDF5: unsupported floating-point size")),
518            }
519        }
520        H5Type::FixedString { .. } => {
521            let end = raw.iter().position(|&b| b == 0).unwrap_or(raw.len());
522            H5Value::Str(String::from_utf8_lossy(&raw[..end]).into_owned())
523        }
524        H5Type::Reference => H5Value::Reference(le(raw)),
525        H5Type::Bitfield { .. } | H5Type::Opaque { .. } => H5Value::UInt(le(&raw[..raw.len().min(8)])),
526        H5Type::Enum { base, names } => {
527            let v = match decode_element(raw, base, r)? {
528                H5Value::Int(i) => i,
529                H5Value::UInt(u) => u as i64,
530                _ => 0,
531            };
532            H5Value::Enum(v, names.iter().find(|(_, x)| *x == v).map(|(n, _)| n.clone()))
533        }
534        H5Type::Array { dims, base } => {
535            let w = base.size();
536            let count = dims.iter().product::<usize>();
537            if raw.len() < count * w {
538                return Err(bad("HDF5: an array element shorter than its type"));
539            }
540            H5Value::Sequence((0..count).map(|i| decode_element(&raw[i * w..(i + 1) * w], base, r)).collect::<Result<_, _>>()?)
541        }
542        H5Type::Compound { members, .. } => {
543            let mut out = Vec::new();
544            for (name, offset, mt) in members {
545                let end = offset + mt.size();
546                let part = raw.get(*offset..end).ok_or_else(|| bad("HDF5: compound member outside its element"))?;
547                out.push((name.clone(), decode_element(part, mt, r)?));
548            }
549            H5Value::Compound(out)
550        }
551        H5Type::VarString | H5Type::VarSequence(_) => {
552            // (length, global heap address, object index).
553            let n = u32::from_le_bytes(raw[..4].try_into().expect("4")) as usize;
554            let addr = le(&raw[4..4 + r.offset_size]) as usize;
555            let index = u32::from_le_bytes(raw[4 + r.offset_size..8 + r.offset_size].try_into().expect("4")) as usize;
556            let bytes = if n == 0 { Vec::new() } else { global_heap_object(r, addr, index)? };
557            match t {
558                H5Type::VarString => H5Value::Str(String::from_utf8_lossy(&bytes[..n.min(bytes.len())]).into_owned()),
559                H5Type::VarSequence(base) => {
560                    let w = base.size();
561                    H5Value::Sequence((0..n).map(|i| decode_element(&bytes[i * w..(i + 1) * w], base, r)).collect::<Result<_, _>>()?)
562                }
563                _ => unreachable!(),
564            }
565        }
566    })
567}
568
569fn half(h: u16) -> f64 {
570    let (exp, frac) = ((h >> 10) & 0x1f, (h & 0x3ff) as f64);
571    let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 };
572    sign * match exp {
573        0 => frac * 2f64.powi(-24),
574        31 => if frac == 0.0 { f64::INFINITY } else { f64::NAN },
575        _ => (1.0 + frac / 1024.0) * 2f64.powi(exp as i32 - 15),
576    }
577}
578
579/// An object of the global heap collection at `addr`.
580fn global_heap_object(r: &Reader, addr: usize, index: usize) -> Result<Vec<u8>, ErrorsJSL> {
581    if r.slice(addr, 4)? != b"GCOL" {
582        return Err(bad("HDF5: bad global heap collection"));
583    }
584    let size = r.uint(addr + 8, r.length_size)? as usize;
585    let mut p = addr + 8 + r.length_size;
586    let end = addr + size;
587    while p + 8 + r.length_size <= end {
588        let idx = r.uint(p, 2)? as usize;
589        let len = r.uint(p + 8, r.length_size)? as usize;
590        if idx == 0 {
591            break;
592        }
593        let data_at = p + 8 + r.length_size;
594        if idx == index {
595            return Ok(r.slice(data_at, len)?.to_vec());
596        }
597        p = data_at + len.div_ceil(8) * 8;
598    }
599    Err(bad("HDF5: global heap object not found"))
600}
601
602#[derive(Clone, Debug)]
603enum Layout {
604    Compact(Vec<u8>),
605    Contiguous { addr: u64, size: u64 },
606    Chunked { btree: u64, chunk: Vec<usize> },
607    /// Layout version 4: the chunk index is one of several kinds (`index`: 1 single chunk, 2
608    /// implicit, 3 fixed array, 4 extensible array, 5 version 2 B-tree).
609    ChunkedV4 { index: u8, flags: u8, chunk: Vec<usize>, addr: u64, single: Option<(usize, u32)>, page_bits: u8 },
610}
611
612#[derive(Clone, Debug)]
613struct Filter {
614    id: u16,
615    values: Vec<u32>,
616}
617
618fn parse_layout(data: &[u8], r: &Reader) -> Result<Layout, ErrorsJSL> {
619    let mut c = Cur { b: data, p: 0 };
620    let version = c.u(1)?;
621    match version {
622        3 => {
623            let class = c.u(1)?;
624            match class {
625                0 => {
626                    let n = c.u(2)? as usize;
627                    Ok(Layout::Compact(c.take(n)?.to_vec()))
628                }
629                1 => Ok(Layout::Contiguous { addr: c.u(r.offset_size)?, size: c.u(r.length_size)? }),
630                2 => {
631                    let dim = c.u(1)? as usize;
632                    let btree = c.u(r.offset_size)?;
633                    let chunk = (0..dim).map(|_| c.u(4).map(|v| v as usize)).collect::<Result<Vec<_>, _>>()?;
634                    Ok(Layout::Chunked { btree, chunk })
635                }
636                _ => Err(bad("HDF5: unsupported data layout class")),
637            }
638        }
639        // Version 5 (HDF5 2.0, for chunks over 4 GiB) is version 4 with wider dimension sizes, which the
640        // encoded size field already covers.
641        4 | 5 => {
642            let class = c.u(1)?;
643            match class {
644                0 => {
645                    let n = c.u(2)? as usize;
646                    Ok(Layout::Compact(c.take(n)?.to_vec()))
647                }
648                1 => Ok(Layout::Contiguous { addr: c.u(r.offset_size)?, size: c.u(r.length_size)? }),
649                2 => {
650                    let flags = c.u(1)? as u8;
651                    let dim = c.u(1)? as usize;
652                    let enc = c.u(1)? as usize;
653                    let chunk = (0..dim).map(|_| c.u(enc).map(|v| v as usize)).collect::<Result<Vec<_>, _>>()?;
654                    let index = c.u(1)? as u8;
655                    let (mut single, mut page_bits) = (None, 0u8);
656                    match index {
657                        1 if flags & 2 != 0 => single = Some((c.u(r.length_size)? as usize, c.u(4)? as u32)),
658                        3 => page_bits = c.u(1)? as u8,
659                        4 => {
660                            c.take(5)?;
661                        }
662                        5 => {
663                            c.take(6)?;
664                        }
665                        _ => {}
666                    }
667                    Ok(Layout::ChunkedV4 { index, flags, chunk, addr: c.u(r.offset_size)?, single, page_bits })
668                }
669                3 => Err(bad("HDF5: virtual datasets are not supported")),
670                _ => Err(bad("HDF5: unsupported data layout class")),
671            }
672        }
673        1 | 2 => {
674            let dim = c.u(1)? as usize;
675            let class = c.u(1)?;
676            c.take(5)?;
677            let addr = if class != 0 { c.u(r.offset_size)? } else { 0 };
678            let dims = (0..dim).map(|_| c.u(4).map(|v| v as usize)).collect::<Result<Vec<_>, _>>()?;
679            match class {
680                1 => Ok(Layout::Contiguous { addr, size: dims.iter().product::<usize>() as u64 }),
681                2 => Ok(Layout::Chunked { btree: addr, chunk: dims }),
682                _ => {
683                    let n = c.u(4)? as usize;
684                    Ok(Layout::Compact(c.take(n)?.to_vec()))
685                }
686            }
687        }
688        _ => Err(bad("HDF5: unsupported data layout version (versions 1 to 5 are read)")),
689    }
690}
691
692fn parse_filters(data: &[u8]) -> Result<Vec<Filter>, ErrorsJSL> {
693    let mut c = Cur { b: data, p: 0 };
694    let version = c.u(1)?;
695    let n = c.u(1)? as usize;
696    if version == 1 {
697        c.take(6)?;
698    }
699    let mut out = Vec::new();
700    for _ in 0..n {
701        let id = c.u(2)? as u16;
702        let name_len = if version == 1 || id >= 256 { c.u(2)? as usize } else { 0 };
703        let _flags = c.u(2)?;
704        let nvalues = c.u(2)? as usize;
705        if name_len > 0 {
706            c.take(if version == 1 { name_len.div_ceil(8) * 8 } else { name_len })?;
707        }
708        let values = (0..nvalues).map(|_| c.u(4).map(|v| v as u32)).collect::<Result<Vec<_>, _>>()?;
709        if version == 1 && nvalues % 2 == 1 {
710            c.take(4)?;
711        }
712        out.push(Filter { id, values });
713    }
714    Ok(out)
715}
716
717/// The raw bytes of a chunk, with its filters undone (in reverse order).
718fn unfilter(mut bytes: Vec<u8>, filters: &[Filter], mask: u32, element: usize) -> Result<Vec<u8>, ErrorsJSL> {
719    for (k, f) in filters.iter().enumerate().rev() {
720        if mask >> k & 1 == 1 {
721            continue;
722        }
723        match f.id {
724            1 => bytes = zlib_decompress(&bytes)?,
725            2 => {
726                // Shuffle: the bytes of each element were stored byte-plane by byte-plane.
727                let size = f.values.first().copied().unwrap_or(element as u32) as usize;
728                if size > 1 && bytes.len().is_multiple_of(size) {
729                    let n = bytes.len() / size;
730                    let mut out = vec![0u8; bytes.len()];
731                    for b in 0..size {
732                        for i in 0..n {
733                            out[i * size + b] = bytes[b * n + i];
734                        }
735                    }
736                    bytes = out;
737                }
738            }
739            3 => {
740                // Fletcher-32: a checksum after the data.
741                bytes.truncate(bytes.len().saturating_sub(4));
742            }
743            32000 => {
744                // LZF (h5py's own filter); the third client value is the size of the uncompressed chunk.
745                let out_len = f.values.get(2).copied().map(|v| v as usize).ok_or_else(|| bad("HDF5: an LZF filter without the chunk size"))?;
746                bytes = lzf_decompress(&bytes, out_len)?;
747            }
748            4 => return Err(bad("HDF5: the SZIP filter is not supported")),
749            5 => return Err(bad("HDF5: the N-bit filter is not supported")),
750            6 => return Err(bad("HDF5: the scale-offset filter is not supported")),
751            _ => return Err(bad("HDF5: unsupported filter (deflate, shuffle, Fletcher-32 and LZF are read)")),
752        }
753    }
754    Ok(bytes)
755}
756
757/// liblzf's decompressor: control bytes below 32 start a run of `ctrl + 1` literal bytes, the others a
758/// back-reference of length `(ctrl >> 5) + 2` (plus a byte if the length field is 7) at a distance
759/// of `((ctrl & 31) << 8) + next byte + 1`, which may overlap its own output.
760fn lzf_decompress(input: &[u8], out_len: usize) -> Result<Vec<u8>, ErrorsJSL> {
761    let corrupt = || bad("HDF5: a corrupt LZF chunk");
762    let mut out: Vec<u8> = Vec::with_capacity(out_len);
763    let mut i = 0;
764    while i < input.len() {
765        let ctrl = input[i] as usize;
766        i += 1;
767        if ctrl < 32 {
768            let run = ctrl + 1;
769            let lit = input.get(i..i + run).ok_or_else(corrupt)?;
770            out.extend_from_slice(lit);
771            i += run;
772        } else {
773            let mut len = ctrl >> 5;
774            if len == 7 {
775                len += *input.get(i).ok_or_else(corrupt)? as usize;
776                i += 1;
777            }
778            let dist = ((ctrl & 0x1f) << 8) + *input.get(i).ok_or_else(corrupt)? as usize + 1;
779            i += 1;
780            len += 2;
781            if dist > out.len() {
782                return Err(corrupt());
783            }
784            let start = out.len() - dist;
785            for k in 0..len {
786                let b = out[start + k];
787                out.push(b);
788            }
789        }
790        if out.len() > out_len {
791            return Err(corrupt());
792        }
793    }
794    if out.len() != out_len {
795        return Err(corrupt());
796    }
797    Ok(out)
798}
799
800/// A chunk: its offsets, address, size and filter mask.
801type Chunk = (Vec<usize>, usize, usize, u32);
802
803/// The chunks of a dataset from its version 1 B-tree: `(chunk offsets, address, size, filter mask)`.
804fn chunk_index(r: &Reader, root: u64, dims: usize) -> Result<Vec<Chunk>, ErrorsJSL> {
805    let mut out = Vec::new();
806    let mut stack = vec![root as usize];
807    let mut guard = 0;
808    while let Some(node) = stack.pop() {
809        guard += 1;
810        if guard > 1_000_000 {
811            return Err(bad("HDF5: chunk index too large"));
812        }
813        if r.slice(node, 4)? != b"TREE" {
814            return Err(bad("HDF5: bad chunk B-tree node"));
815        }
816        let (kind, level, used) = (r.uint(node + 4, 1)?, r.uint(node + 5, 1)?, r.uint(node + 6, 2)? as usize);
817        if kind != 1 {
818            return Err(bad("HDF5: unexpected B-tree type"));
819        }
820        let key_size = 8 + 8 * dims;
821        let mut p = node + 8 + 2 * r.offset_size;
822        for _ in 0..used {
823            let size = r.uint(p, 4)? as usize;
824            let mask = r.uint(p + 4, 4)? as u32;
825            let offsets: Vec<usize> = (0..dims).map(|d| r.uint(p + 8 + 8 * d, 8).map(|v| v as usize)).collect::<Result<_, _>>()?;
826            let child = r.offset(p + key_size)? as usize;
827            if level == 0 {
828                out.push((offsets, child, size, mask));
829            } else {
830                stack.push(child);
831            }
832            p += key_size + r.offset_size;
833        }
834    }
835    Ok(out)
836}
837
838/// Copies chunks into an array of `total` bytes (clipping at the edges): `(offsets, address, size, mask)`.
839#[allow(clippy::too_many_arguments)]
840fn copy_chunks(r: &Reader, shape: &[usize], chunk: &[usize], list: &[Chunk], filters: &[Filter], es: usize, total: usize, fill: Option<&[u8]>) -> Result<Vec<u8>, ErrorsJSL> {
841    let rank = shape.len();
842    let mut out = filled(total, es, fill);
843    let chunk_dims = &chunk[..rank];
844    let chunk_elems: usize = chunk_dims.iter().product();
845    for (offsets, addr, size, mask) in list {
846        let bytes = unfilter(r.slice(*addr, *size)?.to_vec(), filters, *mask, es)?;
847        if bytes.len() < chunk_elems * es {
848            return Err(bad("HDF5: a chunk is smaller than its shape"));
849        }
850        let mut idx = vec![0usize; rank];
851        for e in 0..chunk_elems {
852            let mut lin = 0;
853            let mut inside = true;
854            for d in 0..rank {
855                let pos = offsets[d] + idx[d];
856                if pos >= shape[d] {
857                    inside = false;
858                    break;
859                }
860                lin = lin * shape[d] + pos;
861            }
862            if inside {
863                out[lin * es..(lin + 1) * es].copy_from_slice(&bytes[e * es..(e + 1) * es]);
864            }
865            for d in (0..rank).rev() {
866                idx[d] += 1;
867                if idx[d] < chunk_dims[d] {
868                    break;
869                }
870                idx[d] = 0;
871            }
872        }
873    }
874    Ok(out)
875}
876
877/// A buffer of `total` bytes holding the dataset's fill value in every element (zeros without one).
878fn filled(total: usize, es: usize, fill: Option<&[u8]>) -> Vec<u8> {
879    match fill {
880        Some(f) if f.len() == es && es > 0 && f.iter().any(|&b| b != 0) => f.iter().copied().cycle().take(total).collect(),
881        _ => vec![0u8; total],
882    }
883}
884
885/// The fill value of a dataset from its fill value message (the new one, type 5, or the old one, type 4),
886/// if one is defined.
887fn parse_fill_value(messages: &[Message]) -> Option<Vec<u8>> {
888    let find = |k: u16| messages.iter().find(|m| m.kind == k);
889    let size_and_value = |c: &mut Cur| -> Option<Vec<u8>> {
890        let size = c.u(4).ok()? as usize;
891        if size == 0 { None } else { c.take(size).ok().map(|b| b.to_vec()) }
892    };
893    if let Some(m) = find(0x05) {
894        let mut c = Cur { b: &m.data, p: 0 };
895        match c.u(1).ok()? {
896            1 | 2 => {
897                c.take(2).ok()?;
898                if c.u(1).ok()? == 0 {
899                    return None;
900                }
901                size_and_value(&mut c)
902            }
903            3 => {
904                let flags = c.u(1).ok()?;
905                if flags & 0x20 == 0 { None } else { size_and_value(&mut c) }
906            }
907            _ => None,
908        }
909    } else {
910        find(0x04).and_then(|m| size_and_value(&mut Cur { b: &m.data, p: 0 }))
911    }
912}
913
914/// The chunks of a dataset of layout version 4, for the chunk index kinds that are read: a single
915/// chunk, implicit addresses, a fixed array (paged or not), or a version 2 B-tree.
916#[allow(clippy::too_many_arguments)]
917fn chunk_list_v4(r: &Reader, shape: &[usize], max_dims: Option<&[Option<usize>]>, chunk: &[usize], index: u8, flags: u8, addr: usize, single: Option<(usize, u32)>, page_bits: u8, es: usize, filtered: bool) -> Result<Vec<Chunk>, ErrorsJSL> {
918    let rank = shape.len();
919    let chunk_bytes = chunk[..rank].iter().product::<usize>() * es;
920    let grid: Vec<usize> = (0..rank).map(|d| shape[d].div_ceil(chunk[d])).collect();
921    let ncells: usize = grid.iter().product();
922    let coords = |lin: usize| -> Vec<usize> {
923        let mut rest = lin;
924        let mut c = vec![0usize; rank + 1];
925        for d in (0..rank).rev() {
926            c[d] = (rest % grid[d]) * chunk[d];
927            rest /= grid[d];
928        }
929        c
930    };
931    let mut out = Vec::new();
932    match index {
933        1 => {
934            let (size, mask) = single.unwrap_or((chunk_bytes, 0));
935            out.push((vec![0; rank + 1], addr, size, mask));
936        }
937        2 => {
938            for i in 0..ncells {
939                out.push((coords(i), addr + i * chunk_bytes, chunk_bytes, 0));
940            }
941        }
942        3 => {
943            if r.slice(addr, 4)? != b"FAHD" {
944                return Err(bad("HDF5: bad fixed array header"));
945            }
946            let elem_size = r.uint(addr + 6, 1)? as usize;
947            let nelem = r.uint(addr + 8, r.length_size)? as usize;
948            let block = r.offset(addr + 8 + r.length_size)? as usize;
949            if r.slice(block, 4)? != b"FADB" {
950                return Err(bad("HDF5: bad fixed array data block"));
951            }
952            let page_elems = 1usize << page_bits.min(40);
953            // Elements are in the block itself, or in consecutive pages after its prefix (a page
954            // bitmap, then each page with its own checksum).
955            let (first, page_stride) = if nelem > page_elems {
956                let npages = nelem.div_ceil(page_elems);
957                (block + 6 + r.offset_size + npages.div_ceil(8) + 4, Some(page_elems * elem_size + 4))
958            } else {
959                (block + 6 + r.offset_size, None)
960            };
961            let valid = |a: u64| !r.undefined(a) && a != 0 && (a as usize) < r.b.len();
962            for i in 0..nelem.min(ncells) {
963                let p = match page_stride {
964                    Some(stride) => first + (i / page_elems) * stride + (i % page_elems) * elem_size,
965                    None => first + i * elem_size,
966                };
967                let a = r.offset(p)?;
968                if valid(a) {
969                    if filtered {
970                        let nb = elem_size.checked_sub(r.offset_size + 4).ok_or_else(|| bad("HDF5: bad fixed array element size"))?;
971                        out.push((coords(i), a as usize, r.uint(p + r.offset_size, nb)? as usize, r.uint(p + r.offset_size + nb, 4)? as u32));
972                    } else {
973                        out.push((coords(i), a as usize, chunk_bytes, 0));
974                    }
975                }
976            }
977        }
978        5 => {
979            let _ = flags;
980            for rec in btree2_records(r, addr)? {
981                let o = r.offset_size;
982                let a = le(&rec[..o]);
983                let (size, mask, at) = if filtered {
984                    let nb = rec.len() - o - 4 - 8 * rank;
985                    (le(&rec[o..o + nb]) as usize, le(&rec[o + nb..o + nb + 4]) as u32, o + nb + 4)
986                } else {
987                    (chunk_bytes, 0, o)
988                };
989                let mut offsets: Vec<usize> = (0..rank).map(|d| le(&rec[at + 8 * d..at + 8 * d + 8]) as usize * chunk[d]).collect();
990                offsets.push(0);
991                out.push((offsets, a as usize, size, mask));
992            }
993        }
994        4 => extensible_array_chunks(r, addr, shape, max_dims, chunk, &grid, es, filtered, &mut out)?,
995        _ => return Err(bad("HDF5: unsupported chunk index kind")),
996    }
997    Ok(out)
998}
999
1000/// The chunks of an extensible array index: a header, an index block holding the first elements and the
1001/// addresses of the first data blocks, then super blocks that point to data blocks of doubling sizes
1002/// (paged when large). The element of a chunk is found from its linear index, which runs over the
1003/// chunk grid with the (single) unlimited dimension slowest, so that the array can grow.
1004#[allow(clippy::too_many_arguments)]
1005fn extensible_array_chunks(r: &Reader, hd: usize, shape: &[usize], max_dims: Option<&[Option<usize>]>, chunk: &[usize], grid: &[usize], es: usize, filtered: bool, out: &mut Vec<Chunk>) -> Result<(), ErrorsJSL> {
1006    let _ = es;
1007    let rank = shape.len();
1008    if r.slice(hd, 4)? != b"EAHD" {
1009        return Err(bad("HDF5: bad extensible array header"));
1010    }
1011    let o = r.offset_size;
1012    let elem_size = r.uint(hd + 6, 1)? as usize;
1013    let max_bits = r.uint(hd + 7, 1)? as usize;
1014    let idx_elmts = r.uint(hd + 8, 1)? as usize;
1015    let dblk_min = r.uint(hd + 9, 1)? as usize;
1016    let sblk_min_ptrs = r.uint(hd + 10, 1)? as usize;
1017    let page_bits = r.uint(hd + 11, 1)? as usize;
1018    let ib = r.offset(hd + 12 + 6 * r.length_size)?;
1019    if dblk_min == 0 || !dblk_min.is_power_of_two() || !sblk_min_ptrs.is_power_of_two() || max_bits == 0 || max_bits > 63 || page_bits > 40 || elem_size < o {
1020        return Err(bad("HDF5: bad extensible array parameters"));
1021    }
1022    let log2 = |v: usize| v.trailing_zeros() as usize;
1023    let nsblks = 1 + max_bits.saturating_sub(log2(dblk_min));
1024    let ib_nsblks = 2 * log2(sblk_min_ptrs);
1025    let ib_ndblks = 2 * (sblk_min_ptrs - 1);
1026    let arr_off = max_bits.div_ceil(8);
1027    let page_elems = 1usize << page_bits;
1028    let nb = elem_size.checked_sub(o + 4);
1029    // The unlimited dimension is the slowest; the others count chunks over their maximum extent.
1030    let unlimited = max_dims.and_then(|m| m.iter().position(|d| d.is_none()));
1031    let counts: Vec<usize> = (0..rank).map(|d| match max_dims.and_then(|m| m.get(d)).copied().flatten() {
1032        Some(m) => m.div_ceil(chunk[d]).max(1),
1033        None => grid[d].max(1),
1034    }).collect();
1035    let order: Vec<usize> = match unlimited {
1036        Some(u) => std::iter::once(u).chain((0..rank).filter(|&d| d != u)).collect(),
1037        None => (0..rank).collect(),
1038    };
1039    let mut down = vec![1usize; rank];
1040    for k in (0..rank.saturating_sub(1)).rev() {
1041        down[order[k]] = down[order[k + 1]] * counts[order[k + 1]];
1042    }
1043    let valid = |a: u64| !r.undefined(a) && (a as usize) < r.b.len();
1044    // The element of a chunk, given where it is stored.
1045    let element = |p: usize| -> Result<Option<(usize, usize, u32)>, ErrorsJSL> {
1046        let a = r.offset(p)?;
1047        if !valid(a) {
1048            return Ok(None);
1049        }
1050        if filtered {
1051            let nb = nb.ok_or_else(|| bad("HDF5: bad extensible array element size"))?;
1052            Ok(Some((a as usize, r.uint(p + o, nb)? as usize, r.uint(p + o + nb, 4)? as u32)))
1053        } else {
1054            Ok(Some((a as usize, usize::MAX, 0)))
1055        }
1056    };
1057    let chunk_bytes = chunk[..rank].iter().product::<usize>() * es;
1058    let ncells: usize = grid.iter().product();
1059    let has_index_block = !r.undefined(ib) && (ib as usize) < r.b.len();
1060    if has_index_block && r.slice(ib as usize, 4)? != b"EAIB" {
1061        return Err(bad("HDF5: bad extensible array index block"));
1062    }
1063    for cell in 0..ncells {
1064        // The chunk's coordinates in the grid (row-major over the current extent), and its element index.
1065        let mut rest = cell;
1066        let mut scaled = vec![0usize; rank];
1067        for d in (0..rank).rev() {
1068            scaled[d] = rest % grid[d];
1069            rest /= grid[d];
1070        }
1071        let idx: usize = (0..rank).map(|d| scaled[d] * down[d]).sum();
1072        let found = if !has_index_block {
1073            None
1074        } else if idx < idx_elmts {
1075            element(ib as usize + 6 + o + idx * elem_size)?
1076        } else {
1077            let k = idx - idx_elmts;
1078            let sblk = ((k / dblk_min) + 1).ilog2() as usize;
1079            if sblk >= nsblks {
1080                return Err(bad("HDF5: extensible array index out of range"));
1081            }
1082            let in_sblk = k - ((1usize << sblk) - 1) * dblk_min;
1083            let dblk_elems = dblk_min << sblk.div_ceil(2);
1084            let (dblk_idx, off) = (in_sblk / dblk_elems, in_sblk % dblk_elems);
1085            let ib_elems_end = ib as usize + 6 + o + idx_elmts * elem_size;
1086            let dblk_addr = if sblk < ib_nsblks {
1087                // Data blocks of the first super blocks are addressed from the index block.
1088                let first: usize = (0..sblk).map(|j| 1usize << (j / 2)).sum();
1089                r.offset(ib_elems_end + (first + dblk_idx) * o)?
1090            } else {
1091                let sb_addr = r.offset(ib_elems_end + ib_ndblks * o + (sblk - ib_nsblks) * o)?;
1092                if !valid(sb_addr) {
1093                    u64::MAX
1094                } else {
1095                    let sb = sb_addr as usize;
1096                    if r.slice(sb, 4)? != b"EASB" {
1097                        return Err(bad("HDF5: bad extensible array super block"));
1098                    }
1099                    let ndblks = 1usize << (sblk / 2);
1100                    let paged = dblk_elems > page_elems;
1101                    let npages = if paged { dblk_elems / page_elems } else { 0 };
1102                    let bitmap = npages.div_ceil(8);
1103                    let addrs = sb + 6 + o + arr_off + ndblks * bitmap;
1104                    r.offset(addrs + dblk_idx * o)?
1105                }
1106            };
1107            if !valid(dblk_addr) {
1108                None
1109            } else {
1110                let db = dblk_addr as usize;
1111                if r.slice(db, 4)? != b"EADB" {
1112                    return Err(bad("HDF5: bad extensible array data block"));
1113                }
1114                let prefix = 6 + o + arr_off;
1115                if dblk_elems > page_elems {
1116                    let (page, in_page) = (off / page_elems, off % page_elems);
1117                    // Pages follow the prefix and its checksum, each with a checksum of its own.
1118                    let at = db + prefix + 4 + page * (page_elems * elem_size + 4) + in_page * elem_size;
1119                    element(at)?
1120                } else {
1121                    element(db + prefix + off * elem_size)?
1122                }
1123            }
1124        };
1125        if let Some((a, size, mask)) = found {
1126            let coords: Vec<usize> = (0..rank).map(|d| scaled[d] * chunk[d]).chain(std::iter::once(0)).collect();
1127            out.push((coords, a, if size == usize::MAX { chunk_bytes } else { size }, mask));
1128        }
1129    }
1130    Ok(())
1131}
1132
1133/// The elements of a dataset.
1134fn read_data(r: &Reader, messages: &[Message]) -> Result<H5Array, ErrorsJSL> {
1135    let find = |k: u16| messages.iter().find(|m| m.kind == k);
1136    let space = find(0x01).ok_or_else(|| bad("HDF5: a dataset without a dataspace"))?;
1137    let shape = parse_dataspace(&space.data, r)?;
1138    let dtype_msg = find(0x03).ok_or_else(|| bad("HDF5: a dataset without a datatype"))?;
1139    let dtype = parse_datatype(&mut Cur { b: &dtype_msg.data, p: 0 })?;
1140    if find(0x07).is_some() {
1141        return Err(bad("HDF5: datasets in external files are not supported"));
1142    }
1143    let layout = parse_layout(&find(0x08).ok_or_else(|| bad("HDF5: a dataset without a layout"))?.data, r)?;
1144    let max_dims = dataspace_max(&space.data, r);
1145    let fill = parse_fill_value(messages);
1146    let filters = match find(0x0b) {
1147        Some(m) => parse_filters(&m.data)?,
1148        None => Vec::new(),
1149    };
1150    let n: usize = shape.iter().product();
1151    let es = dtype.size();
1152    let total = n.checked_mul(es).filter(|&t| t <= 1 << 32).ok_or_else(|| bad("HDF5: dataset too large to read into memory (over 4 GiB)"))?;
1153    let raw: Vec<u8> = match layout {
1154        Layout::Compact(d) => d,
1155        Layout::Contiguous { addr, size } => {
1156            if r.undefined(addr) || n == 0 {
1157                filled(total, es, fill.as_deref())
1158            } else {
1159                r.slice(addr as usize, (size as usize).min(total).max(total))?.to_vec()
1160            }
1161        }
1162        Layout::Chunked { btree, chunk } => {
1163            let list = if !r.undefined(btree) && n > 0 { chunk_index(r, btree, shape.len() + 1)? } else { Vec::new() };
1164            copy_chunks(r, &shape, &chunk, &list, &filters, es, total, fill.as_deref())?
1165        }
1166        Layout::ChunkedV4 { index, flags, chunk, addr, single, page_bits } => {
1167            let list = if !r.undefined(addr) && n > 0 { chunk_list_v4(r, &shape, max_dims.as_deref(), &chunk, index, flags, addr as usize, single, page_bits, es, !filters.is_empty())? } else { Vec::new() };
1168            copy_chunks(r, &shape, &chunk, &list, &filters, es, total, fill.as_deref())?
1169        }
1170    };
1171    if raw.len() < total {
1172        return Err(bad("HDF5: less data than the dataspace needs"));
1173    }
1174    let values = (0..n).map(|i| decode_element(&raw[i * es..(i + 1) * es], &dtype, r)).collect::<Result<Vec<_>, _>>()?;
1175    let shape = if shape == [0usize] && n == 0 && space.data.first() == Some(&2) { vec![0] } else { shape };
1176    Ok(H5Array { shape, dtype, values })
1177}
1178
1179fn read_attribute(data: &[u8], r: &Reader) -> Result<(String, H5Array), ErrorsJSL> {
1180    let mut c = Cur { b: data, p: 0 };
1181    let version = c.u(1)?;
1182    if version == 1 {
1183        c.take(1)?;
1184    } else {
1185        c.take(1)?; // flags
1186    }
1187    let (name_size, type_size, space_size) = (c.u(2)? as usize, c.u(2)? as usize, c.u(2)? as usize);
1188    if version == 3 {
1189        c.take(1)?;
1190    }
1191    let pad = |n: usize| if version == 1 { n.div_ceil(8) * 8 } else { n };
1192    let name_bytes = c.take(pad(name_size))?;
1193    let name = String::from_utf8_lossy(&name_bytes[..name_bytes.iter().position(|&b| b == 0).unwrap_or(name_bytes.len())]).into_owned();
1194    let type_bytes = c.take(pad(type_size))?;
1195    let dtype = parse_datatype(&mut Cur { b: type_bytes, p: 0 })?;
1196    let space_bytes = c.take(pad(space_size))?;
1197    let shape = parse_dataspace(space_bytes, r)?;
1198    let n: usize = shape.iter().product();
1199    let es = dtype.size();
1200    let raw = c.take(n * es).or_else(|_| if n == 0 { Ok(&data[0..0]) } else { Err(bad("HDF5: truncated attribute data")) })?;
1201    let values = (0..n).map(|i| decode_element(&raw[i * es..(i + 1) * es], &dtype, r)).collect::<Result<Vec<_>, _>>()?;
1202    Ok((name, H5Array { shape, dtype, values }))
1203}
1204
1205/// The entries of a symbol table group: `(name, object header address)`.
1206fn symbol_table(r: &Reader, btree: usize, heap: usize) -> Result<Vec<(String, usize)>, ErrorsJSL> {
1207    if r.slice(heap, 4)? != b"HEAP" {
1208        return Err(bad("HDF5: bad local heap"));
1209    }
1210    let heap_data = r.offset(heap + 8 + r.length_size * 2)? as usize;
1211    let mut out = Vec::new();
1212    let mut stack = vec![btree];
1213    let mut guard = 0;
1214    while let Some(node) = stack.pop() {
1215        guard += 1;
1216        if guard > 100_000 {
1217            return Err(bad("HDF5: group index too large"));
1218        }
1219        if r.slice(node, 4)? != b"TREE" {
1220            return Err(bad("HDF5: bad group B-tree node"));
1221        }
1222        let (level, used) = (r.uint(node + 5, 1)?, r.uint(node + 6, 2)? as usize);
1223        let mut p = node + 8 + 2 * r.offset_size + r.length_size; // after the first key
1224        let mut children = Vec::new();
1225        for _ in 0..used {
1226            children.push(r.offset(p)? as usize);
1227            p += r.offset_size + r.length_size;
1228        }
1229        if level > 0 {
1230            stack.extend(children.into_iter().rev());
1231            continue;
1232        }
1233        for child in children {
1234            if r.slice(child, 4)? != b"SNOD" {
1235                return Err(bad("HDF5: bad symbol table node"));
1236            }
1237            let count = r.uint(child + 6, 2)? as usize;
1238            let entry_size = 2 * r.offset_size + 8 + 16;
1239            for e in 0..count {
1240                let at = child + 8 + e * entry_size;
1241                let name_off = r.offset(at)? as usize;
1242                let header = r.offset(at + r.offset_size)? as usize;
1243                let name_bytes = r.slice(heap_data + name_off, 1)?;
1244                let _ = name_bytes;
1245                // The name is NUL-terminated in the heap's data segment.
1246                let tail = &r.b[(r.base + heap_data + name_off).min(r.b.len())..];
1247                let end = tail.iter().position(|&b| b == 0).ok_or_else(|| bad("HDF5: unterminated name in the local heap"))?;
1248                out.push((String::from_utf8_lossy(&tail[..end]).into_owned(), header));
1249            }
1250        }
1251    }
1252    Ok(out)
1253}
1254
1255/// A link message: `(name, address of the object header)` for hard links.
1256fn parse_link(data: &[u8], r: &Reader) -> Result<Option<(String, usize)>, ErrorsJSL> {
1257    let mut c = Cur { b: data, p: 0 };
1258    let _version = c.u(1)?;
1259    let flags = c.u(1)? as u8;
1260    let link_type = if flags & 8 != 0 { c.u(1)? } else { 0 };
1261    if flags & 4 != 0 {
1262        c.take(8)?; // creation order
1263    }
1264    if flags & 0x10 != 0 {
1265        c.take(1)?; // name encoding
1266    }
1267    let len_bytes = 1usize << (flags & 3);
1268    let name_len = c.u(len_bytes)? as usize;
1269    let name = String::from_utf8_lossy(c.take(name_len)?).into_owned();
1270    if link_type == 0 { Ok(Some((name, c.u(r.offset_size)? as usize))) } else { Ok(None) }
1271}
1272
1273// ------------------------------------------------------------------ dense storage (fractal heap)
1274
1275/// `⌊log₂ x⌋`.
1276fn log2_floor(x: usize) -> usize {
1277    (usize::BITS - 1 - x.max(1).leading_zeros()) as usize
1278}
1279
1280/// The number of bytes that HDF5 uses to encode a value up to `max`.
1281fn enc_size(max: usize) -> usize {
1282    (log2_floor(max) + 8) / 8
1283}
1284
1285/// A fractal heap, reduced to what reading managed objects needs: the direct blocks, by the offset
1286/// in the heap's address space at which each starts.
1287struct FractalHeap {
1288    offset_bytes: usize,
1289    length_bytes: usize,
1290    /// (heap offset of the block, file address, size)
1291    blocks: Vec<(usize, usize, usize)>,
1292}
1293
1294fn read_fractal_heap(r: &Reader, addr: usize) -> Result<FractalHeap, ErrorsJSL> {
1295    if r.slice(addr, 4)? != b"FRHP" {
1296        return Err(bad("HDF5: bad fractal heap header"));
1297    }
1298    let (o, l) = (r.offset_size, r.length_size);
1299    let mut c = Cur { b: r.slice(addr, 4 + 1 + 2 + 2 + 1 + 4 + 12 * l + 3 * o + 64)?, p: 5 };
1300    let _id_len = c.u(2)?;
1301    let filter_len = c.u(2)? as usize;
1302    let _flags = c.u(1)?;
1303    let max_managed = c.u(4)? as usize;
1304    c.take(l + o + l + o + 3 * l)?; // next huge id, huge B-tree, free space, free-space manager, managed space, allocated space, iterator offset
1305    let _managed_objects = c.u(l)?;
1306    c.take(4 * l)?; // huge objects (size, count), tiny objects (size, count)
1307    let width = c.u(2)? as usize;
1308    let start_size = c.u(l)? as usize;
1309    let max_direct = c.u(l)? as usize;
1310    let max_heap_bits = c.u(2)? as usize;
1311    let _start_rows = c.u(2)?;
1312    let root = c.u(o)?;
1313    let root_rows = c.u(2)? as usize;
1314    if filter_len > 0 {
1315        return Err(bad("HDF5: filtered fractal heaps are not supported"));
1316    }
1317    let offset_bytes = max_heap_bits.div_ceil(8);
1318    let length_bytes = enc_size(max_direct.min(max_managed));
1319    let mut blocks = Vec::new();
1320    if !r.undefined(root) {
1321        if root_rows == 0 {
1322            blocks.push((0, root as usize, start_size));
1323        } else {
1324            let first_row_bits = log2_floor(start_size) + log2_floor(width);
1325            let max_direct_rows = log2_floor(max_direct) - log2_floor(start_size) + 2;
1326            #[allow(clippy::too_many_arguments)]
1327            fn walk(r: &Reader, addr: usize, rows: usize, base: usize, width: usize, start_size: usize, max_direct_rows: usize, first_row_bits: usize, offset_bytes: usize, blocks: &mut Vec<(usize, usize, usize)>, depth: usize) -> Result<(), ErrorsJSL> {
1328                if depth > 16 || r.slice(addr, 4)? != b"FHIB" {
1329                    return Err(bad("HDF5: bad fractal heap indirect block"));
1330                }
1331                let mut p = addr + 4 + 1 + r.offset_size + offset_bytes;
1332                let mut offset = base;
1333                for row in 0..rows {
1334                    let size = if row == 0 { start_size } else { start_size << (row - 1) };
1335                    for _ in 0..width {
1336                        let child = r.offset(p)?;
1337                        p += r.offset_size;
1338                        if !r.undefined(child) {
1339                            if row < max_direct_rows {
1340                                blocks.push((offset, child as usize, size));
1341                            } else {
1342                                let child_rows = log2_floor(size) - first_row_bits + 1;
1343                                walk(r, child as usize, child_rows, offset, width, start_size, max_direct_rows, first_row_bits, offset_bytes, blocks, depth + 1)?;
1344                            }
1345                        }
1346                        offset += size;
1347                    }
1348                }
1349                Ok(())
1350            }
1351            walk(r, root as usize, root_rows, 0, width, start_size, max_direct_rows, first_row_bits, offset_bytes, &mut blocks, 0)?;
1352        }
1353    }
1354    blocks.sort_unstable();
1355    Ok(FractalHeap { offset_bytes, length_bytes, blocks })
1356}
1357
1358impl FractalHeap {
1359    /// The bytes of the managed object a heap ID names.
1360    fn object(&self, r: &Reader, id: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
1361        if id.is_empty() || (id[0] >> 4) & 3 != 0 {
1362            return Err(bad("HDF5: only managed fractal-heap objects are supported"));
1363        }
1364        let off = le(id.get(1..1 + self.offset_bytes).ok_or_else(|| bad("HDF5: short heap ID"))?) as usize;
1365        let len = le(id.get(1 + self.offset_bytes..1 + self.offset_bytes + self.length_bytes).ok_or_else(|| bad("HDF5: short heap ID"))?) as usize;
1366        let k = self.blocks.partition_point(|b| b.0 <= off).checked_sub(1).ok_or_else(|| bad("HDF5: a heap object outside every block"))?;
1367        let (start, addr, size) = self.blocks[k];
1368        if off + len > start + size {
1369            return Err(bad("HDF5: a heap object crosses its block"));
1370        }
1371        Ok(r.slice(addr + (off - start), len)?.to_vec())
1372    }
1373}
1374
1375/// The records of a version 2 B-tree (all of its leaves, in order).
1376fn btree2_records(r: &Reader, addr: usize) -> Result<Vec<Vec<u8>>, ErrorsJSL> {
1377    if r.slice(addr, 4)? != b"BTHD" {
1378        return Err(bad("HDF5: bad version 2 B-tree header"));
1379    }
1380    let (node_size, rec_size, depth) = (r.uint(addr + 6, 4)? as usize, r.uint(addr + 10, 2)? as usize, r.uint(addr + 12, 2)? as usize);
1381    let root = r.offset(addr + 16)? as usize;
1382    let root_n = r.uint(addr + 16 + r.offset_size, 2)? as usize;
1383    if root_n == 0 || r.undefined(root as u64) {
1384        return Ok(Vec::new());
1385    }
1386    // Sizes of the record counts in child pointers, from the maximum counts per level.
1387    let max_leaf = (node_size - 10) / rec_size;
1388    let nrec_bytes = enc_size(max_leaf);
1389    let mut max_nrec = vec![max_leaf];
1390    let mut cum = vec![max_leaf];
1391    for d in 1..=depth {
1392        let ptr = r.offset_size + nrec_bytes + if d > 1 { enc_size(cum[d - 1]) } else { 0 };
1393        let m = (node_size - 10 - ptr) / (rec_size + ptr);
1394        max_nrec.push(m);
1395        cum.push((m + 1) * cum[d - 1] + m);
1396    }
1397    #[allow(clippy::too_many_arguments)]
1398    fn node(r: &Reader, addr: usize, n: usize, depth: usize, rec_size: usize, nrec_bytes: usize, cum: &[usize], out: &mut Vec<Vec<u8>>) -> Result<(), ErrorsJSL> {
1399        let sig = r.slice(addr, 4)?;
1400        let recs = addr + 6;
1401        if depth == 0 {
1402            if sig != b"BTLF" {
1403                return Err(bad("HDF5: bad B-tree leaf"));
1404            }
1405            for k in 0..n {
1406                out.push(r.slice(recs + k * rec_size, rec_size)?.to_vec());
1407            }
1408            return Ok(());
1409        }
1410        if sig != b"BTIN" {
1411            return Err(bad("HDF5: bad B-tree internal node"));
1412        }
1413        let total_bytes = if depth > 1 { enc_size(cum[depth - 1]) } else { 0 };
1414        let ptr = r.offset_size + nrec_bytes + total_bytes;
1415        let ptrs = recs + n * rec_size;
1416        for k in 0..=n {
1417            let p = ptrs + k * ptr;
1418            let child = r.offset(p)? as usize;
1419            let cn = r.uint(p + r.offset_size, nrec_bytes)? as usize;
1420            node(r, child, cn, depth - 1, rec_size, nrec_bytes, cum, out)?;
1421            if k < n {
1422                out.push(r.slice(recs + k * rec_size, rec_size)?.to_vec());
1423            }
1424        }
1425        Ok(())
1426    }
1427    let mut out = Vec::new();
1428    node(r, root, root_n, depth, rec_size, nrec_bytes, &cum, &mut out)?;
1429    Ok(out)
1430}
1431
1432struct Loader<'a> {
1433    r: Reader<'a>,
1434    objects: HashMap<u64, H5Object>,
1435    names: HashMap<u64, String>,
1436    /// Addresses being loaded, against cycles.
1437    active: HashSet<usize>,
1438    count: usize,
1439}
1440
1441impl Loader<'_> {
1442    fn load(&mut self, addr: usize) -> Result<H5Object, ErrorsJSL> {
1443        if let Some(o) = self.objects.get(&(addr as u64)) {
1444            return Ok(o.clone());
1445        }
1446        if !self.active.insert(addr) {
1447            return Err(bad("HDF5: a group contains itself"));
1448        }
1449        self.count += 1;
1450        if self.count > 200_000 {
1451            return Err(bad("HDF5: too many objects"));
1452        }
1453        let messages = read_messages(&self.r, addr)?;
1454        let mut attributes = Vec::new();
1455        for m in messages.iter().filter(|m| m.kind == 0x0c) {
1456            attributes.push(read_attribute(&m.data, &self.r)?);
1457        }
1458        if let Some(m) = messages.iter().find(|m| m.kind == 0x15) {
1459            // Attribute info: dense storage when the fractal heap address is defined.
1460            let mut c = Cur { b: &m.data, p: 0 };
1461            let _v = c.u(1)?;
1462            let f = c.u(1)?;
1463            if f & 1 != 0 {
1464                c.take(2)?;
1465            }
1466            let (heap, index) = (c.u(self.r.offset_size)?, c.u(self.r.offset_size)?);
1467            if !self.r.undefined(heap) && !self.r.undefined(index) {
1468                let fh = read_fractal_heap(&self.r, heap as usize)?;
1469                for rec in btree2_records(&self.r, index as usize)? {
1470                    // Attribute name index records: heap ID (8 bytes), flags, creation order, hash.
1471                    let body = fh.object(&self.r, &rec[..8.min(rec.len())])?;
1472                    attributes.push(read_attribute(&body, &self.r)?);
1473                }
1474                attributes.sort_by(|x, y| x.0.cmp(&y.0));
1475            }
1476        }
1477        let object = if messages.iter().any(|m| m.kind == 0x11 || m.kind == 0x06 || m.kind == 0x02) && !messages.iter().any(|m| m.kind == 0x08) {
1478            let mut links: Vec<(String, usize)> = Vec::new();
1479            if let Some(m) = messages.iter().find(|m| m.kind == 0x11) {
1480                let mut c = Cur { b: &m.data, p: 0 };
1481                let btree = c.u(self.r.offset_size)? as usize;
1482                let heap = c.u(self.r.offset_size)? as usize;
1483                links = symbol_table(&self.r, btree, heap)?;
1484            }
1485            for m in messages.iter().filter(|m| m.kind == 0x06) {
1486                if let Some(l) = parse_link(&m.data, &self.r)? {
1487                    links.push(l);
1488                }
1489            }
1490            if let Some(m) = messages.iter().find(|m| m.kind == 0x02) {
1491                // Link info: dense link storage when the fractal heap address is defined.
1492                let mut c = Cur { b: &m.data, p: 0 };
1493                let _v = c.u(1)?;
1494                let f = c.u(1)?;
1495                if f & 1 != 0 {
1496                    c.take(8)?;
1497                }
1498                let (heap, index) = (c.u(self.r.offset_size)?, c.u(self.r.offset_size)?);
1499                if !self.r.undefined(heap) && !self.r.undefined(index) {
1500                    let fh = read_fractal_heap(&self.r, heap as usize)?;
1501                    let mut dense = Vec::new();
1502                    for rec in btree2_records(&self.r, index as usize)? {
1503                        // Link name index records: hash (4 bytes) and the heap ID.
1504                        let body = fh.object(&self.r, rec.get(4..).ok_or_else(|| bad("HDF5: short link record"))?)?;
1505                        if let Some(l) = parse_link(&body, &self.r)? {
1506                            dense.push(l);
1507                        }
1508                    }
1509                    dense.sort_by(|x, y| x.0.cmp(&y.0));
1510                    links.extend(dense);
1511                }
1512            }
1513            let mut members = Vec::new();
1514            for (name, header) in links {
1515                self.names.entry(header as u64).or_insert_with(|| name.clone());
1516                members.push((name, self.load(header)?));
1517            }
1518            H5Object::Group(H5Group { attributes, members })
1519        } else if messages.iter().any(|m| m.kind == 0x08) {
1520            {
1521                let max_shape = messages.iter().find(|m| m.kind == 0x01).and_then(|m| dataspace_max(&m.data, &self.r)).unwrap_or_default();
1522                H5Object::Dataset(H5Dataset { attributes, data: read_data(&self.r, &messages)?, max_shape })
1523            }
1524        } else {
1525            H5Object::Group(H5Group { attributes, members: Vec::new() })
1526        };
1527        self.active.remove(&addr);
1528        self.objects.insert(addr as u64, object.clone());
1529        Ok(object)
1530    }
1531}
1532
1533// ANCHOR: hdf5_decode
1534/// Parses an HDF5 file held in memory. The signature is searched for at offsets 0, 512, 1024, ...
1535/// (a user block, as in MATLAB v7.3 files, comes first).
1536pub fn hdf5_decode(bytes: &[u8]) -> Result<Hdf5File, ErrorsJSL> {
1537    const SIGNATURE: &[u8; 8] = b"\x89HDF\r\n\x1a\n";
1538    let mut base = 0usize;
1539    while bytes.get(base..base + 8) != Some(SIGNATURE) {
1540        base = if base == 0 { 512 } else { base * 2 };
1541        if base + 8 > bytes.len() {
1542            return Err(bad("HDF5: signature not found"));
1543        }
1544    }
1545    let version = *bytes.get(base + 8).ok_or_else(|| bad("HDF5: truncated superblock"))?;
1546    let (offset_size, length_size, root_addr) = match version {
1547        0 | 1 => {
1548            let (o, l) = (bytes.get(base + 13).copied().unwrap_or(0) as usize, bytes.get(base + 14).copied().unwrap_or(0) as usize);
1549            if !(o == 8 || o == 4) || !(l == 8 || l == 4) {
1550                return Err(bad("HDF5: unsupported sizes of offsets and lengths"));
1551            }
1552            // After the fixed part (and, in version 1, the indexed storage K): the four addresses,
1553            // then the root group's symbol table entry.
1554            let start = base + 24 + if version == 1 { 4 } else { 0 };
1555            let entry = start + 4 * o;
1556            let r = Reader { b: bytes, base, offset_size: o, length_size: l };
1557            let header = r.offset(entry - base + o)?;
1558            (o, l, header)
1559        }
1560        2 | 3 => {
1561            let (o, l) = (bytes.get(base + 9).copied().unwrap_or(0) as usize, bytes.get(base + 10).copied().unwrap_or(0) as usize);
1562            if !(o == 8 || o == 4) || !(l == 8 || l == 4) {
1563                return Err(bad("HDF5: unsupported sizes of offsets and lengths"));
1564            }
1565            let r = Reader { b: bytes, base, offset_size: o, length_size: l };
1566            let root = r.offset(12 + 3 * o)?;
1567            (o, l, root)
1568        }
1569        _ => return Err(bad("HDF5: unsupported superblock version")),
1570    };
1571    let r = Reader { b: bytes, base, offset_size, length_size };
1572    let mut loader = Loader { r, objects: HashMap::new(), names: HashMap::new(), active: HashSet::new(), count: 0 };
1573    let root = match loader.load(root_addr as usize)? {
1574        H5Object::Group(g) => g,
1575        H5Object::Dataset(_) => return Err(bad("HDF5: the root is not a group")),
1576    };
1577    Ok(Hdf5File { root, objects: loader.objects, names: loader.names })
1578}
1579// ANCHOR_END: hdf5_decode
1580
1581/// Reads an HDF5 file.
1582pub fn read_hdf5_file(path: impl AsRef<Path>) -> Result<Hdf5File, ErrorsJSL> {
1583    hdf5_decode(&std::fs::read(path).map_err(|_| ErrorsJSL::RuntimeError("could not read the HDF5 file"))?)
1584}
1585
1586// ------------------------------------------------------------------------------ MATLAB v7.3
1587
1588use crate::matlab::{MatClass, MatValue};
1589
1590fn attr_string(o: &H5Object, name: &str) -> Option<String> {
1591    o.attribute(name)?.to_strings()?.into_iter().next()
1592}
1593
1594fn attr_f64(o: &H5Object, name: &str) -> Option<f64> {
1595    o.attribute(name)?.to_f64()?.first().copied()
1596}
1597
1598fn mat_class(name: &str) -> Option<MatClass> {
1599    Some(match name {
1600        "double" => MatClass::Double,
1601        "single" => MatClass::Single,
1602        "int8" => MatClass::Int8,
1603        "uint8" => MatClass::Uint8,
1604        "int16" => MatClass::Int16,
1605        "uint16" => MatClass::Uint16,
1606        "int32" => MatClass::Int32,
1607        "uint32" => MatClass::Uint32,
1608        "int64" => MatClass::Int64,
1609        "uint64" => MatClass::Uint64,
1610        _ => return None,
1611    })
1612}
1613
1614/// The real and imaginary parts of a numeric dataset (complex values are compounds of `real` and
1615/// `imag`).
1616fn re_im(a: &H5Array) -> Result<(Vec<f64>, Option<Vec<f64>>), ErrorsJSL> {
1617    if let H5Type::Compound { .. } = a.dtype {
1618        let (mut re, mut im) = (Vec::with_capacity(a.values.len()), Vec::with_capacity(a.values.len()));
1619        for v in &a.values {
1620            let H5Value::Compound(m) = v else { return Err(bad("MAT-file (v7.3): bad complex element")) };
1621            let get = |n: &str| match m.iter().find(|(k, _)| k == n) {
1622                Some((_, H5Value::Float(f))) => Ok(*f),
1623                Some((_, H5Value::Int(i))) => Ok(*i as f64),
1624                Some((_, H5Value::UInt(u))) => Ok(*u as f64),
1625                _ => Err(bad("MAT-file (v7.3): bad complex element")),
1626            };
1627            re.push(get("real")?);
1628            im.push(get("imag")?);
1629        }
1630        Ok((re, Some(im)))
1631    } else {
1632        Ok((a.to_f64().ok_or_else(|| bad("MAT-file (v7.3): a numeric dataset of an unexpected type"))?, None))
1633    }
1634}
1635
1636/// MATLAB's dimensions: HDF5 stores the transpose, so they are the dataset's reversed.
1637fn mat_dims(shape: &[usize]) -> Vec<usize> {
1638    let mut d: Vec<usize> = shape.iter().rev().copied().collect();
1639    if d.len() == 1 {
1640        d.push(1);
1641    }
1642    if d.is_empty() {
1643        d = vec![1, 1];
1644    }
1645    d
1646}
1647
1648fn mat_convert(file: &Hdf5File, o: &H5Object, depth: usize) -> Result<MatValue, ErrorsJSL> {
1649    if depth > 64 {
1650        return Err(bad("MAT-file (v7.3): nesting too deep"));
1651    }
1652    let class = attr_string(o, "MATLAB_class").ok_or_else(|| bad("MAT-file (v7.3): an object without MATLAB_class"))?;
1653    match o {
1654        H5Object::Dataset(d) => {
1655            if attr_f64(o, "MATLAB_empty") == Some(1.0) {
1656                // The dataset holds the dimensions, in MATLAB's order.
1657                let dims: Vec<usize> = d.data.to_f64().unwrap_or_default().iter().map(|&x| x as usize).collect();
1658                return Ok(match class.as_str() {
1659                    "cell" => MatValue::Cell { dims, cells: Vec::new() },
1660                    "char" => MatValue::Char { dims, chars: Vec::new() },
1661                    "logical" => MatValue::Logical { dims, data: Vec::new() },
1662                    other => MatValue::Numeric { class: mat_class(other).ok_or_else(|| bad("MAT-file (v7.3): unsupported class"))?, dims, real: Vec::new(), imag: None },
1663                });
1664            }
1665            let dims = mat_dims(&d.data.shape);
1666            match class.as_str() {
1667                "char" => {
1668                    let chars = d.data.to_f64().ok_or_else(|| bad("MAT-file (v7.3): bad char data"))?.iter().map(|&c| char::from_u32(c as u32).unwrap_or('\u{fffd}')).collect();
1669                    Ok(MatValue::Char { dims, chars })
1670                }
1671                "logical" => Ok(MatValue::Logical { dims, data: d.data.to_f64().ok_or_else(|| bad("MAT-file (v7.3): bad logical data"))?.iter().map(|&x| x != 0.0).collect() }),
1672                "cell" => {
1673                    let mut cells = Vec::with_capacity(d.data.values.len());
1674                    for v in &d.data.values {
1675                        let H5Value::Reference(r) = v else { return Err(bad("MAT-file (v7.3): a cell element is not a reference")) };
1676                        let target = file.object_at(*r).ok_or_else(|| bad("MAT-file (v7.3): a dangling reference"))?;
1677                        cells.push(mat_convert(file, target, depth + 1)?);
1678                    }
1679                    Ok(MatValue::Cell { dims, cells })
1680                }
1681                other => {
1682                    let cls = mat_class(other).ok_or_else(|| bad("MAT-file (v7.3): unsupported class (function handles and objects are not read)"))?;
1683                    let (real, imag) = re_im(&d.data)?;
1684                    Ok(MatValue::Numeric { class: cls, dims, real, imag })
1685                }
1686            }
1687        }
1688        H5Object::Group(g) => {
1689            if let Some(nrows) = attr_f64(o, "MATLAB_sparse") {
1690                let field = |n: &str| match g.get(n) {
1691                    Some(H5Object::Dataset(d)) => Ok(&d.data),
1692                    _ => Err(bad("MAT-file (v7.3): a sparse matrix without data, ir or jc")),
1693                };
1694                let (real, imag) = re_im(field("data")?)?;
1695                let ir = field("ir")?.to_f64().unwrap_or_default().iter().map(|&x| x as usize).collect();
1696                let jc: Vec<usize> = field("jc")?.to_f64().unwrap_or_default().iter().map(|&x| x as usize).collect();
1697                return Ok(MatValue::Sparse { nrows: nrows as usize, ncols: jc.len().saturating_sub(1), row_indices: ir, col_ptr: jc, real, imag, logical: class == "logical" });
1698            }
1699            if class != "struct" {
1700                return Err(bad("MAT-file (v7.3): unsupported class (function handles and objects are not read)"));
1701            }
1702            // A scalar structure holds its values; a structure array holds, per field, a dataset of
1703            // references to the elements' values.
1704            let mut fields = Vec::new();
1705            let mut columns: Vec<Vec<MatValue>> = Vec::new();
1706            let mut dims = vec![1usize, 1];
1707            // MATLAB's own order of the fields is in the attribute MATLAB_fields (names as
1708            // sequences of character codes); the file's members are alphabetical.
1709            let mut ordered: Vec<(&String, &H5Object)> = g.members.iter().map(|(n, m)| (n, m)).collect();
1710            if let Some(attr) = o.attribute("MATLAB_fields") {
1711                let names: Vec<String> = attr
1712                    .values
1713                    .iter()
1714                    .filter_map(|v| match v {
1715                        H5Value::Sequence(codes) => Some(
1716                            codes
1717                                .iter()
1718                                .map(|c| match c {
1719                                    // MATLAB stores the name as characters (1-byte strings, as in
1720                                    // files written by MATLAB) or as character codes.
1721                                    H5Value::Str(t) => t.clone(),
1722                                    H5Value::UInt(u) => char::from_u32(*u as u32).map(String::from).unwrap_or_default(),
1723                                    H5Value::Int(i) => char::from_u32(*i as u32).map(String::from).unwrap_or_default(),
1724                                    _ => String::new(),
1725                                })
1726                                .collect::<String>(),
1727                        ),
1728                        _ => None,
1729                    })
1730                    .collect();
1731                ordered.sort_by_key(|(n, _)| names.iter().position(|x| x == *n).unwrap_or(usize::MAX));
1732            }
1733            for (name, member) in ordered {
1734                fields.push(name.clone());
1735                let is_array = matches!(member, H5Object::Dataset(d) if member.attribute("MATLAB_class").is_none() && d.data.dtype == H5Type::Reference);
1736                if is_array {
1737                    let H5Object::Dataset(d) = member else { unreachable!() };
1738                    dims = mat_dims(&d.data.shape);
1739                    let mut col = Vec::new();
1740                    for v in &d.data.values {
1741                        let H5Value::Reference(r) = v else { return Err(bad("MAT-file (v7.3): bad structure array field")) };
1742                        let target = file.object_at(*r).ok_or_else(|| bad("MAT-file (v7.3): a dangling reference"))?;
1743                        col.push(mat_convert(file, target, depth + 1)?);
1744                    }
1745                    columns.push(col);
1746                } else {
1747                    columns.push(vec![mat_convert(file, member, depth + 1)?]);
1748                }
1749            }
1750            let count = columns.first().map_or(1, Vec::len);
1751            let elements = (0..count).map(|i| columns.iter().map(|c| c[i].clone()).collect()).collect();
1752            Ok(MatValue::Struct { dims, fields, elements })
1753        }
1754    }
1755}
1756
1757// ANCHOR: mat73_decode
1758/// Reads a MATLAB v7.3 MAT-file (an HDF5 file with a 512-byte user block): the variables in the
1759/// order the file lists them (alphabetical), as the values [`crate::mat_decode`] gives for level 5.
1760/// Numeric, logical and character arrays (empty ones too), complex arrays, sparse matrices, cell
1761/// arrays and structures (scalar and arrays) are read; function handles, objects and `table`s are
1762/// reported as errors. The order of a structure's fields is MATLAB's (the attribute
1763/// `MATLAB_fields`) when the file has it, and the file's (alphabetical) otherwise.
1764pub fn mat73_decode(bytes: &[u8]) -> Result<Vec<(String, MatValue)>, ErrorsJSL> {
1765    let file = hdf5_decode(bytes)?;
1766    let mut out = Vec::new();
1767    for (name, o) in &file.root.members {
1768        if name == "#refs#" || name == "#subsystem#" {
1769            continue;
1770        }
1771        out.push((name.clone(), mat_convert(&file, o, 0)?));
1772    }
1773    Ok(out)
1774}
1775// ANCHOR_END: mat73_decode
1776
1777/// Reads a MATLAB v7.3 MAT-file.
1778pub fn read_mat73_file(path: impl AsRef<Path>) -> Result<Vec<(String, MatValue)>, ErrorsJSL> {
1779    mat73_decode(&std::fs::read(path).map_err(|_| ErrorsJSL::RuntimeError("could not read the MAT-file"))?)
1780}
1781
1782// ------------------------------------------------------------------------------ NetCDF-4
1783
1784use crate::netcdf::{NcValue, NcVariable, NetCdf};
1785
1786fn nc_value(a: &H5Array) -> Result<NcValue, ErrorsJSL> {
1787    Ok(match &a.dtype {
1788        H5Type::FixedString { .. } | H5Type::VarString => NcValue::Char(a.to_strings().unwrap_or_default().join("")),
1789        H5Type::Int { size: 1, signed: true, .. } => NcValue::Byte(a.to_f64().unwrap_or_default().iter().map(|&x| x as i8).collect()),
1790        H5Type::Int { size: 2, signed: true, .. } => NcValue::Short(a.to_f64().unwrap_or_default().iter().map(|&x| x as i16).collect()),
1791        H5Type::Int { size: 4, signed: true, .. } => NcValue::Int(a.to_f64().unwrap_or_default().iter().map(|&x| x as i32).collect()),
1792        H5Type::Float { size: 4, .. } => NcValue::Float(a.to_f64().unwrap_or_default().iter().map(|&x| x as f32).collect()),
1793        H5Type::Int { .. } | H5Type::Float { .. } | H5Type::Enum { .. } => NcValue::Double(a.to_f64().ok_or_else(|| bad("NetCDF-4: bad numeric data"))?),
1794        _ => return Err(bad("NetCDF-4: unsupported datatype")),
1795    })
1796}
1797
1798// ANCHOR: netcdf4_decode
1799/// Reads the root group of a NetCDF-4 file into the [`NetCdf`] of the classic model: dimensions
1800/// (the file's dimension scales), global attributes and variables with their attributes. Types
1801/// NetCDF-3 lacks (64-bit and unsigned integers, enumerations) are widened to `f64`; subgroups and
1802/// user-defined types are not represented (variables in subgroups are listed under the path
1803/// `group/name`). An unlimited dimension has length `None`, and `numrecs` is its current length.
1804pub fn netcdf4_decode(bytes: &[u8]) -> Result<NetCdf, ErrorsJSL> {
1805    let file = hdf5_decode(bytes)?;
1806    const INTERNAL: [&str; 6] = ["CLASS", "NAME", "DIMENSION_LIST", "REFERENCE_LIST", "_Netcdf4Dimid", "_Netcdf4Coordinates"];
1807    let mut nc = NetCdf::new();
1808    nc.version = 4;
1809    // Dimension scales, in file order, by the address of their headers.
1810    let mut scale_names = HashSet::new();
1811    for (name, o) in &file.root.members {
1812        if let H5Object::Dataset(d) = o
1813            && attr_string(o, "CLASS").as_deref() == Some("DIMENSION_SCALE")
1814        {
1815            let placeholder = attr_string(o, "NAME").is_some_and(|n| n.starts_with("This is a netCDF dimension but not a netCDF variable"));
1816            let length = d.data.shape.first().copied().unwrap_or(1);
1817            let unlimited = d.max_shape.first() == Some(&None);
1818            if unlimited {
1819                nc.numrecs = nc.numrecs.max(length);
1820            }
1821            nc.dimensions.push((name.clone(), if unlimited { None } else { Some(length) }));
1822            if placeholder {
1823                scale_names.insert(name.clone());
1824            }
1825        }
1826    }
1827    for (name, a) in &file.root.attributes {
1828        if !INTERNAL.contains(&name.as_str()) && name != "_NCProperties" {
1829            nc.attributes.push((name.clone(), nc_value(a)?));
1830        }
1831    }
1832    let mut flat: Vec<(String, &H5Object)> = Vec::new();
1833    fn collect<'a>(g: &'a H5Group, prefix: &str, out: &mut Vec<(String, &'a H5Object)>) {
1834        for (name, o) in &g.members {
1835            match o {
1836                H5Object::Dataset(_) => out.push((format!("{prefix}{name}"), o)),
1837                H5Object::Group(sub) => collect(sub, &format!("{prefix}{name}/"), out),
1838            }
1839        }
1840    }
1841    collect(&file.root, "", &mut flat);
1842    for (name, o) in &flat {
1843        let H5Object::Dataset(d) = o else { continue };
1844        if scale_names.contains(name) {
1845            continue;
1846        }
1847        let dims: Vec<usize> = match o.attribute("DIMENSION_LIST") {
1848            Some(list) => list
1849                .values
1850                .iter()
1851                .map(|v| match v {
1852                    H5Value::Sequence(s) => match s.first() {
1853                        Some(H5Value::Reference(r)) => file.name_of(*r).and_then(|n| nc.dimensions.iter().position(|(dn, _)| dn == n)).ok_or_else(|| bad("NetCDF-4: a dimension list names an unknown dimension")),
1854                        _ => Err(bad("NetCDF-4: an empty dimension list entry")),
1855                    },
1856                    _ => Err(bad("NetCDF-4: a malformed dimension list")),
1857                })
1858                .collect::<Result<_, _>>()?,
1859            None if attr_string(o, "CLASS").as_deref() == Some("DIMENSION_SCALE") => vec![nc.dimensions.iter().position(|(dn, _)| dn == name).unwrap_or(0)],
1860            None => Vec::new(),
1861        };
1862        let mut var = NcVariable::new(name, dims, nc_value(&d.data)?);
1863        for (an, a) in o.attributes() {
1864            if !INTERNAL.contains(&an.as_str()) {
1865                var.attributes.push((an.clone(), nc_value(a)?));
1866            }
1867        }
1868        nc.variables.push(var);
1869    }
1870    Ok(nc)
1871}
1872// ANCHOR_END: netcdf4_decode
1873
1874/// Reads a NetCDF-4 file.
1875pub fn read_netcdf4_file(path: impl AsRef<Path>) -> Result<NetCdf, ErrorsJSL> {
1876    netcdf4_decode(&std::fs::read(path).map_err(|_| ErrorsJSL::RuntimeError("could not read the NetCDF-4 file"))?)
1877}
1878
1879#[cfg(test)]
1880mod tests {
1881    use super::*;
1882
1883    #[test]
1884    fn layout_version_5_is_version_4_with_wider_dimension_sizes() {
1885        let r = Reader { b: &[], base: 0, offset_size: 8, length_size: 8 };
1886        // From a file written by HDF5 2.0: one 2^33-element chunk (five bytes per dimension), single-chunk index.
1887        let msg = [5u8, 2, 0, 2, 5, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 1, 255, 255, 255, 255, 255, 255, 255, 255];
1888        match parse_layout(&msg, &r).unwrap() {
1889            Layout::ChunkedV4 { index, chunk, addr, .. } => {
1890                assert_eq!((index, chunk), (1, vec![1usize << 33, 1]));
1891                assert_eq!(addr, u64::MAX);
1892            }
1893            other => panic!("{other:?}"),
1894        }
1895        // Version 6 does not exist.
1896        let mut bad = msg;
1897        bad[0] = 6;
1898        assert!(parse_layout(&bad, &r).is_err());
1899    }
1900
1901    #[test]
1902    fn lzf_literals_back_references_and_corrupt_input() {
1903        assert_eq!(lzf_decompress(&[2, b'a', b'b', b'c'], 3).unwrap(), b"abc");
1904        // A literal 'a', then a copy of length 3 at distance 1 (the source overlaps the output).
1905        assert_eq!(lzf_decompress(&[0, b'a', 0x20, 0], 4).unwrap(), b"aaaa");
1906        // A copy before the start, a literal run past the input, and the wrong output length.
1907        assert!(lzf_decompress(&[0x20, 5], 3).is_err());
1908        assert!(lzf_decompress(&[5, b'a'], 6).is_err());
1909        assert!(lzf_decompress(&[0, b'a'], 2).is_err());
1910    }
1911}