Skip to main content

lib_jsl_file_io/
npz.rs

1//! NumPy `.npz` archives (`numpy.savez`, `numpy.savez_compressed` and `numpy.load`).
2//!
3//! An `.npz` file is a ZIP archive whose members are `.npy` files named `<name>.npy`. This module
4//! reads and writes the ZIP container itself:
5//!
6//! - The reader finds the end-of-central-directory record, and reads each member's name, method,
7//!   sizes, CRC-32 and offset from the *central directory*, not from the local headers, which may
8//!   hold zeros when a data descriptor follows the data. ZIP64 (sizes and offsets above 4 GiB,
9//!   or 65 535 members and more) is read. Members may be stored (method 0) or deflated (8); each
10//!   is checked against its CRC-32 and its declared size.
11//! - The writer stores (`savez`) or deflates (`savez_compressed`) each member, and uses ZIP64
12//!   records exactly when a size or an offset needs them.
13//! - Safety: encrypted members, other compression methods, path-traversal and duplicate names,
14//!   truncated archives, size and CRC mismatches and decompression bombs are errors, never panics.
15//!   Nothing is written to the file system by name.
16//!
17//! See the book entry [Data files](https://jwkunz.github.io/lib_jsl/book/foundations/data-files.html#numpy-npz).
18
19use crate::deflate::{deflate, inflate_limited};
20use crate::npy::{NpyArray, npy_decode, npy_encode};
21use crate::png::crc32;
22use lib_jsl_core::ErrorsJSL;
23use std::collections::HashSet;
24use std::path::Path;
25
26fn bad(msg: &'static str) -> ErrorsJSL {
27    ErrorsJSL::RuntimeError(msg)
28}
29
30const SIG_LOCAL: u32 = 0x0403_4b50;
31const SIG_CENTRAL: u32 = 0x0201_4b50;
32const SIG_EOCD: u32 = 0x0605_4b50;
33const SIG_EOCD64: u32 = 0x0606_4b50;
34const SIG_LOCATOR64: u32 = 0x0706_4b50;
35const U32_MAX: u64 = 0xFFFF_FFFF;
36const U16_MAX: usize = 0xFFFF;
37
38/// The largest member the reader will expand (a guard against decompression bombs).
39const MAX_MEMBER: u64 = 1 << 36;
40
41fn u16_at(b: &[u8], p: usize) -> Result<u16, ErrorsJSL> {
42    b.get(p..p + 2).map(|s| u16::from_le_bytes([s[0], s[1]])).ok_or_else(|| bad("Truncated ZIP archive."))
43}
44
45fn u32_at(b: &[u8], p: usize) -> Result<u32, ErrorsJSL> {
46    b.get(p..p + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])).ok_or_else(|| bad("Truncated ZIP archive."))
47}
48
49fn u64_at(b: &[u8], p: usize) -> Result<u64, ErrorsJSL> {
50    b.get(p..p + 8).map(|s| u64::from_le_bytes(s.try_into().expect("8 bytes"))).ok_or_else(|| bad("Truncated ZIP archive."))
51}
52
53/// A member's name must stay inside the archive: not absolute, no `..` or drive component, no
54/// backslashes or NULs.
55fn safe_name(name: &str) -> bool {
56    !name.is_empty()
57        && !name.contains('\0')
58        && !name.contains('\\')
59        && !name.starts_with('/')
60        && !name.split('/').any(|c| c == ".." || (c.len() >= 2 && c.as_bytes()[1] == b':' && c.as_bytes()[0].is_ascii_alphabetic()))
61}
62
63#[derive(Clone, Debug)]
64struct Entry {
65    /// The name as stored, for example `arr_0.npy`.
66    name: String,
67    method: u16,
68    crc: u32,
69    compressed: u64,
70    size: u64,
71    offset: u64,
72}
73
74// ANCHOR: zip_read
75/// A parsed `.npz` archive, borrowing its bytes. Members are decoded on demand.
76#[derive(Clone, Debug)]
77pub struct NpzArchive<'a> {
78    bytes: &'a [u8],
79    entries: Vec<Entry>,
80}
81
82impl<'a> NpzArchive<'a> {
83    /// Reads the central directory of a ZIP archive, validating every member's name.
84    pub fn new(bytes: &'a [u8]) -> Result<Self, ErrorsJSL> {
85        let len = bytes.len();
86        if len < 22 {
87            return Err(bad("Not a ZIP archive."));
88        }
89        // The end-of-central-directory record: the last 22 + comment bytes.
90        let eocd = (len.saturating_sub(22 + U16_MAX)..=len - 22)
91            .rev()
92            .find(|&i| u32_at(bytes, i).ok() == Some(SIG_EOCD) && u16_at(bytes, i + 20).ok().is_some_and(|c| i + 22 + c as usize == len))
93            .ok_or_else(|| bad("Not a ZIP archive: no end-of-central-directory record."))?;
94        let (disk, cd_disk) = (u16_at(bytes, eocd + 4)?, u16_at(bytes, eocd + 6)?);
95        let mut total = u16_at(bytes, eocd + 10)? as u64;
96        let mut cd_size = u32_at(bytes, eocd + 12)? as u64;
97        let mut cd_offset = u32_at(bytes, eocd + 16)? as u64;
98        if total == U16_MAX as u64 || cd_size == U32_MAX || cd_offset == U32_MAX {
99            // ZIP64: the locator sits just before the end record and points at the ZIP64 record.
100            let loc = eocd.checked_sub(20).filter(|&l| u32_at(bytes, l).ok() == Some(SIG_LOCATOR64));
101            if let Some(loc) = loc {
102                let z = usize::try_from(u64_at(bytes, loc + 8)?).map_err(|_| bad("ZIP64 offset out of range."))?;
103                if u32_at(bytes, z)? != SIG_EOCD64 {
104                    return Err(bad("Corrupt ZIP64 end-of-central-directory record."));
105                }
106                total = u64_at(bytes, z + 32)?;
107                cd_size = u64_at(bytes, z + 40)?;
108                cd_offset = u64_at(bytes, z + 48)?;
109            }
110        } else if disk != 0 || cd_disk != 0 {
111            return Err(bad("Multi-volume ZIP archives are not supported."));
112        }
113        let cd_start = usize::try_from(cd_offset).map_err(|_| bad("ZIP offset out of range."))?;
114        let cd_end = cd_offset.checked_add(cd_size).and_then(|e| usize::try_from(e).ok()).filter(|&e| e <= len).ok_or_else(|| bad("The central directory lies outside the archive."))?;
115        if total > (cd_end.saturating_sub(cd_start) / 46) as u64 {
116            return Err(bad("The central directory is smaller than its member count."));
117        }
118        let mut entries = Vec::with_capacity(total as usize);
119        let mut seen = HashSet::new();
120        let mut p = cd_start;
121        for _ in 0..total {
122            if u32_at(bytes, p)? != SIG_CENTRAL || p + 46 > cd_end {
123                return Err(bad("Corrupt ZIP central directory."));
124            }
125            let flags = u16_at(bytes, p + 8)?;
126            let method = u16_at(bytes, p + 10)?;
127            let crc = u32_at(bytes, p + 16)?;
128            let (mut compressed, mut size) = (u32_at(bytes, p + 20)? as u64, u32_at(bytes, p + 24)? as u64);
129            let (nlen, elen, clen) = (u16_at(bytes, p + 28)? as usize, u16_at(bytes, p + 30)? as usize, u16_at(bytes, p + 32)? as usize);
130            let mut offset = u32_at(bytes, p + 42)? as u64;
131            let name_end = p + 46 + nlen;
132            let extra_end = name_end + elen;
133            if extra_end + clen > cd_end {
134                return Err(bad("Corrupt ZIP central directory."));
135            }
136            // The ZIP64 extra field holds, in order, those of size, compressed size and offset
137            // that are 0xFFFFFFFF in the fixed fields.
138            let extra = &bytes[name_end..extra_end];
139            let mut q = 0;
140            while q + 4 <= extra.len() {
141                let (id, sz) = (u16_at(extra, q)?, u16_at(extra, q + 2)? as usize);
142                let body = extra.get(q + 4..q + 4 + sz).ok_or_else(|| bad("Corrupt ZIP extra field."))?;
143                if id == 1 {
144                    let mut r = 0;
145                    for field in [&mut size, &mut compressed, &mut offset] {
146                        if *field == U32_MAX {
147                            *field = u64_at(body, r)?;
148                            r += 8;
149                        }
150                    }
151                }
152                q += 4 + sz;
153            }
154            let raw = &bytes[p + 46..name_end];
155            let name = if flags & 0x800 != 0 { std::str::from_utf8(raw).map_err(|_| bad("A ZIP member name is not valid UTF-8."))?.to_string() } else { raw.iter().map(|&c| c as char).collect() };
156            p = extra_end + clen;
157            if flags & 0x41 != 0 {
158                return Err(bad("Encrypted ZIP members are not supported."));
159            }
160            if name.ends_with('/') {
161                continue; // a directory entry
162            }
163            if !safe_name(&name) {
164                return Err(bad("A ZIP member name would leave the archive (absolute path, `..`, backslash)."));
165            }
166            if !seen.insert(name.clone()) {
167                return Err(bad("The ZIP archive has two members with the same name."));
168            }
169            entries.push(Entry { name, method, crc, compressed, size, offset });
170        }
171        Ok(NpzArchive { bytes, entries })
172    }
173
174    /// The member names, with `.npy` removed as `numpy.load` does.
175    pub fn names(&self) -> Vec<String> {
176        self.entries.iter().map(|e| e.name.strip_suffix(".npy").unwrap_or(&e.name).to_string()).collect()
177    }
178
179    /// The number of members.
180    pub fn len(&self) -> usize {
181        self.entries.len()
182    }
183
184    /// Whether the archive has no members.
185    pub fn is_empty(&self) -> bool {
186        self.entries.is_empty()
187    }
188
189    /// Whether a member of this name exists (with or without `.npy`).
190    pub fn contains(&self, name: &str) -> bool {
191        self.find(name).is_some()
192    }
193
194    fn find(&self, name: &str) -> Option<&Entry> {
195        self.entries.iter().find(|e| e.name == name || e.name.strip_suffix(".npy") == Some(name))
196    }
197
198    /// The bytes of a member, expanded and checked against its CRC-32 and size.
199    pub fn raw(&self, name: &str) -> Result<Vec<u8>, ErrorsJSL> {
200        let e = self.find(name).ok_or_else(|| bad("No such member in the archive."))?;
201        let off = usize::try_from(e.offset).map_err(|_| bad("ZIP offset out of range."))?;
202        if u32_at(self.bytes, off)? != SIG_LOCAL {
203            return Err(bad("Corrupt ZIP local header."));
204        }
205        let (nlen, elen) = (u16_at(self.bytes, off + 26)? as usize, u16_at(self.bytes, off + 28)? as usize);
206        let start = off + 30 + nlen + elen;
207        let end = e.compressed.checked_add(start as u64).and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("ZIP size out of range."))?;
208        let data = self.bytes.get(start..end).ok_or_else(|| bad("Truncated ZIP member."))?;
209        if e.size > MAX_MEMBER {
210            return Err(bad("A ZIP member is larger than the size limit."));
211        }
212        let out = match e.method {
213            0 => {
214                if e.compressed != e.size {
215                    return Err(bad("A stored ZIP member's sizes disagree."));
216                }
217                data.to_vec()
218            }
219            8 => inflate_limited(data, e.size as usize)?,
220            _ => return Err(bad("Unsupported ZIP compression method (only stored and deflate).")),
221        };
222        if out.len() as u64 != e.size {
223            return Err(bad("A ZIP member's size differs from its directory entry."));
224        }
225        if crc32(&[&out]) != e.crc {
226            return Err(bad("ZIP member CRC-32 mismatch."));
227        }
228        Ok(out)
229    }
230
231    /// The array stored in a member (the name with or without `.npy`).
232    pub fn get(&self, name: &str) -> Result<NpyArray, ErrorsJSL> {
233        npy_decode(&self.raw(name)?)
234    }
235}
236// ANCHOR_END: zip_read
237
238/// Reads every `.npy` member of an `.npz` archive, as `(name, array)` pairs in archive order with
239/// `.npy` removed from the names. Members of other names are skipped.
240pub fn npz_decode(bytes: &[u8]) -> Result<Vec<(String, NpyArray)>, ErrorsJSL> {
241    let archive = NpzArchive::new(bytes)?;
242    archive.entries.iter().filter(|e| e.name.ends_with(".npy")).map(|e| Ok((e.name.trim_end_matches(".npy").to_string(), archive.get(&e.name)?))).collect()
243}
244
245fn valid_member_name(name: &str) -> bool {
246    safe_name(name) && !name.contains('/') && !name.ends_with(".npy")
247}
248
249struct Member {
250    name: String,
251    crc: u32,
252    method: u16,
253    data: Vec<u8>,
254    size: u64,
255}
256
257fn write_zip(members: &[(String, Vec<u8>)], compressed: bool, force_zip64: bool) -> Result<Vec<u8>, ErrorsJSL> {
258    let parts: Vec<Member> = members
259        .iter()
260        .map(|(name, raw)| {
261            let data = if compressed { deflate(raw, 6) } else { raw.clone() };
262            Member { name: name.clone(), crc: crc32(&[raw]), method: if compressed { 8 } else { 0 }, data, size: raw.len() as u64 }
263        })
264        .collect();
265    let mut out: Vec<u8> = Vec::new();
266    let mut offsets = Vec::with_capacity(parts.len());
267    let mut big = Vec::with_capacity(parts.len());
268    for m in &parts {
269        offsets.push(out.len() as u64);
270        let zip64 = force_zip64 || m.size >= U32_MAX || m.data.len() as u64 >= U32_MAX;
271        big.push(zip64);
272        let flags: u16 = if m.name.is_ascii() { 0 } else { 0x800 };
273        out.extend(SIG_LOCAL.to_le_bytes());
274        out.extend((if zip64 { 45u16 } else if compressed { 20 } else { 10 }).to_le_bytes());
275        out.extend(flags.to_le_bytes());
276        out.extend(m.method.to_le_bytes());
277        out.extend(0u16.to_le_bytes()); // time
278        out.extend(0x21u16.to_le_bytes()); // date: 1980-01-01
279        out.extend(m.crc.to_le_bytes());
280        if zip64 {
281            out.extend((U32_MAX as u32).to_le_bytes());
282            out.extend((U32_MAX as u32).to_le_bytes());
283        } else {
284            out.extend((m.data.len() as u32).to_le_bytes());
285            out.extend((m.size as u32).to_le_bytes());
286        }
287        out.extend((m.name.len() as u16).to_le_bytes());
288        out.extend((if zip64 { 20u16 } else { 0 }).to_le_bytes());
289        out.extend(m.name.as_bytes());
290        if zip64 {
291            out.extend(1u16.to_le_bytes());
292            out.extend(16u16.to_le_bytes());
293            out.extend(m.size.to_le_bytes());
294            out.extend((m.data.len() as u64).to_le_bytes());
295        }
296        out.extend(&m.data);
297    }
298    let cd_start = out.len() as u64;
299    for (i, m) in parts.iter().enumerate() {
300        let off_big = force_zip64 || offsets[i] >= U32_MAX;
301        let flags: u16 = if m.name.is_ascii() { 0 } else { 0x800 };
302        // The ZIP64 extra field holds, in order, those of size, compressed size and offset that
303        // are written as 0xFFFFFFFF in the fixed fields.
304        let mut extra = Vec::new();
305        let (size32, comp32) = if big[i] { (U32_MAX as u32, U32_MAX as u32) } else { (m.size as u32, m.data.len() as u32) };
306        if big[i] {
307            extra.extend(m.size.to_le_bytes());
308            extra.extend((m.data.len() as u64).to_le_bytes());
309        }
310        if off_big {
311            extra.extend(offsets[i].to_le_bytes());
312        }
313        let needed: u16 = if big[i] || off_big { 45 } else if compressed { 20 } else { 10 };
314        out.extend(SIG_CENTRAL.to_le_bytes());
315        out.extend(needed.max(20).to_le_bytes()); // version made by
316        out.extend(needed.to_le_bytes());
317        out.extend(flags.to_le_bytes());
318        out.extend(m.method.to_le_bytes());
319        out.extend(0u16.to_le_bytes());
320        out.extend(0x21u16.to_le_bytes());
321        out.extend(m.crc.to_le_bytes());
322        out.extend(comp32.to_le_bytes());
323        out.extend(size32.to_le_bytes());
324        out.extend((m.name.len() as u16).to_le_bytes());
325        out.extend((if extra.is_empty() { 0u16 } else { extra.len() as u16 + 4 }).to_le_bytes());
326        out.extend(0u16.to_le_bytes()); // comment
327        out.extend(0u16.to_le_bytes()); // disk
328        out.extend(0u16.to_le_bytes()); // internal attributes
329        out.extend(0u32.to_le_bytes()); // external attributes
330        out.extend((if off_big { U32_MAX as u32 } else { offsets[i] as u32 }).to_le_bytes());
331        out.extend(m.name.as_bytes());
332        if !extra.is_empty() {
333            out.extend(1u16.to_le_bytes());
334            out.extend((extra.len() as u16).to_le_bytes());
335            out.extend(&extra);
336        }
337    }
338    let cd_size = out.len() as u64 - cd_start;
339    let n = parts.len();
340    let zip64_end = force_zip64 || n >= U16_MAX || cd_start >= U32_MAX || cd_size >= U32_MAX;
341    if zip64_end {
342        let z = out.len() as u64;
343        out.extend(SIG_EOCD64.to_le_bytes());
344        out.extend(44u64.to_le_bytes());
345        out.extend(45u16.to_le_bytes());
346        out.extend(45u16.to_le_bytes());
347        out.extend(0u32.to_le_bytes());
348        out.extend(0u32.to_le_bytes());
349        out.extend((n as u64).to_le_bytes());
350        out.extend((n as u64).to_le_bytes());
351        out.extend(cd_size.to_le_bytes());
352        out.extend(cd_start.to_le_bytes());
353        out.extend(SIG_LOCATOR64.to_le_bytes());
354        out.extend(0u32.to_le_bytes());
355        out.extend(z.to_le_bytes());
356        out.extend(1u32.to_le_bytes());
357    }
358    out.extend(SIG_EOCD.to_le_bytes());
359    out.extend(0u16.to_le_bytes());
360    out.extend(0u16.to_le_bytes());
361    out.extend((n.min(U16_MAX) as u16).to_le_bytes());
362    out.extend((n.min(U16_MAX) as u16).to_le_bytes());
363    out.extend((if zip64_end { U32_MAX as u32 } else { cd_size as u32 }).to_le_bytes());
364    out.extend((if zip64_end { U32_MAX as u32 } else { cd_start as u32 }).to_le_bytes());
365    out.extend(0u16.to_le_bytes());
366    Ok(out)
367}
368
369fn encode(arrays: &[(&str, &NpyArray)], compressed: bool, force_zip64: bool) -> Result<Vec<u8>, ErrorsJSL> {
370    let mut seen = HashSet::new();
371    let mut members = Vec::with_capacity(arrays.len());
372    for (name, array) in arrays {
373        if !valid_member_name(name) {
374            return Err(ErrorsJSL::InvalidInputRange("An .npz member name must be non-empty, without `/`, `\\`, `..` or a trailing `.npy`."));
375        }
376        if !seen.insert(*name) {
377            return Err(ErrorsJSL::InvalidInputRange("Two .npz members have the same name."));
378        }
379        members.push((format!("{name}.npy"), npy_encode(array)?));
380    }
381    write_zip(&members, compressed, force_zip64)
382}
383
384// ANCHOR: savez
385/// Builds an `.npz` archive from named arrays (`numpy.savez`, or `numpy.savez_compressed` when
386/// `compressed`): each array becomes the member `<name>.npy`. Names must be non-empty, distinct,
387/// and free of `/`, `\`, `..` and a trailing `.npy`. Sizes and offsets that do not fit 32 bits get
388/// ZIP64 records.
389pub fn npz_encode(arrays: &[(&str, &NpyArray)], compressed: bool) -> Result<Vec<u8>, ErrorsJSL> {
390    encode(arrays, compressed, false)
391}
392// ANCHOR_END: savez
393
394/// As [`npz_encode`], for arrays without names: they are called `arr_0`, `arr_1`, ... as
395/// `numpy.savez` does.
396pub fn npz_encode_positional(arrays: &[&NpyArray], compressed: bool) -> Result<Vec<u8>, ErrorsJSL> {
397    let names: Vec<String> = (0..arrays.len()).map(|i| format!("arr_{i}")).collect();
398    let named: Vec<(&str, &NpyArray)> = names.iter().map(String::as_str).zip(arrays.iter().copied()).collect();
399    npz_encode(&named, compressed)
400}
401
402/// As [`npz_encode`], with ZIP64 records on every member and on the end of the directory even
403/// though the sizes do not need them (what NumPy's `savez` does for the local headers). Mainly
404/// for testing readers.
405pub fn npz_encode_zip64(arrays: &[(&str, &NpyArray)], compressed: bool) -> Result<Vec<u8>, ErrorsJSL> {
406    encode(arrays, compressed, true)
407}
408
409/// Reads an `.npz` file.
410pub fn read_npz_file(path: impl AsRef<Path>) -> Result<Vec<(String, NpyArray)>, ErrorsJSL> {
411    npz_decode(&std::fs::read(path).map_err(|_| bad("Could not read the .npz file."))?)
412}
413
414/// Writes an `.npz` file.
415pub fn write_npz_file(path: impl AsRef<Path>, arrays: &[(&str, &NpyArray)], compressed: bool) -> Result<(), ErrorsJSL> {
416    std::fs::write(path, npz_encode(arrays, compressed)?).map_err(|_| bad("Could not write the .npz file."))
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422    use crate::npy::NpyData;
423    use num_complex::Complex;
424
425    fn sample() -> Vec<(String, NpyArray)> {
426        vec![
427            ("a".into(), NpyArray::new(vec![2, 3], NpyData::F64(vec![-2.0, -0.5, 1.0, 2.5, 4.0, 5.5])).unwrap()),
428            ("b".into(), NpyArray::new(vec![4], NpyData::I16(vec![1, -2, 300, -400])).unwrap()),
429            ("flags".into(), NpyArray::new(vec![3], NpyData::Bool(vec![true, false, true])).unwrap()),
430            ("z".into(), NpyArray::new(vec![2], NpyData::C128(vec![Complex::new(1.0, 2.0), Complex::new(0.0, -0.5)])).unwrap()),
431            ("scalar".into(), NpyArray::new(vec![], NpyData::U8(vec![7])).unwrap()),
432            ("empty".into(), NpyArray::new(vec![0, 4], NpyData::F32(vec![])).unwrap()),
433            ("big".into(), NpyArray::new(vec![5000], NpyData::F64((0..5000).map(|i| (i % 17) as f64).collect())).unwrap()),
434        ]
435    }
436
437    fn refs(v: &[(String, NpyArray)]) -> Vec<(&str, &NpyArray)> {
438        v.iter().map(|(n, a)| (n.as_str(), a)).collect()
439    }
440
441    #[test]
442    fn round_trips_stored_compressed_and_zip64() {
443        let arrays = sample();
444        for (compressed, zip64) in [(false, false), (true, false), (false, true), (true, true)] {
445            let bytes = if zip64 { npz_encode_zip64(&refs(&arrays), compressed) } else { npz_encode(&refs(&arrays), compressed) }.unwrap();
446            let back = npz_decode(&bytes).unwrap();
447            assert_eq!(back, arrays, "compressed = {compressed}, zip64 = {zip64}");
448            let archive = NpzArchive::new(&bytes).unwrap();
449            assert_eq!(archive.len(), 7);
450            assert!(archive.contains("a") && archive.contains("a.npy") && !archive.contains("q"));
451            assert_eq!(archive.get("b").unwrap(), arrays[1].1);
452            assert!(archive.get("missing").is_err());
453        }
454        let stored = npz_encode(&refs(&arrays), false).unwrap();
455        let deflated = npz_encode(&refs(&arrays), true).unwrap();
456        assert!(deflated.len() < stored.len() - 20000, "the compressible array shrinks: {} vs {}", deflated.len(), stored.len());
457    }
458
459    #[test]
460    fn positional_names_follow_numpy() {
461        let a = &sample()[0].1;
462        let b = &sample()[1].1;
463        let bytes = npz_encode_positional(&[a, b], false).unwrap();
464        let names: Vec<String> = npz_decode(&bytes).unwrap().into_iter().map(|(n, _)| n).collect();
465        assert_eq!(names, ["arr_0", "arr_1"]);
466    }
467
468    #[test]
469    fn empty_archive_and_name_rules() {
470        let bytes = npz_encode(&[], false).unwrap();
471        assert!(NpzArchive::new(&bytes).unwrap().is_empty());
472        let a = &sample()[0].1;
473        for bad_name in ["", "a/b", "..", "x\\y", "has.npy", "nul\0"] {
474            assert!(npz_encode(&[(bad_name, a)], false).is_err(), "{bad_name:?}");
475        }
476        assert!(npz_encode(&[("a", a), ("a", a)], false).is_err());
477        assert!(npz_encode(&[("tëst", a)], false).is_ok());
478        assert_eq!(npz_decode(&npz_encode(&[("tëst", a)], true).unwrap()).unwrap()[0].0, "tëst");
479    }
480
481    fn raw_zip(names: &[&str]) -> Vec<u8> {
482        let a = npy_encode(&sample()[1].1).unwrap();
483        write_zip(&names.iter().map(|n| (n.to_string(), a.clone())).collect::<Vec<_>>(), false, false).unwrap()
484    }
485
486    #[test]
487    fn dangerous_names_are_refused() {
488        for name in ["../evil.npy", "/etc/passwd.npy", "a/../../b.npy", "c:/x.npy", "back\\slash.npy"] {
489            assert!(NpzArchive::new(&raw_zip(&[name])).is_err(), "{name}");
490        }
491        assert!(NpzArchive::new(&raw_zip(&["a.npy", "a.npy"])).is_err(), "duplicate names");
492        assert!(NpzArchive::new(&raw_zip(&["dir/inner.npy"])).is_ok());
493    }
494
495    #[test]
496    fn damage_is_detected() {
497        let arrays = sample();
498        let stored = npz_encode(&refs(&arrays[..2]), false).unwrap();
499        // Truncation anywhere fails (the end record is gone, or a member is cut).
500        for cut in 0..stored.len() - 1 {
501            let r = npz_decode(&stored[..cut]);
502            assert!(r.is_err(), "cut at {cut}");
503        }
504        // A flipped data byte fails the CRC.
505        let mut flipped = stored.clone();
506        let data_at = 30 + "a.npy".len() + 150;
507        flipped[data_at] ^= 0x10;
508        assert!(npz_decode(&flipped).is_err());
509        // The same for a compressed member.
510        let deflated = npz_encode(&refs(&arrays[..2]), true).unwrap();
511        let mut d = deflated.clone();
512        d[30 + "a.npy".len() + 20] ^= 0x04;
513        assert!(npz_decode(&d).is_err());
514        // Encrypted, and an unsupported method (bzip2 = 12).
515        let find_central = |b: &[u8]| (0..b.len() - 4).find(|&i| b[i..i + 4] == SIG_CENTRAL.to_le_bytes()).unwrap();
516        let mut enc = stored.clone();
517        let c = find_central(&enc);
518        enc[c + 8] |= 1;
519        assert!(NpzArchive::new(&enc).is_err());
520        let mut bz = stored.clone();
521        bz[c + 10] = 12;
522        assert!(NpzArchive::new(&bz).unwrap().raw("a").is_err());
523        // A member declared smaller than it expands: the size limit stops the inflation.
524        let mut small = deflated.clone();
525        let c = find_central(&small);
526        small[c + 24..c + 28].copy_from_slice(&3u32.to_le_bytes());
527        assert!(NpzArchive::new(&small).unwrap().raw("a").is_err());
528    }
529
530    #[test]
531    fn corrupt_bytes_never_panic() {
532        let arrays = sample();
533        for compressed in [false, true] {
534            let bytes = npz_encode(&refs(&arrays[..3]), compressed).unwrap();
535            let mut state = 5u64;
536            for _ in 0..2000 {
537                let mut b = bytes.clone();
538                for _ in 0..1 + state % 3 {
539                    state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
540                    let i = (state >> 33) as usize % b.len();
541                    b[i] = (state >> 20) as u8;
542                }
543                let _ = npz_decode(&b);
544            }
545        }
546    }
547}