Skip to main content

lib_jsl_file_io/
idl.rs

1//! IDL `.sav` files (SciPy's `io.readsav`): the SAVE format of Harris Geospatial's Interactive Data
2//! Language, as documented by Craig Markwardt's *Unofficial Format Specification*.
3//!
4//! A file is `SR` and a format code (`\0\x04`, or `\0\x06` when every record is zlib-compressed),
5//! then records. Each has a type, the absolute offset of the next record (64 bits), four unused
6//! bytes and a body. All values are big-endian and padded to 32-bit boundaries: bytes and 16-bit
7//! integers take four bytes as scalars, a byte array is padded to a multiple of four, strings
8//! carry their length. A `VARIABLE` record holds a name, a type descriptor (a type code, flags,
9//! and for arrays and structures their descriptors) and the data; pointers refer to `HEAP_DATA`
10//! records by index, and are replaced by the values they point to.
11//!
12//! Reading covers every scalar type, arrays of up to eight dimensions, strings, structures
13//! (nested, in arrays, inherited), pointers and object references, and compressed files.
14//! There is no writer; SciPy has none either.
15//!
16//! See the book entry [Scientific data files](https://jwkunz.github.io/lib_jsl/book/foundations/scientific-files.html#idl-save-files).
17
18use crate::deflate::zlib_decompress;
19use lib_jsl_core::ErrorsJSL;
20use std::collections::HashMap;
21use std::path::Path;
22use std::rc::Rc;
23
24fn bad(msg: &'static str) -> ErrorsJSL {
25    ErrorsJSL::InvalidInputRange(msg)
26}
27
28/// The type of a numeric IDL value.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum IdlType {
32    /// `BYTE`, 8-bit unsigned.
33    Byte,
34    /// `INT`, 16-bit signed.
35    Int,
36    /// `LONG`, 32-bit signed.
37    Long,
38    /// `FLOAT`, 32-bit.
39    Float,
40    /// `DOUBLE`, 64-bit.
41    Double,
42    /// `COMPLEX`, two 32-bit floats.
43    Complex,
44    /// `DCOMPLEX`, two 64-bit floats.
45    DComplex,
46    /// `UINT`, 16-bit unsigned.
47    UInt,
48    /// `ULONG`, 32-bit unsigned.
49    ULong,
50    /// `LONG64`, 64-bit signed.
51    Long64,
52    /// `ULONG64`, 64-bit unsigned.
53    ULong64,
54}
55
56/// A value read from a save file. Arrays have NumPy's shape, which is IDL's dimensions reversed:
57/// IDL's `a[i, j]` is element `[j][i]`. Data are in the file's order, which is row-major in that
58/// shape. A scalar has empty `dims`.
59#[derive(Clone, Debug, PartialEq)]
60#[non_exhaustive]
61pub enum IdlValue {
62    /// A null pointer, or a pointer whose target is not in the file.
63    Null,
64    /// Numbers, converted to `f64` (64-bit integers beyond 2⁵³ lose precision); complex values
65    /// have an imaginary part.
66    Number { kind: IdlType, dims: Vec<usize>, real: Vec<f64>, imag: Option<Vec<f64>> },
67    /// Strings, in Latin-1.
68    Str { dims: Vec<usize>, data: Vec<String> },
69    /// A structure array: the structure's name, the field names, and for each element one value
70    /// per field.
71    Struct { name: String, dims: Vec<usize>, fields: Vec<String>, elements: Vec<Vec<IdlValue>> },
72    /// An array of pointers or object references, each replaced by its target.
73    Objects { dims: Vec<usize>, items: Vec<IdlValue> },
74    /// A pointer, before it is replaced by its target. Never returned by [`idl_decode`].
75    Pointer(i32),
76}
77
78/// The descriptive records of a save file, where present.
79#[derive(Clone, Debug, Default, PartialEq)]
80#[non_exhaustive]
81pub struct IdlInfo {
82    /// When the file was written.
83    pub date: Option<String>,
84    pub user: Option<String>,
85    pub host: Option<String>,
86    /// The save-file format version.
87    pub format: Option<i32>,
88    /// The writer's architecture, operating system and IDL release.
89    pub arch: Option<String>,
90    pub os: Option<String>,
91    pub release: Option<String>,
92    pub notice: Option<String>,
93    pub description: Option<String>,
94    pub author: Option<String>,
95    pub title: Option<String>,
96    pub idcode: Option<String>,
97}
98
99/// A parsed save file.
100#[derive(Clone, Debug, PartialEq)]
101#[non_exhaustive]
102pub struct IdlSave {
103    /// The variables in file order, with their names as saved (IDL names are case-insensitive).
104    pub variables: Vec<(String, IdlValue)>,
105    pub info: IdlInfo,
106}
107
108impl IdlSave {
109    /// A variable by name, ignoring case as IDL does.
110    pub fn get(&self, name: &str) -> Option<&IdlValue> {
111        self.variables.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v)
112    }
113}
114
115#[derive(Clone, Debug)]
116struct ArrayDesc {
117    nelements: usize,
118    ndims: usize,
119    dims: Vec<usize>,
120}
121
122impl ArrayDesc {
123    /// NumPy's shape: IDL's dimensions reversed, or just the length for a vector.
124    fn shape(&self) -> Result<Vec<usize>, ErrorsJSL> {
125        if self.ndims <= 1 {
126            return Ok(vec![self.nelements]);
127        }
128        let mut d: Vec<usize> = self.dims[..self.ndims].to_vec();
129        d.reverse();
130        if d.iter().try_fold(1usize, |a, &b| a.checked_mul(b)) != Some(self.nelements) {
131            return Err(bad("IDL save file: array dimensions do not match the number of elements"));
132        }
133        Ok(d)
134    }
135}
136
137#[derive(Debug)]
138struct Tag {
139    name: String,
140    typecode: i32,
141    array: bool,
142    structure: bool,
143    arr: Option<ArrayDesc>,
144    sub: Option<Rc<StructDesc>>,
145}
146
147#[derive(Debug)]
148struct StructDesc {
149    name: String,
150    tags: Vec<Tag>,
151}
152
153#[derive(Debug)]
154struct TypeDesc {
155    typecode: i32,
156    array: Option<ArrayDesc>,
157    structure: Option<(ArrayDesc, Rc<StructDesc>)>,
158}
159
160/// A big-endian reader over one record's body.
161struct Rd<'a> {
162    b: &'a [u8],
163    pos: usize,
164    defs: &'a mut HashMap<String, Rc<StructDesc>>,
165}
166
167const MAX_DEPTH: usize = 64;
168
169impl Rd<'_> {
170    fn take(&mut self, n: usize) -> Result<&[u8], ErrorsJSL> {
171        let end = self.pos.checked_add(n).filter(|&e| e <= self.b.len()).ok_or_else(|| bad("IDL save file: truncated record"))?;
172        let s = &self.b[self.pos..end];
173        self.pos = end;
174        Ok(s)
175    }
176
177    fn skip(&mut self, n: usize) -> Result<(), ErrorsJSL> {
178        self.take(n).map(|_| ())
179    }
180
181    fn long(&mut self) -> Result<i32, ErrorsJSL> {
182        Ok(i32::from_be_bytes(self.take(4)?.try_into().expect("4 bytes")))
183    }
184
185    fn u64(&mut self) -> Result<u64, ErrorsJSL> {
186        Ok(u64::from_be_bytes(self.take(8)?.try_into().expect("8 bytes")))
187    }
188
189    fn align(&mut self) {
190        if !self.pos.is_multiple_of(4) {
191            self.pos = (self.pos + 4 - self.pos % 4).min(self.b.len());
192        }
193    }
194
195    fn count(&mut self) -> Result<usize, ErrorsJSL> {
196        usize::try_from(self.long()?).map_err(|_| bad("IDL save file: negative count"))
197    }
198
199    /// A string: its length, the bytes, padded to 32 bits.
200    fn string(&mut self) -> Result<String, ErrorsJSL> {
201        let n = self.long()?;
202        if n <= 0 {
203            return Ok(String::new());
204        }
205        let s: String = self.take(n as usize)?.iter().map(|&c| c as char).collect();
206        self.align();
207        Ok(s)
208    }
209
210    /// A data string, whose length is given twice.
211    fn string_data(&mut self) -> Result<String, ErrorsJSL> {
212        let n = self.long()?;
213        if n <= 0 {
214            return Ok(String::new());
215        }
216        let m = self.count()?;
217        let s: String = self.take(m)?.iter().map(|&c| c as char).collect();
218        self.align();
219        Ok(s)
220    }
221
222    fn array_desc(&mut self) -> Result<ArrayDesc, ErrorsJSL> {
223        let start = self.long()?;
224        match start {
225            8 => {
226                self.skip(4)?;
227                let _nbytes = self.long()?;
228                let nelements = self.count()?;
229                let ndims = self.count()?;
230                self.skip(8)?;
231                let nmax = self.count()?;
232                if ndims > nmax || nmax > 64 {
233                    return Err(bad("IDL save file: invalid array descriptor"));
234                }
235                let dims = (0..nmax).map(|_| self.count()).collect::<Result<Vec<_>, _>>()?;
236                Ok(ArrayDesc { nelements, ndims, dims })
237            }
238            18 => {
239                self.skip(8)?;
240                let _nbytes = self.u64()?;
241                let nelements = usize::try_from(self.u64()?).map_err(|_| bad("IDL save file: array too large"))?;
242                let ndims = self.count()?;
243                self.skip(8)?;
244                if ndims > 8 {
245                    return Err(bad("IDL save file: invalid array descriptor"));
246                }
247                let mut dims = Vec::new();
248                for _ in 0..8 {
249                    if self.long()? != 0 {
250                        return Err(bad("IDL save file: expected a zero in a 64-bit array descriptor"));
251                    }
252                    dims.push(self.count()?);
253                }
254                Ok(ArrayDesc { nelements, ndims, dims })
255            }
256            _ => Err(bad("IDL save file: unknown array descriptor")),
257        }
258    }
259
260    fn struct_desc(&mut self, depth: usize) -> Result<Rc<StructDesc>, ErrorsJSL> {
261        if depth > MAX_DEPTH {
262            return Err(bad("IDL save file: structure nesting too deep"));
263        }
264        if self.long()? != 9 {
265            return Err(bad("IDL save file: expected a structure descriptor"));
266        }
267        let name = self.string()?;
268        let predef = self.long()?;
269        let ntags = self.count()?;
270        let _nbytes = self.long()?;
271        let (predefined, inherits, is_super) = (predef & 1 != 0, predef & 2 != 0, predef & 4 != 0);
272        if predefined {
273            return self.defs.get(&name).cloned().ok_or_else(|| bad("IDL save file: a predefined structure is not defined earlier"));
274        }
275        if ntags > self.b.len() {
276            return Err(bad("IDL save file: invalid structure descriptor"));
277        }
278        let mut tags = Vec::with_capacity(ntags);
279        for _ in 0..ntags {
280            let mut offset = self.long()?;
281            if offset == -1 {
282                offset = 0;
283                self.skip(8)?;
284            }
285            let _ = offset;
286            let typecode = self.long()?;
287            let flags = self.long()?;
288            tags.push(Tag { name: String::new(), typecode, array: flags & 4 != 0, structure: flags & 32 != 0, arr: None, sub: None });
289        }
290        for t in tags.iter_mut() {
291            t.name = self.string()?;
292        }
293        for t in tags.iter_mut().filter(|t| t.array) {
294            t.arr = Some(self.array_desc()?);
295        }
296        for t in tags.iter_mut().filter(|t| t.structure) {
297            t.sub = Some(self.struct_desc(depth + 1)?);
298        }
299        if inherits || is_super {
300            let _classname = self.string()?;
301            let nsup = self.count()?;
302            if nsup > self.b.len() {
303                return Err(bad("IDL save file: invalid superclass count"));
304            }
305            for _ in 0..nsup {
306                self.string()?;
307            }
308            for _ in 0..nsup {
309                self.struct_desc(depth + 1)?;
310            }
311        }
312        let desc = Rc::new(StructDesc { name: name.clone(), tags });
313        self.defs.insert(name, desc.clone());
314        Ok(desc)
315    }
316
317    fn type_desc(&mut self) -> Result<TypeDesc, ErrorsJSL> {
318        let typecode = self.long()?;
319        let flags = self.long()?;
320        if flags & 2 != 0 {
321            return Err(bad("IDL save file: system variables are not supported"));
322        }
323        let (array, structure) = (flags & 4 != 0, flags & 32 != 0);
324        if structure {
325            let a = self.array_desc()?;
326            let s = self.struct_desc(0)?;
327            Ok(TypeDesc { typecode, array: None, structure: Some((a, s)) })
328        } else if array {
329            Ok(TypeDesc { typecode, array: Some(self.array_desc()?), structure: None })
330        } else {
331            Ok(TypeDesc { typecode, array: None, structure: None })
332        }
333    }
334
335    /// A scalar of type `code`.
336    fn data(&mut self, code: i32) -> Result<IdlValue, ErrorsJSL> {
337        let num = |kind, v: f64| IdlValue::Number { kind, dims: Vec::new(), real: vec![v], imag: None };
338        Ok(match code {
339            1 => {
340                if self.long()? != 1 {
341                    return Err(bad("IDL save file: error reading a byte variable"));
342                }
343                let v = self.take(4)?[0];
344                num(IdlType::Byte, v as f64)
345            }
346            2 => num(IdlType::Int, i16::from_be_bytes(self.take(4)?[2..4].try_into().expect("2 bytes")) as f64),
347            3 => num(IdlType::Long, self.long()? as f64),
348            4 => num(IdlType::Float, f32::from_be_bytes(self.take(4)?.try_into().expect("4 bytes")) as f64),
349            5 => num(IdlType::Double, f64::from_be_bytes(self.take(8)?.try_into().expect("8 bytes"))),
350            6 => {
351                let re = f32::from_be_bytes(self.take(4)?.try_into().expect("4 bytes")) as f64;
352                let im = f32::from_be_bytes(self.take(4)?.try_into().expect("4 bytes")) as f64;
353                IdlValue::Number { kind: IdlType::Complex, dims: Vec::new(), real: vec![re], imag: Some(vec![im]) }
354            }
355            7 => IdlValue::Str { dims: Vec::new(), data: vec![self.string_data()?] },
356            9 => {
357                let re = f64::from_be_bytes(self.take(8)?.try_into().expect("8 bytes"));
358                let im = f64::from_be_bytes(self.take(8)?.try_into().expect("8 bytes"));
359                IdlValue::Number { kind: IdlType::DComplex, dims: Vec::new(), real: vec![re], imag: Some(vec![im]) }
360            }
361            10 | 11 => IdlValue::Pointer(self.long()?),
362            12 => num(IdlType::UInt, u16::from_be_bytes(self.take(4)?[2..4].try_into().expect("2 bytes")) as f64),
363            13 => num(IdlType::ULong, u32::from_be_bytes(self.take(4)?.try_into().expect("4 bytes")) as f64),
364            14 => num(IdlType::Long64, i64::from_be_bytes(self.take(8)?.try_into().expect("8 bytes")) as f64),
365            15 => num(IdlType::ULong64, self.u64()? as f64),
366            _ => return Err(bad("IDL save file: unknown variable type")),
367        })
368    }
369
370    /// An array of type `code`.
371    fn array(&mut self, code: i32, desc: &ArrayDesc) -> Result<IdlValue, ErrorsJSL> {
372        let n = desc.nelements;
373        let dims = desc.shape()?;
374        let value = match code {
375            1 | 3 | 4 | 5 | 6 | 9 | 13 | 14 | 15 => {
376                if code == 1 {
377                    self.long()?; // the byte count, repeated
378                }
379                let (kind, width, complex) = match code {
380                    1 => (IdlType::Byte, 1, false),
381                    3 => (IdlType::Long, 4, false),
382                    4 => (IdlType::Float, 4, false),
383                    5 => (IdlType::Double, 8, false),
384                    6 => (IdlType::Complex, 4, true),
385                    9 => (IdlType::DComplex, 8, true),
386                    13 => (IdlType::ULong, 4, false),
387                    14 => (IdlType::Long64, 8, false),
388                    _ => (IdlType::ULong64, 8, false),
389                };
390                let values = n.checked_mul(width * if complex { 2 } else { 1 }).ok_or_else(|| bad("IDL save file: array too large"))?;
391                let raw = self.take(values)?;
392                let one = |c: &[u8]| -> f64 {
393                    match (code, width) {
394                        (1, _) => c[0] as f64,
395                        (3, _) => i32::from_be_bytes(c.try_into().expect("4 bytes")) as f64,
396                        (13, _) => u32::from_be_bytes(c.try_into().expect("4 bytes")) as f64,
397                        (14, _) => i64::from_be_bytes(c.try_into().expect("8 bytes")) as f64,
398                        (15, _) => u64::from_be_bytes(c.try_into().expect("8 bytes")) as f64,
399                        (_, 4) => f32::from_be_bytes(c.try_into().expect("4 bytes")) as f64,
400                        _ => f64::from_be_bytes(c.try_into().expect("8 bytes")),
401                    }
402                };
403                let all: Vec<f64> = raw.chunks_exact(width).map(one).collect();
404                if complex {
405                    IdlValue::Number { kind, dims, real: all.iter().step_by(2).copied().collect(), imag: Some(all.iter().skip(1).step_by(2).copied().collect()) }
406                } else {
407                    IdlValue::Number { kind, dims, real: all, imag: None }
408                }
409            }
410            2 | 12 => {
411                // Two-byte integers occupy four bytes each; the value is the low half.
412                let total = n.checked_mul(4).ok_or_else(|| bad("IDL save file: array too large"))?;
413                let raw = self.take(total)?;
414                let real = raw
415                    .chunks_exact(4)
416                    .map(|c| if code == 2 { i16::from_be_bytes([c[2], c[3]]) as f64 } else { u16::from_be_bytes([c[2], c[3]]) as f64 })
417                    .collect();
418                IdlValue::Number { kind: if code == 2 { IdlType::Int } else { IdlType::UInt }, dims, real, imag: None }
419            }
420            7 => {
421                if n > self.b.len() {
422                    return Err(bad("IDL save file: array larger than its record"));
423                }
424                let data = (0..n).map(|_| self.string_data()).collect::<Result<Vec<_>, _>>()?;
425                IdlValue::Str { dims, data }
426            }
427            10 | 11 => {
428                if n > self.b.len() {
429                    return Err(bad("IDL save file: array larger than its record"));
430                }
431                let items = (0..n).map(|_| self.data(code)).collect::<Result<Vec<_>, _>>()?;
432                IdlValue::Objects { dims, items }
433            }
434            _ => return Err(bad("IDL save file: unsupported array type")),
435        };
436        self.align();
437        Ok(value)
438    }
439
440    fn structure(&mut self, desc: &ArrayDesc, sd: &StructDesc, depth: usize) -> Result<IdlValue, ErrorsJSL> {
441        if depth > MAX_DEPTH {
442            return Err(bad("IDL save file: structure nesting too deep"));
443        }
444        let dims = desc.shape()?;
445        if desc.nelements > self.b.len() {
446            return Err(bad("IDL save file: array larger than its record"));
447        }
448        let mut elements = Vec::with_capacity(desc.nelements);
449        for _ in 0..desc.nelements {
450            let mut row = Vec::with_capacity(sd.tags.len());
451            for t in &sd.tags {
452                row.push(if t.structure {
453                    let (Some(a), Some(s)) = (t.arr.as_ref(), t.sub.as_ref()) else {
454                        return Err(bad("IDL save file: a structure tag has no descriptor"));
455                    };
456                    self.structure(a, s, depth + 1)?
457                } else if t.array {
458                    let a = t.arr.as_ref().ok_or_else(|| bad("IDL save file: an array tag has no descriptor"))?;
459                    self.array(t.typecode, a)?
460                } else {
461                    self.data(t.typecode)?
462                });
463            }
464            elements.push(row);
465        }
466        Ok(IdlValue::Struct { name: sd.name.clone(), dims, fields: sd.tags.iter().map(|t| t.name.clone()).collect(), elements })
467    }
468
469    /// The type descriptor and value of a `VARIABLE` or `HEAP_DATA` record; `None` for a null.
470    fn typed_value(&mut self) -> Result<Option<IdlValue>, ErrorsJSL> {
471        let td = self.type_desc()?;
472        if td.typecode == 0 {
473            return if self.pos == self.b.len() { Ok(None) } else { Err(bad("IDL save file: unexpected type code 0")) };
474        }
475        if self.long()? != 7 {
476            return Err(bad("IDL save file: VARSTART is not 7"));
477        }
478        Ok(Some(if let Some((a, s)) = &td.structure {
479            self.structure(a, s, 0)?
480        } else if let Some(a) = &td.array {
481            self.array(td.typecode, a)?
482        } else {
483            self.data(td.typecode)?
484        }))
485    }
486}
487
488fn resolve(v: &IdlValue, heap: &HashMap<i32, IdlValue>, depth: usize) -> Result<IdlValue, ErrorsJSL> {
489    if depth > MAX_DEPTH {
490        return Err(bad("IDL save file: pointers nest too deeply or form a cycle"));
491    }
492    Ok(match v {
493        IdlValue::Pointer(0) => IdlValue::Null,
494        IdlValue::Pointer(i) => match heap.get(i) {
495            Some(target) => resolve(target, heap, depth + 1)?,
496            None => IdlValue::Null,
497        },
498        IdlValue::Objects { dims, items } => IdlValue::Objects { dims: dims.clone(), items: items.iter().map(|x| resolve(x, heap, depth + 1)).collect::<Result<_, _>>()? },
499        IdlValue::Struct { name, dims, fields, elements } => IdlValue::Struct {
500            name: name.clone(),
501            dims: dims.clone(),
502            fields: fields.clone(),
503            elements: elements.iter().map(|row| row.iter().map(|x| resolve(x, heap, depth + 1)).collect::<Result<Vec<_>, _>>()).collect::<Result<_, _>>()?,
504        },
505        other => other.clone(),
506    })
507}
508
509const END_MARKER: i32 = 6;
510
511// ANCHOR: readsav
512/// Parses an IDL save file (SciPy's `readsav`): the variables in file order, pointers replaced
513/// by what they point to, and the descriptive records. A compressed file (format code `\0\x06`)
514/// is expanded record by record. Record types the reader does not use, such as `COMPILED` and
515/// `PROMOTE64`, are skipped by their next-record offsets, where SciPy refuses some of them.
516pub fn idl_decode(bytes: &[u8]) -> Result<IdlSave, ErrorsJSL> {
517    if bytes.len() < 4 || &bytes[..2] != b"SR" {
518        return Err(bad("IDL save file: invalid signature"));
519    }
520    let compressed = match &bytes[2..4] {
521        [0, 4] => false,
522        [0, 6] => true,
523        _ => return Err(bad("IDL save file: invalid record format")),
524    };
525    // Split into records: (type, body).
526    let mut records: Vec<(i32, Vec<u8>)> = Vec::new();
527    let mut pos = 4usize;
528    loop {
529        let header = bytes.get(pos..pos + 16).ok_or_else(|| bad("IDL save file: truncated before the end marker"))?;
530        let rectype = i32::from_be_bytes(header[0..4].try_into().expect("4 bytes"));
531        let next = u32::from_be_bytes(header[4..8].try_into().expect("4 bytes")) as u64 + ((u32::from_be_bytes(header[8..12].try_into().expect("4 bytes")) as u64) << 32);
532        if rectype == END_MARKER {
533            break;
534        }
535        let next = usize::try_from(next).map_err(|_| bad("IDL save file: record offset too large"))?;
536        if next < pos + 16 || next > bytes.len() {
537            return Err(bad("IDL save file: a record's next-record offset is outside the file"));
538        }
539        let body = &bytes[pos + 16..next];
540        records.push((rectype, if compressed { zlib_decompress(body)? } else { body.to_vec() }));
541        pos = next;
542    }
543    let mut defs: HashMap<String, Rc<StructDesc>> = HashMap::new();
544    let mut info = IdlInfo::default();
545    let mut raw: Vec<(String, IdlValue)> = Vec::new();
546    let mut heap: HashMap<i32, IdlValue> = HashMap::new();
547    for (rectype, body) in &records {
548        let mut r = Rd { b: body, pos: 0, defs: &mut defs };
549        match rectype {
550            2 => {
551                let name = r.string()?;
552                let value = r.typed_value()?.unwrap_or(IdlValue::Null);
553                raw.push((name, value));
554            }
555            16 => {
556                let index = r.long()?;
557                r.skip(4)?;
558                heap.insert(index, r.typed_value()?.unwrap_or(IdlValue::Null));
559            }
560            10 => {
561                r.skip(4 * 256)?;
562                info.date = Some(r.string()?);
563                info.user = Some(r.string()?);
564                info.host = Some(r.string()?);
565            }
566            14 => {
567                info.format = Some(r.long()?);
568                info.arch = Some(r.string()?);
569                info.os = Some(r.string()?);
570                info.release = Some(r.string()?);
571            }
572            13 => {
573                info.author = Some(r.string()?);
574                info.title = Some(r.string()?);
575                info.idcode = Some(r.string()?);
576            }
577            19 => info.notice = Some(r.string()?),
578            20 => info.description = Some(r.string_data()?),
579            _ => {}
580        }
581    }
582    let variables = raw.iter().map(|(n, v)| Ok((n.clone(), resolve(v, &heap, 0)?))).collect::<Result<Vec<_>, ErrorsJSL>>()?;
583    Ok(IdlSave { variables, info })
584}
585// ANCHOR_END: readsav
586
587/// Reads an IDL save file.
588pub fn read_idl_file(path: impl AsRef<Path>) -> Result<IdlSave, ErrorsJSL> {
589    idl_decode(&std::fs::read(path).map_err(|_| ErrorsJSL::RuntimeError("could not read the IDL save file"))?)
590}