lib_jsl_file_io/
fortran.rs1use lib_jsl_core::ErrorsJSL;
11use std::path::Path;
12
13fn bad(msg: &'static str) -> ErrorsJSL {
14 ErrorsJSL::InvalidInputRange(msg)
15}
16
17pub 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
44pub 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}
62pub 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
72pub 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
80pub 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
88pub fn record_from_f64(v: &[f64]) -> Vec<u8> {
90 v.iter().flat_map(|x| x.to_le_bytes()).collect()
91}
92
93pub fn record_from_f32(v: &[f32]) -> Vec<u8> {
95 v.iter().flat_map(|x| x.to_le_bytes()).collect()
96}
97
98pub fn record_from_i32(v: &[i32]) -> Vec<u8> {
100 v.iter().flat_map(|x| x.to_le_bytes()).collect()
101}
102
103pub 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
108pub 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; assert!(fortran_records_decode(&b, 4).is_err());
131 }
132}