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