Skip to main content

lib_jsl_file_io/
fortran.rs

1//! Fortran sequential unformatted files (SciPy's `io.FortranFile`).
2//!
3//! Each record written by a Fortran `WRITE` statement to an unformatted sequential file is
4//! framed by its length in bytes, as a 4-byte (gfortran's default, SciPy's `header_dtype`
5//! `uint32`) or 8-byte integer, before and after the data. The data are raw machine values,
6//! here little-endian.
7//!
8//! See the book entry [Scientific data files](https://jwkunz.github.io/lib_jsl/book/foundations/scientific-files.html#fortran-records-and-arff).
9
10use lib_jsl_core::ErrorsJSL;
11use std::path::Path;
12
13fn bad(msg: &'static str) -> ErrorsJSL {
14    ErrorsJSL::InvalidInputRange(msg)
15}
16
17// ANCHOR: fortran
18/// Splits a Fortran unformatted sequential file into its records (SciPy's
19/// `FortranFile.read_record`), with `marker_bytes` (4 or 8) per length marker. Each record's
20/// leading and trailing markers must agree.
21pub fn fortran_records_decode(bytes: &[u8], marker_bytes: usize) -> Result<Vec<Vec<u8>>, ErrorsJSL> {
22    if !matches!(marker_bytes, 4 | 8) {
23        return Err(bad("Fortran file: record markers are 4 or 8 bytes"));
24    }
25    let marker = |at: usize| -> Result<usize, ErrorsJSL> {
26        let s = bytes.get(at..at + marker_bytes).ok_or(bad("Fortran file: truncated record marker"))?;
27        Ok(if marker_bytes == 4 { u32::from_le_bytes(s.try_into().expect("4 bytes")) as usize } else { u64::from_le_bytes(s.try_into().expect("8 bytes")) as usize })
28    };
29    let mut out = Vec::new();
30    let mut pos = 0;
31    while pos < bytes.len() {
32        let n = marker(pos)?;
33        let start = pos + marker_bytes;
34        let data = bytes.get(start..start + n).ok_or(bad("Fortran file: truncated record"))?;
35        if marker(start + n)? != n {
36            return Err(bad("Fortran file: the record markers disagree"));
37        }
38        out.push(data.to_vec());
39        pos = start + n + marker_bytes;
40    }
41    Ok(out)
42}
43
44/// Frames records for a Fortran unformatted sequential file (SciPy's `FortranFile.write_record`).
45pub fn fortran_records_encode(records: &[Vec<u8>], marker_bytes: usize) -> Result<Vec<u8>, ErrorsJSL> {
46    if !matches!(marker_bytes, 4 | 8) {
47        return Err(bad("Fortran file: record markers are 4 or 8 bytes"));
48    }
49    let mut out = Vec::new();
50    for r in records {
51        let m: Vec<u8> = if marker_bytes == 4 {
52            u32::try_from(r.len()).map_err(|_| bad("Fortran file: a record is too long for 4-byte markers"))?.to_le_bytes().to_vec()
53        } else {
54            (r.len() as u64).to_le_bytes().to_vec()
55        };
56        out.extend(&m);
57        out.extend(r);
58        out.extend(&m);
59    }
60    Ok(out)
61}
62// ANCHOR_END: fortran
63
64/// A record's bytes as little-endian `f64` values (`read_reals(dtype=float)`).
65pub fn record_to_f64(r: &[u8]) -> Result<Vec<f64>, ErrorsJSL> {
66    if !r.len().is_multiple_of(8) {
67        return Err(bad("Fortran file: the record is not a whole number of f64 values"));
68    }
69    Ok(r.chunks_exact(8).map(|c| f64::from_le_bytes(c.try_into().expect("8 bytes"))).collect())
70}
71
72/// A record's bytes as little-endian `f32` values.
73pub fn record_to_f32(r: &[u8]) -> Result<Vec<f32>, ErrorsJSL> {
74    if !r.len().is_multiple_of(4) {
75        return Err(bad("Fortran file: the record is not a whole number of f32 values"));
76    }
77    Ok(r.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().expect("4 bytes"))).collect())
78}
79
80/// A record's bytes as little-endian `i32` values (`read_ints()`).
81pub fn record_to_i32(r: &[u8]) -> Result<Vec<i32>, ErrorsJSL> {
82    if !r.len().is_multiple_of(4) {
83        return Err(bad("Fortran file: the record is not a whole number of i32 values"));
84    }
85    Ok(r.chunks_exact(4).map(|c| i32::from_le_bytes(c.try_into().expect("4 bytes"))).collect())
86}
87
88/// `f64` values as a record's bytes.
89pub fn record_from_f64(v: &[f64]) -> Vec<u8> {
90    v.iter().flat_map(|x| x.to_le_bytes()).collect()
91}
92
93/// `f32` values as a record's bytes.
94pub fn record_from_f32(v: &[f32]) -> Vec<u8> {
95    v.iter().flat_map(|x| x.to_le_bytes()).collect()
96}
97
98/// `i32` values as a record's bytes.
99pub fn record_from_i32(v: &[i32]) -> Vec<u8> {
100    v.iter().flat_map(|x| x.to_le_bytes()).collect()
101}
102
103/// Reads the records of a Fortran unformatted sequential file.
104pub fn read_fortran_file(path: impl AsRef<Path>, marker_bytes: usize) -> Result<Vec<Vec<u8>>, ErrorsJSL> {
105    fortran_records_decode(&std::fs::read(path).map_err(|_| ErrorsJSL::RuntimeError("could not read the Fortran file"))?, marker_bytes)
106}
107
108/// Writes records as a Fortran unformatted sequential file.
109pub fn write_fortran_file(path: impl AsRef<Path>, records: &[Vec<u8>], marker_bytes: usize) -> Result<(), ErrorsJSL> {
110    std::fs::write(path, fortran_records_encode(records, marker_bytes)?).map_err(|_| ErrorsJSL::RuntimeError("could not write the Fortran file"))
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    #[test]
118    fn records_round_trip() {
119        let recs = vec![record_from_i32(&[3, -4]), record_from_f64(&[1.5, -2.25, 1e300]), Vec::new(), record_from_f32(&[0.5])];
120        for m in [4, 8] {
121            let b = fortran_records_encode(&recs, m).unwrap();
122            assert_eq!(b.len(), recs.iter().map(|r| r.len() + 2 * m).sum::<usize>());
123            let back = fortran_records_decode(&b, m).unwrap();
124            assert_eq!(back, recs);
125            assert_eq!(record_to_f64(&back[1]).unwrap(), vec![1.5, -2.25, 1e300]);
126            assert_eq!(record_to_i32(&back[0]).unwrap(), vec![3, -4]);
127        }
128        let mut b = fortran_records_encode(&recs, 4).unwrap();
129        b[12] = 99; // the trailing marker of the first record
130        assert!(fortran_records_decode(&b, 4).is_err());
131    }
132}