Work on system file library.
[pspp] / rust / src / lib.rs
1 #![allow(unused_variables)]
2 use endian::{Endian, Parse};
3 use std::io::{BufReader, Error as IoError, Read};
4 use thiserror::Error;
5
6 pub mod endian;
7
8 #[derive(Error, Debug)]
9 pub enum Error {
10     #[error("Not an SPSS system file")]
11     NotASystemFile,
12
13     #[error("I/O error ({source})")]
14     Io {
15         #[from]
16         source: IoError,
17     },
18
19     #[error("Invalid SAV compression code {0}")]
20     InvalidSavCompression(u32),
21
22     #[error("Invalid ZSAV compression code {0}")]
23     InvalidZsavCompression(u32),
24 }
25
26 #[derive(Error, Debug)]
27 pub enum Warning {
28     #[error("Unexpected floating-point bias {0} or unrecognized floating-point format.")]
29     UnexpectedBias(f64),
30 }
31
32 #[derive(Copy, Clone, Debug)]
33 pub enum Compression {
34     Simple,
35     ZLib,
36 }
37
38 pub struct Reader<R: Read> {
39     r: BufReader<R>,
40 }
41
42 pub const ASCII_MAGIC: &[u8; 4] = b"$FL2";
43 pub const ASCII_ZMAGIC: &[u8; 4] = b"$FL3";
44 pub const EBCDIC_MAGIC: &[u8; 4] = &[0x5b, 0xc6, 0xd3, 0xf2];
45
46 pub struct FileHeader {
47     /// First 4 bytes of the file, one of `ASCII_MAGIC`, `ASCII_ZMAGIC`, and
48     /// `EBCDIC_MAGIC`.
49     pub magic: [u8; 4],
50
51     /// True if `magic` indicates that this file contained zlib-compressed data.
52     pub is_zsav: bool,
53
54     /// True if `magic` indicates that this file contained EBCDIC data.
55     pub is_ebcdic: bool,
56
57     /// 0-based variable index of the weight variable, or `None` if the file is
58     /// unweighted.
59     pub weight_index: Option<u32>,
60
61     /// Number of variable positions, or `None` if the value in the file is
62     /// questionably trustworthy.
63     pub nominal_case_size: Option<u32>,
64
65     /// `dd mmm yy` in the file's encoding.
66     pub creation_date: [u8; 9],
67
68     /// `HH:MM:SS` in the file's encoding.
69     pub creation_time: [u8; 8],
70
71     /// Eye-catcher string, then product name, in the file's encoding.  Padded
72     /// on the right with spaces.
73     pub eye_catcher: [u8; 60],
74
75     /// File label, in the file's encoding.  Padded on the right with spaces.
76     pub file_label: [u8; 64],
77 }
78
79 impl<R: Read> Reader<R> {
80     pub fn new(r: R, warn: impl Fn(Warning)) -> Result<Reader<R>, Error> {
81         let mut r = BufReader::new(r);
82
83         let magic: [u8; 4] = read_bytes(&mut r)?;
84         let (is_zsav, is_ebcdic) = match &magic {
85             ASCII_MAGIC => (false, false),
86             ASCII_ZMAGIC => (true, false),
87             EBCDIC_MAGIC => (false, true),
88             _ => return Err(Error::NotASystemFile),
89         };
90
91         let eye_catcher: [u8; 60] = read_bytes(&mut r)?;
92         let layout_code: [u8; 4] = read_bytes(&mut r)?;
93         let endianness = Endian::identify_u32(2, layout_code)
94             .or_else(|| Endian::identify_u32(2, layout_code))
95             .ok_or_else(|| Error::NotASystemFile)?;
96
97         let nominal_case_size: u32 = endianness.parse(read_bytes(&mut r)?);
98         let nominal_case_size = (nominal_case_size <= u32::MAX / 32).then_some(nominal_case_size);
99
100         let compression_code: u32 = endianness.parse(read_bytes(&mut r)?);
101         let compression = match (is_zsav, compression_code) {
102             (false, 0) => None,
103             (false, 1) => Some(Compression::Simple),
104             (true, 2) => Some(Compression::ZLib),
105             (false, code) => return Err(Error::InvalidSavCompression(code)),
106             (true, code) => return Err(Error::InvalidZsavCompression(code)),
107         };
108
109         let weight_index: u32 = endianness.parse(read_bytes(&mut r)?);
110         let weight_index = (weight_index > 0).then_some(weight_index - 1);
111
112         let n_cases: u32 = endianness.parse(read_bytes(&mut r)?);
113         let n_cases = (n_cases <= u32::MAX / 4).then_some(n_cases);
114
115         let bias: f64 = endianness.parse(read_bytes(&mut r)?);
116         if bias != 100.0 {
117             warn(Warning::UnexpectedBias(bias))
118         }
119
120         let creation_date: [u8; 9] = read_bytes(&mut r)?;
121         let creation_time: [u8; 8] = read_bytes(&mut r)?;
122         let file_label: [u8; 64] = read_bytes(&mut r)?;
123         let _: [u8; 3] = read_bytes(&mut r)?;
124
125         let header = FileHeader {
126             magic,
127             is_zsav,
128             is_ebcdic,
129             weight_index,
130             nominal_case_size,
131             creation_date,
132             creation_time,
133             eye_catcher,
134             file_label,
135         };
136
137         Ok(Reader { r })
138     }
139 }
140
141 fn read_bytes<const N: usize, R: Read>(r: &mut R) -> Result<[u8; N], IoError> {
142     let mut buf = [0; N];
143     r.read_exact(&mut buf)?;
144     Ok(buf)
145 }
146
147 /*
148 fn trim_end(mut s: Vec<u8>, c: u8) -> Vec<u8> {
149     while s.last() == Some(&c) {
150         s.pop();
151     }
152     s
153 }
154
155 fn skip_bytes<R: Read>(r: &mut R, mut n: u64) -> Result<(), IoError> {
156     let mut buf = [0; 1024];
157     while n > 0 {
158         let chunk = u64::min(n, buf.len() as u64);
159         r.read_exact(&mut buf[0..chunk as usize])?;
160         n -= chunk;
161     }
162     Ok(())
163 }
164
165 */