more library work
[pspp] / rust / src / lib.rs
1 #![allow(unused_variables)]
2 use endian::{Endian, Parse};
3 use num::Integer;
4 use std::io::{BufReader, Error as IoError, Read, Seek};
5 use thiserror::Error;
6
7 pub mod endian;
8
9 #[derive(Error, Debug)]
10 pub enum Error {
11     #[error("Not an SPSS system file")]
12     NotASystemFile,
13
14     #[error("I/O error ({source})")]
15     Io {
16         #[from]
17         source: IoError,
18     },
19
20     #[error("Invalid SAV compression code {0}")]
21     InvalidSavCompression(u32),
22
23     #[error("Invalid ZSAV compression code {0}")]
24     InvalidZsavCompression(u32),
25
26     #[error("Misplaced type 4 record near offset {0:#x}.")]
27     MisplacedType4Record(u64),
28
29     #[error("Document record at offset {offset:#x} has document line count ({n}) greater than the maximum number {max}.")]
30     BadDocumentLength { offset: u64, n: u32, max: u32 },
31
32     #[error("At offset {offset:#x}, Unrecognized record type {rec_type}.")]
33     BadRecordType { offset: u64, rec_type: u32 },
34
35     #[error("At offset {offset:#x}, variable label code ({code}) is not 0 or 1.")]
36     BadVariableLabelCode { offset: u64, code: u32 },
37
38     #[error(
39         "At offset {offset:#x}, numeric missing value code ({code}) is not -3, -2, 0, 1, 2, or 3."
40     )]
41     BadNumericMissingValueCode { offset: u64, code: i32 },
42
43     #[error("At offset {offset:#x}, string missing value code ({code}) is not 0, 1, 2, or 3.")]
44     BadStringMissingValueCode { offset: u64, code: i32 },
45
46     #[error("At offset {offset:#x}, number of value labels ({n}) is greater than the maximum number {max}.")]
47     BadNumberOfValueLabels { offset: u64, n: u32, max: u32 },
48
49     #[error("At offset {offset:#x}, variable index record (type 4) does not immediately follow value label record (type 3) as it should.")]
50     MissingVariableIndexRecord { offset: u64 },
51
52     #[error("At offset {offset:#x}, number of variables associated with a value label ({n}) is not between 1 and the number of variables ({max}).")]
53     BadNumberOfValueLabelVariables { offset: u64, n: u32, max: u32 },
54 }
55
56 #[derive(Error, Debug)]
57 pub enum Warning {
58     #[error("Unexpected floating-point bias {0} or unrecognized floating-point format.")]
59     UnexpectedBias(f64),
60
61     #[error("Duplicate type 6 (document) record.")]
62     DuplicateDocumentRecord,
63 }
64
65 #[derive(Copy, Clone, Debug)]
66 pub enum Compression {
67     Simple,
68     ZLib,
69 }
70
71 pub struct Reader<R: Read> {
72     r: BufReader<R>,
73
74     document_record: Option<DocumentRecord>,
75
76     variables: Vec<VariableRecord>,
77
78     value_labels: Vec<ValueLabelRecord>,
79 }
80
81 /// Magic number for a regular system file.
82 pub const ASCII_MAGIC: &[u8; 4] = b"$FL2";
83
84 /// Magic number for a system file that contains zlib-compressed data.
85 pub const ASCII_ZMAGIC: &[u8; 4] = b"$FL3";
86
87 /// Magic number for an EBDIC-encoded system file.  This is `$FL2` encoded in
88 /// EBCDIC.
89 pub const EBCDIC_MAGIC: &[u8; 4] = &[0x5b, 0xc6, 0xd3, 0xf2];
90
91 pub struct FileHeader {
92     /// First 4 bytes of the file, one of `ASCII_MAGIC`, `ASCII_ZMAGIC`, and
93     /// `EBCDIC_MAGIC`.
94     pub magic: [u8; 4],
95
96     /// True if `magic` indicates that this file contained zlib-compressed data.
97     pub is_zsav: bool,
98
99     /// True if `magic` indicates that this file contained EBCDIC data.
100     pub is_ebcdic: bool,
101
102     /// Endianness of the data in the file header.
103     pub endianness: Endian,
104
105     /// 0-based variable index of the weight variable, or `None` if the file is
106     /// unweighted.
107     pub weight_index: Option<u32>,
108
109     /// Number of variable positions, or `None` if the value in the file is
110     /// questionably trustworthy.
111     pub nominal_case_size: Option<u32>,
112
113     /// `dd mmm yy` in the file's encoding.
114     pub creation_date: [u8; 9],
115
116     /// `HH:MM:SS` in the file's encoding.
117     pub creation_time: [u8; 8],
118
119     /// Eye-catcher string, then product name, in the file's encoding.  Padded
120     /// on the right with spaces.
121     pub eye_catcher: [u8; 60],
122
123     /// File label, in the file's encoding.  Padded on the right with spaces.
124     pub file_label: [u8; 64],
125 }
126
127 pub const DOC_LINE_LEN: u32 = 80;
128 pub const DOC_MAX_LINES: u32 = i32::MAX as u32 / DOC_LINE_LEN;
129
130 impl<R: Read + Seek> Reader<R> {
131     pub fn new(r: R, warn: impl Fn(Warning)) -> Result<Reader<R>, Error> {
132         let mut r = BufReader::new(r);
133
134         let header = read_header(&mut r, &warn)?;
135         let e = header.endianness;
136         let mut document_record = None;
137         let mut variables = Vec::new();
138         let mut value_labels = Vec::new();
139         loop {
140             let offset = r.stream_position()?;
141             let rec_type: u32 = e.parse(read_bytes(&mut r)?);
142             match rec_type {
143                 2 => variables.push(read_variable_record(&mut r, e)?),
144                 3 => value_labels.push(read_value_label_record(&mut r, e, variables.len())?),
145                 // A Type 4 record is always immediately after a type 3 record,
146                 // the code for type 3 records reads the type 4 record too.
147                 4 => return Err(Error::MisplacedType4Record(offset)),
148
149                 6 => {
150                     let d = read_document_record(&mut r, e)?;
151                     if document_record.is_some() {
152                         warn(Warning::DuplicateDocumentRecord);
153                     } else {
154                         document_record = d;
155                     }
156                 }
157                 /*
158                                 7 => d.read_extension_record()?,
159                 */
160                 999 => break,
161                 _ => return Err(Error::BadRecordType { offset, rec_type }),
162             }
163         }
164
165         Ok(Reader {
166             r,
167             document_record,
168             variables,
169             value_labels,
170         })
171     }
172 }
173
174 fn read_header<R: Read>(r: &mut R, warn: impl Fn(Warning)) -> Result<FileHeader, Error> {
175     let magic: [u8; 4] = read_bytes(r)?;
176     let (is_zsav, is_ebcdic) = match &magic {
177         ASCII_MAGIC => (false, false),
178         ASCII_ZMAGIC => (true, false),
179         EBCDIC_MAGIC => (false, true),
180         _ => return Err(Error::NotASystemFile),
181     };
182
183     let eye_catcher: [u8; 60] = read_bytes(r)?;
184     let layout_code: [u8; 4] = read_bytes(r)?;
185     let endianness = Endian::identify_u32(2, layout_code)
186         .or_else(|| Endian::identify_u32(2, layout_code))
187         .ok_or_else(|| Error::NotASystemFile)?;
188
189     let nominal_case_size: u32 = endianness.parse(read_bytes(r)?);
190     let nominal_case_size =
191         (nominal_case_size <= i32::MAX as u32 / 16).then_some(nominal_case_size);
192
193     let compression_code: u32 = endianness.parse(read_bytes(r)?);
194     let compression = match (is_zsav, compression_code) {
195         (false, 0) => None,
196         (false, 1) => Some(Compression::Simple),
197         (true, 2) => Some(Compression::ZLib),
198         (false, code) => return Err(Error::InvalidSavCompression(code)),
199         (true, code) => return Err(Error::InvalidZsavCompression(code)),
200     };
201
202     let weight_index: u32 = endianness.parse(read_bytes(r)?);
203     let weight_index = (weight_index > 0).then_some(weight_index - 1);
204
205     let n_cases: u32 = endianness.parse(read_bytes(r)?);
206     let n_cases = (n_cases < i32::MAX as u32 / 2).then_some(n_cases);
207
208     let bias: f64 = endianness.parse(read_bytes(r)?);
209     if bias != 100.0 {
210         warn(Warning::UnexpectedBias(bias))
211     }
212
213     let creation_date: [u8; 9] = read_bytes(r)?;
214     let creation_time: [u8; 8] = read_bytes(r)?;
215     let file_label: [u8; 64] = read_bytes(r)?;
216     let _: [u8; 3] = read_bytes(r)?;
217
218     Ok(FileHeader {
219         magic,
220         is_zsav,
221         is_ebcdic,
222         endianness,
223         weight_index,
224         nominal_case_size,
225         creation_date,
226         creation_time,
227         eye_catcher,
228         file_label,
229     })
230 }
231
232 pub struct VariableRecord {
233     /// Offset from the start of the file to the start of the record.
234     pub offset: u64,
235
236     /// Variable width, in the range -1..=255.
237     pub width: i32,
238
239     /// Variable name, padded on the right with spaces.
240     pub name: [u8; 8],
241
242     /// Print format.
243     pub print_format: u32,
244
245     /// Write format.
246     pub write_format: u32,
247
248     /// Missing value code, one of -3, -2, 0, 1, 2, or 3.
249     pub missing_value_code: i32,
250
251     /// Raw missing values, up to 3 of them.
252     pub missing: Vec<[u8; 8]>,
253
254     /// Optional variable label.
255     pub label: Option<Vec<u8>>,
256 }
257
258 fn read_variable_record<R: Read + Seek>(
259     r: &mut BufReader<R>,
260     e: Endian,
261 ) -> Result<VariableRecord, Error> {
262     let offset = r.stream_position()?;
263     let width: i32 = e.parse(read_bytes(r)?);
264     let has_variable_label: u32 = e.parse(read_bytes(r)?);
265     let missing_value_code: i32 = e.parse(read_bytes(r)?);
266     let print_format: u32 = e.parse(read_bytes(r)?);
267     let write_format: u32 = e.parse(read_bytes(r)?);
268     let name: [u8; 8] = read_bytes(r)?;
269
270     let label = match has_variable_label {
271         0 => None,
272         1 => {
273             let len: u32 = e.parse(read_bytes(r)?);
274             let read_len = len.min(65535) as usize;
275             let label = Some(read_vec(r, read_len)?);
276
277             let padding_bytes = Integer::next_multiple_of(&len, &4) - len;
278             let _ = read_vec(r, padding_bytes as usize)?;
279
280             label
281         }
282         _ => {
283             return Err(Error::BadVariableLabelCode {
284                 offset,
285                 code: has_variable_label,
286             })
287         }
288     };
289
290     let mut missing = Vec::new();
291     if missing_value_code != 0 {
292         match (width, missing_value_code) {
293             (0, -3 | -2 | 1 | 2 | 3) => (),
294             (0, _) => {
295                 return Err(Error::BadNumericMissingValueCode {
296                     offset,
297                     code: missing_value_code,
298                 })
299             }
300             (_, 0..=3) => (),
301             (_, _) => {
302                 return Err(Error::BadStringMissingValueCode {
303                     offset,
304                     code: missing_value_code,
305                 })
306             }
307         }
308
309         for _ in 0..missing_value_code.abs() {
310             missing.push(read_bytes(r)?);
311         }
312     }
313
314     Ok(VariableRecord {
315         offset,
316         width,
317         name,
318         print_format,
319         write_format,
320         missing_value_code,
321         missing,
322         label,
323     })
324 }
325
326 pub struct ValueLabelRecord {
327     /// Offset from the start of the file to the start of the record.
328     pub offset: u64,
329
330     /// The labels.
331     pub labels: Vec<([u8; 8], Vec<u8>)>,
332
333     /// The 0-based indexes of the variables to which the labels are assigned.
334     pub var_indexes: Vec<u32>,
335 }
336
337 pub const MAX_VALUE_LABELS: u32 = u32::MAX / 8;
338
339 fn read_value_label_record<R: Read + Seek>(
340     r: &mut BufReader<R>,
341     e: Endian,
342     n_var_records: usize,
343 ) -> Result<ValueLabelRecord, Error> {
344     let offset = r.stream_position()?;
345     let n: u32 = e.parse(read_bytes(r)?);
346     if n > MAX_VALUE_LABELS {
347         return Err(Error::BadNumberOfValueLabels {
348             offset,
349             n,
350             max: MAX_VALUE_LABELS,
351         });
352     }
353
354     let mut labels = Vec::new();
355     for _ in 0..n {
356         let value: [u8; 8] = read_bytes(r)?;
357         let label_len: u8 = e.parse(read_bytes(r)?);
358         let label_len = label_len as usize;
359         let padded_len = Integer::next_multiple_of(&(label_len + 1), &8);
360
361         let mut label = read_vec(r, padded_len)?;
362         label.truncate(label_len);
363         labels.push((value, label));
364     }
365
366     let rec_type: u32 = e.parse(read_bytes(r)?);
367     if rec_type != 4 {
368         return Err(Error::MissingVariableIndexRecord {
369             offset: r.stream_position()?,
370         });
371     }
372
373     let n_vars: u32 = e.parse(read_bytes(r)?);
374     if n_vars < 1 || n_vars as usize > n_var_records {
375         return Err(Error::BadNumberOfValueLabelVariables {
376             offset: r.stream_position()?,
377             n: n_vars,
378             max: n_var_records as u32,
379         });
380     }
381     let mut var_indexes = Vec::with_capacity(n_vars as usize);
382     for _ in 0..n_vars {
383         var_indexes.push(e.parse(read_bytes(r)?));
384     }
385
386     Ok(ValueLabelRecord {
387         offset,
388         labels,
389         var_indexes,
390     })
391 }
392
393 pub struct DocumentRecord {
394     /// Offset from the start of the file to the start of the record.
395     pub pos: u64,
396
397     /// The document, as an array of 80-byte lines.
398     pub lines: Vec<[u8; DOC_LINE_LEN as usize]>,
399 }
400
401 fn read_document_record<R: Read + Seek>(
402     r: &mut BufReader<R>,
403     e: Endian,
404 ) -> Result<Option<DocumentRecord>, Error> {
405     let offset = r.stream_position()?;
406     let n: u32 = e.parse(read_bytes(r)?);
407     if n == 0 {
408         Ok(None)
409     } else if n > DOC_MAX_LINES {
410         Err(Error::BadDocumentLength {
411             offset,
412             n,
413             max: DOC_MAX_LINES,
414         })
415     } else {
416         let pos = r.stream_position()?;
417         let mut lines = Vec::with_capacity(n as usize);
418         for i in 0..n {
419             let line: [u8; 80] = read_bytes(r)?;
420             lines.push(line);
421         }
422         Ok(Some(DocumentRecord { pos, lines }))
423     }
424 }
425
426 fn read_bytes<const N: usize, R: Read>(r: &mut R) -> Result<[u8; N], IoError> {
427     let mut buf = [0; N];
428     r.read_exact(&mut buf)?;
429     Ok(buf)
430 }
431
432 fn read_vec<R: Read>(r: &mut BufReader<R>, n: usize) -> Result<Vec<u8>, IoError> {
433     let mut vec = vec![0; n];
434     r.read_exact(&mut vec)?;
435     Ok(vec)
436 }
437
438 /*
439 fn trim_end(mut s: Vec<u8>, c: u8) -> Vec<u8> {
440     while s.last() == Some(&c) {
441         s.pop();
442     }
443     s
444 }
445
446 fn skip_bytes<R: Read>(r: &mut R, mut n: u64) -> Result<(), IoError> {
447     let mut buf = [0; 1024];
448     while n > 0 {
449         let chunk = u64::min(n, buf.len() as u64);
450         r.read_exact(&mut buf[0..chunk as usize])?;
451         n -= chunk;
452     }
453     Ok(())
454 }
455
456 */