64e9801447fb4e9ad6f1d567c214cdbe89b6631d
[pspp] / rust / src / lib.rs
1 #![allow(unused_variables)]
2 use endian::{Endian, Parse};
3 use num::Integer;
4 use num_derive::FromPrimitive;
5 use std::io::{BufReader, Error as IoError, Read, Seek};
6 use thiserror::Error;
7
8 pub mod endian;
9
10 #[derive(Error, Debug)]
11 pub enum Error {
12     #[error("Not an SPSS system file")]
13     NotASystemFile,
14
15     #[error("Invalid magic number {0:?}")]
16     BadMagic([u8; 4]),
17
18     #[error("I/O error ({source})")]
19     Io {
20         #[from]
21         source: IoError,
22     },
23
24     #[error("Invalid SAV compression code {0}")]
25     InvalidSavCompression(u32),
26
27     #[error("Invalid ZSAV compression code {0}")]
28     InvalidZsavCompression(u32),
29
30     #[error("Misplaced type 4 record near offset {0:#x}.")]
31     MisplacedType4Record(u64),
32
33     #[error("Document record at offset {offset:#x} has document line count ({n}) greater than the maximum number {max}.")]
34     BadDocumentLength { offset: u64, n: u32, max: u32 },
35
36     #[error("At offset {offset:#x}, Unrecognized record type {rec_type}.")]
37     BadRecordType { offset: u64, rec_type: u32 },
38
39     #[error("At offset {offset:#x}, variable label code ({code}) is not 0 or 1.")]
40     BadVariableLabelCode { offset: u64, code: u32 },
41
42     #[error(
43         "At offset {offset:#x}, numeric missing value code ({code}) is not -3, -2, 0, 1, 2, or 3."
44     )]
45     BadNumericMissingValueCode { offset: u64, code: i32 },
46
47     #[error("At offset {offset:#x}, string missing value code ({code}) is not 0, 1, 2, or 3.")]
48     BadStringMissingValueCode { offset: u64, code: i32 },
49
50     #[error("At offset {offset:#x}, number of value labels ({n}) is greater than the maximum number {max}.")]
51     BadNumberOfValueLabels { offset: u64, n: u32, max: u32 },
52
53     #[error("At offset {offset:#x}, variable index record (type 4) does not immediately follow value label record (type 3) as it should.")]
54     MissingVariableIndexRecord { offset: u64 },
55
56     #[error("At offset {offset:#x}, number of variables associated with a value label ({n}) is not between 1 and the number of variables ({max}).")]
57     BadNumberOfValueLabelVariables { offset: u64, n: u32, max: u32 },
58
59     #[error("At offset {offset:#x}, record type 7 subtype {subtype} is too large with element size {size} and {count} elements.")]
60     ExtensionRecordTooLarge {
61         offset: u64,
62         subtype: u32,
63         size: u32,
64         count: u32,
65     },
66
67     #[error("Wrong ZLIB data header offset {zheader_offset:#x} (expected {offset:#x}).")]
68     BadZlibHeaderOffset { offset: u64, zheader_offset: u64 },
69
70     #[error("At offset {offset:#x}, impossible ZLIB trailer offset {ztrailer_offset:#x}.")]
71     BadZlibTrailerOffset { offset: u64, ztrailer_offset: u64 },
72
73     #[error("At offset {offset:#x}, impossible ZLIB trailer length {ztrailer_len}.")]
74     BadZlibTrailerLen { offset: u64, ztrailer_len: u64 },
75 }
76
77 #[derive(Error, Debug)]
78 pub enum Warning {
79     #[error("Unexpected floating-point bias {0} or unrecognized floating-point format.")]
80     UnexpectedBias(f64),
81
82     #[error("Duplicate type 6 (document) record.")]
83     DuplicateDocumentRecord,
84 }
85
86 #[derive(Copy, Clone, Debug)]
87 pub enum Compression {
88     Simple,
89     ZLib,
90 }
91
92 pub struct Reader<R: Read> {
93     r: BufReader<R>,
94     documents: Vec<DocumentRecord>,
95     variables: Vec<VariableRecord>,
96     value_labels: Vec<ValueLabelRecord>,
97     extensions: Vec<ExtensionRecord>,
98     zheader: Option<ZHeader>,
99 }
100
101 pub struct FileHeader {
102     /// Magic number.
103     pub magic: Magic,
104
105     /// Endianness of the data in the file header.
106     pub endianness: Endian,
107
108     /// 0-based variable index of the weight variable, or `None` if the file is
109     /// unweighted.
110     pub weight_index: Option<u32>,
111
112     /// Number of variable positions, or `None` if the value in the file is
113     /// questionably trustworthy.
114     pub nominal_case_size: Option<u32>,
115
116     /// `dd mmm yy` in the file's encoding.
117     pub creation_date: [u8; 9],
118
119     /// `HH:MM:SS` in the file's encoding.
120     pub creation_time: [u8; 8],
121
122     /// Eye-catcher string, then product name, in the file's encoding.  Padded
123     /// on the right with spaces.
124     pub eye_catcher: [u8; 60],
125
126     /// File label, in the file's encoding.  Padded on the right with spaces.
127     pub file_label: [u8; 64],
128 }
129
130 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
131 pub struct Magic([u8; 4]);
132
133 impl Magic {
134     /// Magic number for a regular system file.
135     pub const SAV: Magic = Magic(*b"$FL2");
136
137     /// Magic number for a system file that contains zlib-compressed data.
138     pub const ZSAV: Magic = Magic(*b"$FL3");
139
140     /// Magic number for an EBDIC-encoded system file.  This is `$FL2` encoded
141     /// in EBCDIC.
142     pub const EBCDIC: Magic = Magic([0x5b, 0xc6, 0xd3, 0xf2]);
143 }
144
145 impl TryFrom<[u8; 4]> for Magic {
146     type Error = Error;
147
148     fn try_from(value: [u8; 4]) -> Result<Self, Self::Error> {
149         let magic = Magic(value);
150         match magic {
151             Magic::SAV | Magic::ZSAV | Magic::EBCDIC => Ok(magic),
152             _ => Err(Error::BadMagic(value)),
153         }
154     }
155 }
156
157 impl<R: Read + Seek> Reader<R> {
158     pub fn new(r: R, warn: impl Fn(Warning)) -> Result<Reader<R>, Error> {
159         let mut r = BufReader::new(r);
160
161         let header = read_header(&mut r, &warn)?;
162         let e = header.endianness;
163         let mut documents = Vec::new();
164         let mut variables = Vec::new();
165         let mut value_labels = Vec::new();
166         let mut extensions = Vec::new();
167         loop {
168             let offset = r.stream_position()?;
169             let rec_type: u32 = e.parse(read_bytes(&mut r)?);
170             match rec_type {
171                 2 => variables.push(read_variable_record(&mut r, e)?),
172                 3 => value_labels.push(read_value_label_record(&mut r, e, variables.len())?),
173                 4 => return Err(Error::MisplacedType4Record(offset)),
174                 6 => documents.push(read_document_record(&mut r, e)?),
175                 7 => extensions.push(read_extension_record(&mut r, e)?),
176                 999 => break,
177                 _ => return Err(Error::BadRecordType { offset, rec_type }),
178             }
179         }
180         let _: [u8; 4] = read_bytes(&mut r)?;
181         let zheader = match header.magic {
182             Magic::ZSAV => Some(read_zheader(&mut r, e)?),
183             _ => None,
184         };
185
186         Ok(Reader {
187             r,
188             documents,
189             variables,
190             value_labels,
191             extensions,
192             zheader,
193         })
194     }
195 }
196
197 fn read_header<R: Read>(r: &mut R, warn: impl Fn(Warning)) -> Result<FileHeader, Error> {
198     let magic: [u8; 4] = read_bytes(r)?;
199     let magic: Magic = magic.try_into().map_err(|_| Error::NotASystemFile)?;
200
201     let eye_catcher: [u8; 60] = read_bytes(r)?;
202     let layout_code: [u8; 4] = read_bytes(r)?;
203     let endianness = Endian::identify_u32(2, layout_code)
204         .or_else(|| Endian::identify_u32(2, layout_code))
205         .ok_or_else(|| Error::NotASystemFile)?;
206
207     let nominal_case_size: u32 = endianness.parse(read_bytes(r)?);
208     let nominal_case_size =
209         (nominal_case_size <= i32::MAX as u32 / 16).then_some(nominal_case_size);
210
211     let compression_code: u32 = endianness.parse(read_bytes(r)?);
212     let compression = match (magic, compression_code) {
213         (Magic::ZSAV, 2) => Some(Compression::ZLib),
214         (Magic::ZSAV, code) => return Err(Error::InvalidZsavCompression(code)),
215         (_, 0) => None,
216         (_, 1) => Some(Compression::Simple),
217         (_, code) => return Err(Error::InvalidSavCompression(code)),
218     };
219
220     let weight_index: u32 = endianness.parse(read_bytes(r)?);
221     let weight_index = (weight_index > 0).then_some(weight_index - 1);
222
223     let n_cases: u32 = endianness.parse(read_bytes(r)?);
224     let n_cases = (n_cases < i32::MAX as u32 / 2).then_some(n_cases);
225
226     let bias: f64 = endianness.parse(read_bytes(r)?);
227     if bias != 100.0 {
228         warn(Warning::UnexpectedBias(bias))
229     }
230
231     let creation_date: [u8; 9] = read_bytes(r)?;
232     let creation_time: [u8; 8] = read_bytes(r)?;
233     let file_label: [u8; 64] = read_bytes(r)?;
234     let _: [u8; 3] = read_bytes(r)?;
235
236     Ok(FileHeader {
237         magic,
238         endianness,
239         weight_index,
240         nominal_case_size,
241         creation_date,
242         creation_time,
243         eye_catcher,
244         file_label,
245     })
246 }
247
248 pub struct VariableRecord {
249     /// Offset from the start of the file to the start of the record.
250     pub offset: u64,
251
252     /// Variable width, in the range -1..=255.
253     pub width: i32,
254
255     /// Variable name, padded on the right with spaces.
256     pub name: [u8; 8],
257
258     /// Print format.
259     pub print_format: u32,
260
261     /// Write format.
262     pub write_format: u32,
263
264     /// Missing value code, one of -3, -2, 0, 1, 2, or 3.
265     pub missing_value_code: i32,
266
267     /// Raw missing values, up to 3 of them.
268     pub missing: Vec<[u8; 8]>,
269
270     /// Optional variable label.
271     pub label: Option<Vec<u8>>,
272 }
273
274 fn read_variable_record<R: Read + Seek>(
275     r: &mut BufReader<R>,
276     e: Endian,
277 ) -> Result<VariableRecord, Error> {
278     let offset = r.stream_position()?;
279     let width: i32 = e.parse(read_bytes(r)?);
280     let has_variable_label: u32 = e.parse(read_bytes(r)?);
281     let missing_value_code: i32 = e.parse(read_bytes(r)?);
282     let print_format: u32 = e.parse(read_bytes(r)?);
283     let write_format: u32 = e.parse(read_bytes(r)?);
284     let name: [u8; 8] = read_bytes(r)?;
285
286     let label = match has_variable_label {
287         0 => None,
288         1 => {
289             let len: u32 = e.parse(read_bytes(r)?);
290             let read_len = len.min(65535) as usize;
291             let label = Some(read_vec(r, read_len)?);
292
293             let padding_bytes = Integer::next_multiple_of(&len, &4) - len;
294             let _ = read_vec(r, padding_bytes as usize)?;
295
296             label
297         }
298         _ => {
299             return Err(Error::BadVariableLabelCode {
300                 offset,
301                 code: has_variable_label,
302             })
303         }
304     };
305
306     let mut missing = Vec::new();
307     if missing_value_code != 0 {
308         match (width, missing_value_code) {
309             (0, -3 | -2 | 1 | 2 | 3) => (),
310             (0, _) => {
311                 return Err(Error::BadNumericMissingValueCode {
312                     offset,
313                     code: missing_value_code,
314                 })
315             }
316             (_, 0..=3) => (),
317             (_, _) => {
318                 return Err(Error::BadStringMissingValueCode {
319                     offset,
320                     code: missing_value_code,
321                 })
322             }
323         }
324
325         for _ in 0..missing_value_code.abs() {
326             missing.push(read_bytes(r)?);
327         }
328     }
329
330     Ok(VariableRecord {
331         offset,
332         width,
333         name,
334         print_format,
335         write_format,
336         missing_value_code,
337         missing,
338         label,
339     })
340 }
341
342 pub struct ValueLabelRecord {
343     /// Offset from the start of the file to the start of the record.
344     pub offset: u64,
345
346     /// The labels.
347     pub labels: Vec<([u8; 8], Vec<u8>)>,
348
349     /// The 0-based indexes of the variables to which the labels are assigned.
350     pub var_indexes: Vec<u32>,
351 }
352
353 pub const MAX_VALUE_LABELS: u32 = u32::MAX / 8;
354
355 fn read_value_label_record<R: Read + Seek>(
356     r: &mut BufReader<R>,
357     e: Endian,
358     n_var_records: usize,
359 ) -> Result<ValueLabelRecord, Error> {
360     let offset = r.stream_position()?;
361     let n: u32 = e.parse(read_bytes(r)?);
362     if n > MAX_VALUE_LABELS {
363         return Err(Error::BadNumberOfValueLabels {
364             offset,
365             n,
366             max: MAX_VALUE_LABELS,
367         });
368     }
369
370     let mut labels = Vec::new();
371     for _ in 0..n {
372         let value: [u8; 8] = read_bytes(r)?;
373         let label_len: u8 = e.parse(read_bytes(r)?);
374         let label_len = label_len as usize;
375         let padded_len = Integer::next_multiple_of(&(label_len + 1), &8);
376
377         let mut label = read_vec(r, padded_len)?;
378         label.truncate(label_len);
379         labels.push((value, label));
380     }
381
382     let rec_type: u32 = e.parse(read_bytes(r)?);
383     if rec_type != 4 {
384         return Err(Error::MissingVariableIndexRecord {
385             offset: r.stream_position()?,
386         });
387     }
388
389     let n_vars: u32 = e.parse(read_bytes(r)?);
390     if n_vars < 1 || n_vars as usize > n_var_records {
391         return Err(Error::BadNumberOfValueLabelVariables {
392             offset: r.stream_position()?,
393             n: n_vars,
394             max: n_var_records as u32,
395         });
396     }
397     let mut var_indexes = Vec::with_capacity(n_vars as usize);
398     for _ in 0..n_vars {
399         var_indexes.push(e.parse(read_bytes(r)?));
400     }
401
402     Ok(ValueLabelRecord {
403         offset,
404         labels,
405         var_indexes,
406     })
407 }
408
409 pub const DOC_LINE_LEN: u32 = 80;
410 pub const DOC_MAX_LINES: u32 = i32::MAX as u32 / DOC_LINE_LEN;
411
412 pub struct DocumentRecord {
413     /// Offset from the start of the file to the start of the record.
414     pub pos: u64,
415
416     /// The document, as an array of 80-byte lines.
417     pub lines: Vec<[u8; DOC_LINE_LEN as usize]>,
418 }
419
420 fn read_document_record<R: Read + Seek>(
421     r: &mut BufReader<R>,
422     e: Endian,
423 ) -> Result<DocumentRecord, Error> {
424     let offset = r.stream_position()?;
425     let n: u32 = e.parse(read_bytes(r)?);
426     match n {
427         0..=DOC_MAX_LINES => {
428             let pos = r.stream_position()?;
429             let mut lines = Vec::with_capacity(n as usize);
430             for _ in 0..n {
431                 let line: [u8; 80] = read_bytes(r)?;
432                 lines.push(line);
433             }
434             Ok(DocumentRecord { pos, lines })
435         }
436         _ => Err(Error::BadDocumentLength {
437             offset,
438             n,
439             max: DOC_MAX_LINES,
440         }),
441     }
442 }
443
444 #[derive(FromPrimitive)]
445 enum Extension {
446     /// Machine integer info.
447     Integer = 3,
448     /// Machine floating-point info.
449     Float = 4,
450     /// Variable sets.
451     VarSets = 5,
452     /// DATE.
453     Date = 6,
454     /// Multiple response sets.
455     Mrsets = 7,
456     /// SPSS Data Entry.
457     DataEntry = 8,
458     /// Extra product info text.
459     ProductInfo = 10,
460     /// Variable display parameters.
461     Display = 11,
462     /// Long variable names.
463     LongNames = 13,
464     /// Long strings.
465     LongStrings = 14,
466     /// Extended number of cases.
467     Ncases = 16,
468     /// Data file attributes.
469     FileAttrs = 17,
470     /// Variable attributes.
471     VarAttrs = 18,
472     /// Multiple response sets (extended).
473     Mrsets2 = 19,
474     /// Character encoding.
475     Encoding = 20,
476     /// Value labels for long strings.
477     LongLabels = 21,
478     /// Missing values for long strings.
479     LongMissing = 22,
480     /// "Format properties in dataview table".
481     Dataview = 24,
482 }
483
484 struct ExtensionRecord {
485     /// Offset from the start of the file to the start of the record.
486     offset: u64,
487
488     /// Record subtype.
489     subtype: u32,
490
491     /// Size of each data element.
492     size: u32,
493
494     /// Number of data elements.
495     count: u32,
496
497     /// `size * count` bytes of data.
498     data: Vec<u8>,
499 }
500
501 fn extension_record_size_requirements(extension: Extension) -> (u32, u32) {
502     match extension {
503         /* Implemented record types. */
504         Extension::Integer => (4, 8),
505         Extension::Float => (8, 3),
506         Extension::VarSets => (1, 0),
507         Extension::Mrsets => (1, 0),
508         Extension::ProductInfo => (1, 0),
509         Extension::Display => (4, 0),
510         Extension::LongNames => (1, 0),
511         Extension::LongStrings => (1, 0),
512         Extension::Ncases => (8, 2),
513         Extension::FileAttrs => (1, 0),
514         Extension::VarAttrs => (1, 0),
515         Extension::Mrsets2 => (1, 0),
516         Extension::Encoding => (1, 0),
517         Extension::LongLabels => (1, 0),
518         Extension::LongMissing => (1, 0),
519
520         /* Ignored record types. */
521         Extension::Date => (0, 0),
522         Extension::DataEntry => (0, 0),
523         Extension::Dataview => (0, 0),
524     }
525 }
526
527 fn read_extension_record<R: Read + Seek>(
528     r: &mut BufReader<R>,
529     e: Endian,
530 ) -> Result<ExtensionRecord, Error> {
531     let subtype = e.parse(read_bytes(r)?);
532     let offset = r.stream_position()?;
533     let size: u32 = e.parse(read_bytes(r)?);
534     let count = e.parse(read_bytes(r)?);
535     let Some(product) = size.checked_mul(count) else {
536         return Err(Error::ExtensionRecordTooLarge {
537             offset,
538             subtype,
539             size,
540             count,
541         });
542     };
543     let offset = r.stream_position()?;
544     let data = read_vec(r, product as usize)?;
545     Ok(ExtensionRecord {
546         offset,
547         subtype,
548         size,
549         count,
550         data,
551     })
552 }
553
554 struct ZHeader {
555     /// File offset to the start of the record.
556     offset: u64,
557
558     /// File offset to the ZLIB data header.
559     zheader_offset: u64,
560
561     /// File offset to the ZLIB trailer.
562     ztrailer_offset: u64,
563
564     /// Length of the ZLIB trailer in bytes.
565     ztrailer_len: u64,
566 }
567
568 fn read_zheader<R: Read + Seek>(r: &mut BufReader<R>, e: Endian) -> Result<ZHeader, Error> {
569     let offset = r.stream_position()?;
570     let zheader_offset: u64 = e.parse(read_bytes(r)?);
571     let ztrailer_offset: u64 = e.parse(read_bytes(r)?);
572     let ztrailer_len: u64 = e.parse(read_bytes(r)?);
573
574     if zheader_offset != offset {
575         return Err(Error::BadZlibHeaderOffset {
576             offset,
577             zheader_offset,
578         });
579     }
580     if ztrailer_offset < offset {
581         return Err(Error::BadZlibTrailerOffset {
582             offset,
583             ztrailer_offset,
584         });
585     }
586     if ztrailer_len < 24 || ztrailer_len % 24 != 0 {
587         return Err(Error::BadZlibTrailerLen {
588             offset,
589             ztrailer_len,
590         });
591     }
592
593     Ok(ZHeader {
594         offset,
595         zheader_offset,
596         ztrailer_offset,
597         ztrailer_len,
598     })
599 }
600
601 fn read_bytes<const N: usize, R: Read>(r: &mut R) -> Result<[u8; N], IoError> {
602     let mut buf = [0; N];
603     r.read_exact(&mut buf)?;
604     Ok(buf)
605 }
606
607 fn read_vec<R: Read>(r: &mut BufReader<R>, n: usize) -> Result<Vec<u8>, IoError> {
608     let mut vec = vec![0; n];
609     r.read_exact(&mut vec)?;
610     Ok(vec)
611 }
612
613 /*
614 fn trim_end(mut s: Vec<u8>, c: u8) -> Vec<u8> {
615     while s.last() == Some(&c) {
616         s.pop();
617     }
618     s
619 }
620
621 fn skip_bytes<R: Read>(r: &mut R, mut n: u64) -> Result<(), IoError> {
622     let mut buf = [0; 1024];
623     while n > 0 {
624         let chunk = u64::min(n, buf.len() as u64);
625         r.read_exact(&mut buf[0..chunk as usize])?;
626         n -= chunk;
627     }
628     Ok(())
629 }
630
631 */