c6eabecdbf17bf6942f67874b8f5ef99fb637103
[pspp] / rust / src / cooked.rs
1 use std::{
2     borrow::Cow, cell::RefCell, cmp::Ordering, collections::HashMap, iter::repeat, ops::Range,
3     rc::Rc,
4 };
5
6 use crate::{
7     encoding::{default_encoding, get_encoding, Error as EncodingError},
8     endian::Endian,
9     format::{Error as FormatError, Spec, UncheckedSpec},
10     identifier::{Error as IdError, Identifier},
11     raw::{self, RawDocumentLine, RawStr, RawString, VarDisplayRecord, VarType},
12 };
13 use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
14 use encoding_rs::{DecoderResult, Encoding};
15 use num::integer::div_ceil;
16 use ordered_float::OrderedFloat;
17 use thiserror::Error as ThisError;
18
19 pub use crate::raw::{CategoryLabels, Compression};
20
21 #[derive(ThisError, Debug)]
22 pub enum Error {
23     // XXX this is really an internal error and maybe we should change the
24     // interfaces to make it impossible
25     #[error("Missing header record")]
26     MissingHeaderRecord,
27
28     #[error("{0}")]
29     EncodingError(EncodingError),
30
31     #[error("Using default encoding {0}.")]
32     UsingDefaultEncoding(String),
33
34     #[error("Variable record from offset {:x} to {:x} specifies width {width} not in valid range [-1,255).", offsets.start, offsets.end)]
35     InvalidVariableWidth { offsets: Range<u64>, width: i32 },
36
37     #[error("This file has corrupted metadata written by a buggy version of PSPP.  To ensure that other software can read it correctly, save a new copy of the file.")]
38     InvalidLongMissingValueFormat,
39
40     #[error("File creation date {creation_date} is not in the expected format \"DD MMM YY\" format.  Using 01 Jan 1970.")]
41     InvalidCreationDate { creation_date: String },
42
43     #[error("File creation time {creation_time} is not in the expected format \"HH:MM:SS\" format.  Using midnight.")]
44     InvalidCreationTime { creation_time: String },
45
46     #[error("{id_error}  Renaming variable to {new_name}.")]
47     InvalidVariableName {
48         id_error: IdError,
49         new_name: Identifier,
50     },
51
52     #[error(
53         "Substituting {new_spec} for invalid print format on variable {variable}.  {format_error}"
54     )]
55     InvalidPrintFormat {
56         new_spec: Spec,
57         variable: Identifier,
58         format_error: FormatError,
59     },
60
61     #[error(
62         "Substituting {new_spec} for invalid write format on variable {variable}.  {format_error}"
63     )]
64     InvalidWriteFormat {
65         new_spec: Spec,
66         variable: Identifier,
67         format_error: FormatError,
68     },
69
70     #[error("Renaming variable with duplicate name {duplicate_name} to {new_name}.")]
71     DuplicateVariableName {
72         duplicate_name: Identifier,
73         new_name: Identifier,
74     },
75
76     #[error("Dictionary index {dict_index} is outside valid range [1,{max_index}].")]
77     InvalidDictIndex { dict_index: usize, max_index: usize },
78
79     #[error("Dictionary index {0} refers to a long string continuation.")]
80     DictIndexIsContinuation(usize),
81
82     #[error("Variables associated with value label are not all of identical type.  Variable {numeric_var} is numeric, but variable {string_var} is string.")]
83     ValueLabelsDifferentTypes {
84         numeric_var: Identifier,
85         string_var: Identifier,
86     },
87
88     #[error(
89         "Value labels may not be added to long string variable {0} using record types 3 or 4."
90     )]
91     InvalidLongStringValueLabel(Identifier),
92
93     #[error("Invalid multiple response set name.  {0}")]
94     InvalidMrSetName(IdError),
95
96     #[error("Multiple response set {mr_set} includes unknown variable {short_name}.")]
97     UnknownMrSetVariable {
98         mr_set: Identifier,
99         short_name: Identifier,
100     },
101
102     #[error("Multiple response set {0} has no variables.")]
103     EmptyMrSet(Identifier),
104
105     #[error("Multiple response set {0} has only one variable.")]
106     OneVarMrSet(Identifier),
107
108     #[error("Multiple response set {0} contains both string and numeric variables.")]
109     MixedMrSet(Identifier),
110
111     #[error(
112         "Invalid numeric format for counted value {number} in multiple response set {mr_set}."
113     )]
114     InvalidMDGroupCountedValue { mr_set: Identifier, number: String },
115
116     #[error("Counted value {value} has width {width}, but it must be no wider than {max_width}, the width of the narrowest variable in multiple response set {mr_set}.")]
117     TooWideMDGroupCountedValue {
118         mr_set: Identifier,
119         value: String,
120         width: usize,
121         max_width: u16,
122     },
123
124     #[error("Long string value label for variable {name} has width {width}, which is not in the valid range [{min_width},{max_width}].")]
125     InvalidLongValueLabelWidth {
126         name: Identifier,
127         width: u32,
128         min_width: u16,
129         max_width: u16,
130     },
131
132     #[error("Invalid attribute name.  {0}")]
133     InvalidAttributeName(IdError),
134
135     #[error("Invalid short name in long variable name record.  {0}")]
136     InvalidShortName(IdError),
137
138     #[error("Invalid name in long variable name record.  {0}")]
139     InvalidLongName(IdError),
140
141     #[error("Invalid variable name in very long string record.  {0}")]
142     InvalidLongStringName(IdError),
143
144     #[error("Invalid variable name in long string value label record.  {0}")]
145     InvalidLongStringValueLabelName(IdError),
146
147     #[error("Invalid variable name in attribute record.  {0}")]
148     InvalidAttributeVariableName(IdError),
149
150     // XXX This is risky because `text` might be arbitarily long.
151     #[error("Text string contains invalid bytes for {encoding} encoding: {text}")]
152     MalformedString { encoding: String, text: String },
153
154     #[error("Details TBD")]
155     TBD,
156 }
157
158 #[derive(Clone, Debug)]
159 pub enum Record {
160     Header(HeaderRecord),
161     Variable(VariableRecord),
162     ValueLabel(ValueLabelRecord),
163     Document(DocumentRecord),
164     IntegerInfo(IntegerInfoRecord),
165     FloatInfo(FloatInfoRecord),
166     VariableSets(VariableSetRecord),
167     VarDisplay(VarDisplayRecord),
168     MultipleResponse(MultipleResponseRecord),
169     LongStringMissingValues(LongStringMissingValuesRecord),
170     LongStringValueLabels(LongStringValueLabelRecord),
171     Encoding(EncodingRecord),
172     NumberOfCases(NumberOfCasesRecord),
173     ProductInfo(ProductInfoRecord),
174     LongNames(LongNameRecord),
175     VeryLongStrings(VeryLongStringRecord),
176     FileAttributes(FileAttributeRecord),
177     VariableAttributes(VariableAttributeRecord),
178     OtherExtension(Extension),
179     //Case(Vec<Value>),
180 }
181
182 pub use crate::raw::EncodingRecord;
183 pub use crate::raw::Extension;
184 pub use crate::raw::FloatInfoRecord;
185 pub use crate::raw::IntegerInfoRecord;
186 pub use crate::raw::NumberOfCasesRecord;
187
188 type DictIndex = usize;
189
190 pub struct Variable {
191     pub dict_index: DictIndex,
192     pub short_name: Identifier,
193     pub long_name: Option<Identifier>,
194     pub width: VarWidth,
195 }
196
197 pub struct Decoder {
198     pub compression: Option<Compression>,
199     pub endian: Endian,
200     pub encoding: &'static Encoding,
201     pub variables: HashMap<DictIndex, Variable>,
202     pub var_names: HashMap<Identifier, DictIndex>,
203     n_dict_indexes: usize,
204     n_generated_names: usize,
205 }
206
207 #[derive(Default)]
208 struct Headers<'a> {
209     header: Option<&'a raw::HeaderRecord<RawString>>,
210     variables: Vec<&'a raw::VariableRecord<RawString, RawStr<8>>>,
211     value_labels: Vec<&'a raw::ValueLabelRecord<RawStr<8>, RawString>>,
212     document: Option<&'a raw::DocumentRecord<RawDocumentLine>>,
213     integer_info: Option<&'a raw::IntegerInfoRecord>,
214     float_info: Option<&'a raw::FloatInfoRecord>,
215     variable_sets: Vec<&'a raw::TextRecord>,
216     var_display: Option<&'a raw::VarDisplayRecord>,
217     multiple_response: Vec<&'a raw::MultipleResponseRecord<RawString>>,
218     long_string_value_labels: Vec<&'a raw::LongStringValueLabelRecord>,
219     long_string_missing_values: Vec<&'a raw::LongStringMissingValueRecord>,
220     encoding: Option<&'a raw::EncodingRecord>,
221     number_of_cases: Option<&'a raw::NumberOfCasesRecord>,
222     product_info: Option<&'a raw::TextRecord>,
223     long_names: Option<&'a raw::TextRecord>,
224     very_long_strings: Vec<&'a raw::TextRecord>,
225     file_attributes: Vec<&'a raw::TextRecord>,
226     variable_attributes: Vec<&'a raw::TextRecord>,
227     other_extensions: Vec<&'a raw::Extension>,
228     cases: Option<&'a Rc<RefCell<raw::Cases>>>,
229 }
230
231 fn set_or_warn<T>(option: &mut Option<T>, value: T, warn: &impl Fn(Error)) {
232     if option.is_none() {
233         let _ = option.insert(value);
234     } else {
235         warn(Error::TBD);
236     }
237 }
238
239 impl<'a> Headers<'a> {
240     fn new(headers: &'a Vec<raw::Record>, warn: &impl Fn(Error)) -> Headers<'a> {
241         let mut h = Headers::default();
242         for header in headers {
243             match header {
244                 raw::Record::Header(record) => set_or_warn(&mut h.header, record, warn),
245                 raw::Record::Variable(record) => h.variables.push(record),
246                 raw::Record::ValueLabel(record) => h.value_labels.push(record),
247                 raw::Record::Document(record) => set_or_warn(&mut h.document, record, warn),
248                 raw::Record::IntegerInfo(record) => set_or_warn(&mut h.integer_info, record, warn),
249                 raw::Record::FloatInfo(record) => set_or_warn(&mut h.float_info, record, warn),
250                 raw::Record::VariableSets(record) => h.variable_sets.push(record),
251                 raw::Record::VarDisplay(record) => set_or_warn(&mut h.var_display, record, warn),
252                 raw::Record::MultipleResponse(record) => h.multiple_response.push(record),
253                 raw::Record::LongStringValueLabels(record) => {
254                     h.long_string_value_labels.push(record)
255                 }
256                 raw::Record::LongStringMissingValues(record) => {
257                     h.long_string_missing_values.push(record)
258                 }
259                 raw::Record::Encoding(record) => set_or_warn(&mut h.encoding, record, warn),
260                 raw::Record::NumberOfCases(record) => {
261                     set_or_warn(&mut h.number_of_cases, record, warn)
262                 }
263                 raw::Record::ProductInfo(record) => set_or_warn(&mut h.product_info, record, warn),
264                 raw::Record::LongNames(record) => set_or_warn(&mut h.long_names, record, warn),
265                 raw::Record::VeryLongStrings(record) => h.very_long_strings.push(record),
266                 raw::Record::FileAttributes(record) => h.file_attributes.push(record),
267                 raw::Record::VariableAttributes(record) => h.variable_attributes.push(record),
268                 raw::Record::OtherExtension(record) => h.other_extensions.push(record),
269                 raw::Record::EndOfHeaders(_) => (),
270                 raw::Record::ZHeader(_) => (),
271                 raw::Record::ZTrailer(_) => (),
272                 raw::Record::Cases(record) => set_or_warn(&mut h.cases, record, warn),
273             }
274         }
275         h
276     }
277 }
278
279 pub fn decode(
280     headers: Vec<raw::Record>,
281     encoding: Option<&'static Encoding>,
282     warn: &impl Fn(Error),
283 ) -> Result<Vec<Record>, Error> {
284     let h = Headers::new(&headers, warn);
285     let Some(header) = h.header else {
286         return Err(Error::MissingHeaderRecord);
287     };
288     let encoding = match encoding {
289         Some(encoding) => encoding,
290         None => {
291             let encoding = h.encoding.map(|record| record.0.as_str());
292             let character_code = h.integer_info.map(|record| record.character_code);
293             match get_encoding(encoding, character_code) {
294                 Ok(encoding) => encoding,
295                 Err(err @ EncodingError::Ebcdic) => return Err(Error::EncodingError(err)),
296                 Err(err) => {
297                     warn(Error::EncodingError(err));
298                     // Warn that we're using the default encoding.
299                     default_encoding()
300                 }
301             }
302         }
303     };
304
305     //let mut dictionary = Dictionary::new(encoding);
306
307     let mut decoder = Decoder {
308         compression: header.compression,
309         endian: header.endian,
310         encoding,
311         variables: HashMap::new(),
312         var_names: HashMap::new(),
313         n_dict_indexes: 0,
314         n_generated_names: 0,
315     };
316
317     let mut output = Vec::with_capacity(headers.len());
318
319     // Decode the records that don't use variables at all.
320     if let Some(header) = HeaderRecord::try_decode(&mut decoder, header, warn)? {
321         output.push(Record::Header(header))
322     }
323     if let Some(raw) = h.document {
324         if let Some(document) = DocumentRecord::try_decode(&mut decoder, raw, warn)? {
325             output.push(Record::Document(document))
326         }
327     }
328     if let Some(raw) = h.integer_info {
329         output.push(Record::IntegerInfo(raw.clone()));
330     }
331     if let Some(raw) = h.float_info {
332         output.push(Record::FloatInfo(raw.clone()));
333     }
334     if let Some(raw) = h.product_info {
335         let s = decoder.decode_string_cow(&raw.text.0, warn);
336         output.push(Record::ProductInfo(ProductInfoRecord::parse(&s, warn)?));
337     }
338     if let Some(raw) = h.number_of_cases {
339         output.push(Record::NumberOfCases(raw.clone()))
340     }
341     for &raw in &h.file_attributes {
342         let s = decoder.decode_string_cow(&raw.text.0, warn);
343         output.push(Record::FileAttributes(FileAttributeRecord::parse(
344             &decoder, &s, warn,
345         )?));
346     }
347     for &raw in &h.other_extensions {
348         output.push(Record::OtherExtension(raw.clone()));
349     }
350
351     // Decode the variable records, which are the basis of almost everything
352     // else.
353     for &raw in &h.variables {
354         if let Some(variable) = VariableRecord::try_decode(&mut decoder, raw, warn)? {
355             output.push(Record::Variable(variable));
356         }
357     }
358
359     // Decode value labels and weight variable.  These use indexes into the
360     // variable records, so we need to parse them before those indexes become
361     // invalidated by very long string variables.
362     for &raw in &h.value_labels {
363         if let Some(value_label) = ValueLabelRecord::try_decode(&mut decoder, raw, warn)? {
364             output.push(Record::ValueLabel(value_label));
365         }
366     }
367     // XXX weight
368     if let Some(raw) = h.var_display {
369         output.push(Record::VarDisplay(raw.clone()));
370     }
371
372     // Decode records that use short names.
373     /*
374         for &raw in &h.multiple_response {
375             if let Some(mrr) = MultipleResponseRecord::try_decode(&mut decoder, raw, warn)? {
376                 output.push(Record::MultipleResponse(mrr))
377             }
378         }
379     */
380     for &raw in &h.very_long_strings {
381         let s = decoder.decode_string_cow(&raw.text.0, warn);
382         output.push(Record::VeryLongStrings(VeryLongStringRecord::parse(
383             &decoder, &s, warn,
384         )?));
385     }
386
387     // Rename variables to their long names.
388     for &raw in &h.long_names {
389         let s = decoder.decode_string_cow(&raw.text.0, warn);
390         output.push(Record::LongNames(LongNameRecord::parse(
391             &mut decoder,
392             &s,
393             warn,
394         )?));
395     }
396
397     // Decode recods that use long names.
398     for &raw in &h.variable_attributes {
399         let s = decoder.decode_string_cow(&raw.text.0, warn);
400         output.push(Record::VariableAttributes(VariableAttributeRecord::parse(
401             &decoder, &s, warn,
402         )?));
403     }
404     for &raw in &h.long_string_value_labels {
405         if let Some(mrr) = LongStringValueLabelRecord::try_decode(&mut decoder, raw, warn)? {
406             output.push(Record::LongStringValueLabels(mrr))
407         }
408     }
409     for &raw in &h.long_string_missing_values {
410         if let Some(mrr) = LongStringMissingValuesRecord::try_decode(&mut decoder, raw, warn)? {
411             output.push(Record::LongStringMissingValues(mrr))
412         }
413     }
414     for &raw in &h.variable_sets {
415         let s = decoder.decode_string_cow(&raw.text.0, warn);
416         output.push(Record::VariableSets(VariableSetRecord::parse(&s, warn)?));
417     }
418     Ok(output)
419 }
420
421 impl Decoder {
422     fn generate_name(&mut self) -> Identifier {
423         loop {
424             self.n_generated_names += 1;
425             let name = Identifier::new(&format!("VAR{:03}", self.n_generated_names), self.encoding)
426                 .unwrap();
427             if !self.var_names.contains_key(&name) {
428                 return name;
429             }
430             assert!(self.n_generated_names < usize::MAX);
431         }
432     }
433     fn decode_string_cow<'a>(&self, input: &'a [u8], warn: &impl Fn(Error)) -> Cow<'a, str> {
434         let (output, malformed) = self.encoding.decode_without_bom_handling(input);
435         if malformed {
436             warn(Error::MalformedString {
437                 encoding: self.encoding.name().into(),
438                 text: output.clone().into(),
439             });
440         }
441         output
442     }
443     fn decode_string(&self, input: &[u8], warn: &impl Fn(Error)) -> String {
444         self.decode_string_cow(input, warn).into()
445     }
446     pub fn decode_identifier(
447         &self,
448         input: &[u8],
449         warn: &impl Fn(Error),
450     ) -> Result<Identifier, IdError> {
451         let s = self.decode_string_cow(input, warn);
452         Identifier::new(&s, self.encoding)
453     }
454     fn get_var_by_index(&self, dict_index: usize) -> Result<&Variable, Error> {
455         let max_index = self.n_dict_indexes;
456         if dict_index == 0 || dict_index > max_index {
457             return Err(Error::InvalidDictIndex {
458                 dict_index,
459                 max_index,
460             });
461         }
462         let Some(variable) = self.variables.get(&(dict_index - 1)) else {
463             return Err(Error::DictIndexIsContinuation(dict_index));
464         };
465         Ok(variable)
466     }
467
468     /// Returns `input` decoded from `self.encoding` into UTF-8 such that
469     /// re-encoding the result back into `self.encoding` will have exactly the
470     /// same length in bytes.
471     ///
472     /// XXX warn about errors?
473     fn decode_exact_length<'a>(&self, input: &'a [u8]) -> Cow<'a, str> {
474         if let (s, false) = self.encoding.decode_without_bom_handling(input) {
475             // This is the common case.  Usually there will be no errors.
476             s
477         } else {
478             // Unusual case.  Don't bother to optimize it much.
479             let mut decoder = self.encoding.new_decoder_without_bom_handling();
480             let mut output = String::with_capacity(
481                 decoder
482                     .max_utf8_buffer_length_without_replacement(input.len())
483                     .unwrap(),
484             );
485             let mut rest = input;
486             while !rest.is_empty() {
487                 match decoder.decode_to_string_without_replacement(rest, &mut output, true) {
488                     (DecoderResult::InputEmpty, _) => break,
489                     (DecoderResult::OutputFull, _) => unreachable!(),
490                     (DecoderResult::Malformed(a, b), consumed) => {
491                         let skipped = a as usize + b as usize;
492                         output.extend(repeat('?').take(skipped));
493                         rest = &rest[consumed..];
494                     }
495                 }
496             }
497             assert_eq!(self.encoding.encode(&output).0.len(), input.len());
498             output.into()
499         }
500     }
501 }
502
503 pub trait TryDecode: Sized {
504     type Input<'a>;
505     fn try_decode(
506         decoder: &mut Decoder,
507         input: &Self::Input<'_>,
508         warn: impl Fn(Error),
509     ) -> Result<Option<Self>, Error>;
510 }
511
512 pub trait Decode<Input>: Sized {
513     fn decode(decoder: &Decoder, input: &Input, warn: impl Fn(Error)) -> Self;
514 }
515
516 impl<const N: usize> Decode<RawStr<N>> for String {
517     fn decode(decoder: &Decoder, input: &RawStr<N>, warn: impl Fn(Error)) -> Self {
518         decoder.decode_string(&input.0, &warn)
519     }
520 }
521
522 #[derive(Clone, Debug)]
523 pub struct HeaderRecord {
524     pub eye_catcher: String,
525     pub weight_index: Option<usize>,
526     pub n_cases: Option<u64>,
527     pub creation: NaiveDateTime,
528     pub file_label: String,
529 }
530
531 fn trim_end_spaces(mut s: String) -> String {
532     s.truncate(s.trim_end_matches(' ').len());
533     s
534 }
535
536 impl TryDecode for HeaderRecord {
537     type Input<'a> = crate::raw::HeaderRecord<RawString>;
538
539     fn try_decode(
540         decoder: &mut Decoder,
541         input: &Self::Input<'_>,
542         warn: impl Fn(Error),
543     ) -> Result<Option<Self>, Error> {
544         let eye_catcher = trim_end_spaces(decoder.decode_string(&input.eye_catcher.0, &warn));
545         let file_label = trim_end_spaces(decoder.decode_string(&input.file_label.0, &warn));
546         let creation_date = decoder.decode_string_cow(&input.creation_date.0, &warn);
547         let creation_date =
548             NaiveDate::parse_from_str(&creation_date, "%e %b %Y").unwrap_or_else(|_| {
549                 warn(Error::InvalidCreationDate {
550                     creation_date: creation_date.into(),
551                 });
552                 Default::default()
553             });
554         let creation_time = decoder.decode_string_cow(&input.creation_time.0, &warn);
555         let creation_time =
556             NaiveTime::parse_from_str(&creation_time, "%H:%M:%S").unwrap_or_else(|_| {
557                 warn(Error::InvalidCreationTime {
558                     creation_time: creation_time.into(),
559                 });
560                 Default::default()
561             });
562         Ok(Some(HeaderRecord {
563             eye_catcher,
564             weight_index: input.weight_index.map(|n| n as usize),
565             n_cases: input.n_cases.map(|n| n as u64),
566             creation: NaiveDateTime::new(creation_date, creation_time),
567             file_label,
568         }))
569     }
570 }
571
572 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
573 pub enum VarWidth {
574     Numeric,
575     String(u16),
576 }
577
578 impl PartialOrd for VarWidth {
579     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
580         match (self, other) {
581             (VarWidth::Numeric, VarWidth::Numeric) => Some(Ordering::Equal),
582             (VarWidth::String(a), VarWidth::String(b)) => Some(a.cmp(b)),
583             _ => None,
584         }
585     }
586 }
587
588 impl VarWidth {
589     const MAX_STRING: u16 = 32767;
590
591     fn n_dict_indexes(self) -> usize {
592         match self {
593             VarWidth::Numeric => 1,
594             VarWidth::String(w) => div_ceil(w as usize, 8),
595         }
596     }
597
598     fn width_predicate(
599         a: Option<VarWidth>,
600         b: Option<VarWidth>,
601         f: impl Fn(u16, u16) -> u16,
602     ) -> Option<VarWidth> {
603         match (a, b) {
604             (Some(VarWidth::Numeric), Some(VarWidth::Numeric)) => Some(VarWidth::Numeric),
605             (Some(VarWidth::String(a)), Some(VarWidth::String(b))) => {
606                 Some(VarWidth::String(f(a, b)))
607             }
608             _ => None,
609         }
610     }
611
612     /// Returns the wider of `self` and `other`:
613     /// - Numerical variable widths are equally wide.
614     /// - Longer strings are wider than shorter strings.
615     /// - Numerical and string types are incomparable, so result in `None`.
616     /// - Any `None` in the input yields `None` in the output.
617     pub fn wider(a: Option<VarWidth>, b: Option<VarWidth>) -> Option<VarWidth> {
618         Self::width_predicate(a, b, |a, b| a.max(b))
619     }
620
621     /// Returns the narrower of `self` and `other` (see [`Self::wider`]).
622     pub fn narrower(a: Option<VarWidth>, b: Option<VarWidth>) -> Option<VarWidth> {
623         Self::width_predicate(a, b, |a, b| a.min(b))
624     }
625 }
626
627 impl From<VarWidth> for VarType {
628     fn from(source: VarWidth) -> Self {
629         match source {
630             VarWidth::Numeric => VarType::Numeric,
631             VarWidth::String(_) => VarType::String,
632         }
633     }
634 }
635
636 #[derive(Clone, Debug)]
637 pub struct VariableRecord {
638     pub width: VarWidth,
639     pub name: Identifier,
640     pub print_format: Spec,
641     pub write_format: Spec,
642     pub missing_values: MissingValues,
643     pub label: Option<String>,
644 }
645
646 #[derive(Clone, Debug)]
647 pub struct MissingValues {
648     /// Individual missing values, up to 3 of them.
649     pub values: Vec<Value>,
650
651     /// Optional range of missing values.
652     pub range: Option<(Value, Value)>,
653 }
654
655 impl Decode<raw::MissingValues<RawStr<8>>> for MissingValues {
656     fn decode(
657         decoder: &Decoder,
658         input: &raw::MissingValues<RawStr<8>>,
659         _warn: impl Fn(Error),
660     ) -> Self {
661         MissingValues {
662             values: input
663                 .values
664                 .iter()
665                 .map(|value| Value::decode(value, decoder))
666                 .collect(),
667             range: input
668                 .range
669                 .as_ref()
670                 .map(|(low, high)| (Value::decode(low, decoder), Value::decode(high, decoder))),
671         }
672     }
673 }
674
675 fn decode_format(raw: raw::Spec, width: VarWidth, warn: impl Fn(Spec, FormatError)) -> Spec {
676     UncheckedSpec::try_from(raw)
677         .and_then(Spec::try_from)
678         .and_then(|x| x.check_width_compatibility(width))
679         .unwrap_or_else(|error| {
680             let new_format = Spec::default_for_width(width);
681             warn(new_format, error);
682             new_format
683         })
684 }
685
686 impl TryDecode for VariableRecord {
687     type Input<'a> = raw::VariableRecord<RawString, RawStr<8>>;
688
689     fn try_decode(
690         decoder: &mut Decoder,
691         input: &Self::Input<'_>,
692         warn: impl Fn(Error),
693     ) -> Result<Option<VariableRecord>, Error> {
694         let width = match input.width {
695             0 => VarWidth::Numeric,
696             w @ 1..=255 => VarWidth::String(w as u16),
697             -1 => return Ok(None),
698             _ => {
699                 return Err(Error::InvalidVariableWidth {
700                     offsets: input.offsets.clone(),
701                     width: input.width,
702                 })
703             }
704         };
705         let name = trim_end_spaces(decoder.decode_string(&input.name.0, &warn));
706         let name = match Identifier::new(&name, decoder.encoding) {
707             Ok(name) => {
708                 if !decoder.var_names.contains_key(&name) {
709                     name
710                 } else {
711                     let new_name = decoder.generate_name();
712                     warn(Error::DuplicateVariableName {
713                         duplicate_name: name.clone(),
714                         new_name: new_name.clone(),
715                     });
716                     new_name
717                 }
718             }
719             Err(id_error) => {
720                 let new_name = decoder.generate_name();
721                 warn(Error::InvalidVariableName {
722                     id_error,
723                     new_name: new_name.clone(),
724                 });
725                 new_name
726             }
727         };
728         let variable = Variable {
729             dict_index: decoder.n_dict_indexes,
730             short_name: name.clone(),
731             long_name: None,
732             width,
733         };
734         decoder.n_dict_indexes += width.n_dict_indexes();
735         assert!(decoder
736             .var_names
737             .insert(name.clone(), variable.dict_index)
738             .is_none());
739         assert!(decoder
740             .variables
741             .insert(variable.dict_index, variable)
742             .is_none());
743
744         let print_format = decode_format(input.print_format, width, |new_spec, format_error| {
745             warn(Error::InvalidPrintFormat {
746                 new_spec,
747                 variable: name.clone(),
748                 format_error,
749             })
750         });
751         let write_format = decode_format(input.write_format, width, |new_spec, format_error| {
752             warn(Error::InvalidWriteFormat {
753                 new_spec,
754                 variable: name.clone(),
755                 format_error,
756             })
757         });
758         let label = input
759             .label
760             .as_ref()
761             .map(|label| decoder.decode_string(&label.0, &warn));
762         Ok(Some(VariableRecord {
763             width,
764             name,
765             print_format,
766             write_format,
767             missing_values: MissingValues::decode(decoder, &input.missing_values, warn),
768             label,
769         }))
770     }
771 }
772
773 #[derive(Clone, Debug)]
774 pub struct DocumentRecord(Vec<String>);
775
776 impl TryDecode for DocumentRecord {
777     type Input<'a> = crate::raw::DocumentRecord<RawDocumentLine>;
778
779     fn try_decode(
780         decoder: &mut Decoder,
781         input: &Self::Input<'_>,
782         warn: impl Fn(Error),
783     ) -> Result<Option<Self>, Error> {
784         Ok(Some(DocumentRecord(
785             input
786                 .lines
787                 .iter()
788                 .map(|s| trim_end_spaces(decoder.decode_string(&s.0, &warn)))
789                 .collect(),
790         )))
791     }
792 }
793
794 trait TextRecord
795 where
796     Self: Sized,
797 {
798     const NAME: &'static str;
799     fn parse(input: &str, warn: impl Fn(Error)) -> Result<Self, Error>;
800 }
801
802 #[derive(Clone, Debug)]
803 pub struct VariableSet {
804     pub name: String,
805     pub vars: Vec<String>,
806 }
807
808 impl VariableSet {
809     fn parse(input: &str) -> Result<Self, Error> {
810         let (name, input) = input.split_once('=').ok_or(Error::TBD)?;
811         let vars = input.split_ascii_whitespace().map(String::from).collect();
812         Ok(VariableSet {
813             name: name.into(),
814             vars,
815         })
816     }
817 }
818
819 trait WarnOnError<T> {
820     fn warn_on_error<F: Fn(Error)>(self, warn: &F) -> Option<T>;
821 }
822 impl<T> WarnOnError<T> for Result<T, Error> {
823     fn warn_on_error<F: Fn(Error)>(self, warn: &F) -> Option<T> {
824         match self {
825             Ok(result) => Some(result),
826             Err(error) => {
827                 warn(error);
828                 None
829             }
830         }
831     }
832 }
833
834 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
835 pub enum Value {
836     Number(Option<OrderedFloat<f64>>),
837     String(String),
838 }
839
840 impl Value {
841     pub fn decode(raw: &raw::Value<RawStr<8>>, decoder: &Decoder) -> Self {
842         match raw {
843             raw::Value::Number(x) => Value::Number(x.map(|x| x.into())),
844             raw::Value::String(s) => Value::String(decoder.decode_exact_length(&s.0).into()),
845         }
846     }
847 }
848
849 #[derive(Clone, Debug)]
850 pub struct ValueLabel {
851     pub value: Value,
852     pub label: String,
853 }
854
855 #[derive(Clone, Debug)]
856 pub struct ValueLabelRecord {
857     pub var_type: VarType,
858     pub labels: Vec<ValueLabel>,
859     pub variables: Vec<Identifier>,
860 }
861
862 impl TryDecode for ValueLabelRecord {
863     type Input<'a> = crate::raw::ValueLabelRecord<RawStr<8>, RawString>;
864     fn try_decode(
865         decoder: &mut Decoder,
866         input: &Self::Input<'_>,
867         warn: impl Fn(Error),
868     ) -> Result<Option<ValueLabelRecord>, Error> {
869         let variables: Vec<&Variable> = input
870             .dict_indexes
871             .iter()
872             .filter_map(|&dict_index| {
873                 decoder
874                     .get_var_by_index(dict_index as usize)
875                     .warn_on_error(&warn)
876             })
877             .filter(|&variable| match variable.width {
878                 VarWidth::String(width) if width > 8 => {
879                     warn(Error::InvalidLongStringValueLabel(
880                         variable.short_name.clone(),
881                     ));
882                     false
883                 }
884                 _ => true,
885             })
886             .collect();
887         let mut i = variables.iter();
888         let Some(&first_var) = i.next() else {
889             return Ok(None);
890         };
891         let var_type: VarType = first_var.width.into();
892         for &variable in i {
893             let this_type: VarType = variable.width.into();
894             if var_type != this_type {
895                 let (numeric_var, string_var) = match var_type {
896                     VarType::Numeric => (first_var, variable),
897                     VarType::String => (variable, first_var),
898                 };
899                 warn(Error::ValueLabelsDifferentTypes {
900                     numeric_var: numeric_var.short_name.clone(),
901                     string_var: string_var.short_name.clone(),
902                 });
903                 return Ok(None);
904             }
905         }
906         let labels = input
907             .labels
908             .iter()
909             .map(|raw::ValueLabel { value, label }| {
910                 let label = decoder.decode_string(&label.0, &warn);
911                 let value = Value::decode(value, decoder);
912                 ValueLabel { value, label }
913             })
914             .collect();
915         let variables = variables
916             .iter()
917             .map(|&variable| variable.short_name.clone())
918             .collect();
919         Ok(Some(ValueLabelRecord {
920             var_type,
921             labels,
922             variables,
923         }))
924     }
925 }
926
927 #[derive(Clone, Debug)]
928 pub struct VariableSetRecord(Vec<VariableSet>);
929
930 impl TextRecord for VariableSetRecord {
931     const NAME: &'static str = "variable set";
932     fn parse(input: &str, warn: impl Fn(Error)) -> Result<Self, Error> {
933         let mut sets = Vec::new();
934         for line in input.lines() {
935             if let Some(set) = VariableSet::parse(line).warn_on_error(&warn) {
936                 sets.push(set)
937             }
938         }
939         Ok(VariableSetRecord(sets))
940     }
941 }
942
943 #[derive(Clone, Debug)]
944 pub struct ProductInfoRecord(pub String);
945
946 impl TextRecord for ProductInfoRecord {
947     const NAME: &'static str = "extra product info";
948     fn parse(input: &str, _warn: impl Fn(Error)) -> Result<Self, Error> {
949         Ok(ProductInfoRecord(input.into()))
950     }
951 }
952
953 #[derive(Clone, Debug)]
954 pub struct LongName {
955     pub short_name: Identifier,
956     pub long_name: Identifier,
957 }
958
959 impl LongName {
960     fn new(decoder: &mut Decoder, short_name: &str, long_name: &str) -> Result<LongName, Error> {
961         let short_name =
962             Identifier::new(short_name, decoder.encoding).map_err(Error::InvalidShortName)?;
963         let long_name =
964             Identifier::new(long_name, decoder.encoding).map_err(Error::InvalidLongName)?;
965         Ok(LongName {
966             short_name,
967             long_name,
968         })
969     }
970 }
971
972 #[derive(Clone, Debug)]
973 pub struct LongNameRecord(Vec<LongName>);
974
975 impl LongNameRecord {
976     pub fn parse(decoder: &mut Decoder, input: &str, warn: impl Fn(Error)) -> Result<Self, Error> {
977         let mut names = Vec::new();
978         for pair in input.split('\t').filter(|s| !s.is_empty()) {
979             if let Some((short_name, long_name)) = pair.split_once('=') {
980                 if let Some(long_name) =
981                     LongName::new(decoder, short_name, long_name).warn_on_error(&warn)
982                 {
983                     names.push(long_name);
984                 }
985             } else {
986                 warn(Error::TBD)
987             }
988         }
989         Ok(LongNameRecord(names))
990     }
991 }
992
993 #[derive(Clone, Debug)]
994 pub struct VeryLongString {
995     pub short_name: Identifier,
996     pub length: u16,
997 }
998
999 impl VeryLongString {
1000     fn parse(decoder: &Decoder, input: &str) -> Result<VeryLongString, Error> {
1001         let Some((short_name, length)) = input.split_once('=') else {
1002             return Err(Error::TBD);
1003         };
1004         let short_name =
1005             Identifier::new(short_name, decoder.encoding).map_err(Error::InvalidLongStringName)?;
1006         let length: u16 = length.parse().map_err(|_| Error::TBD)?;
1007         if length > VarWidth::MAX_STRING {
1008             return Err(Error::TBD);
1009         }
1010         Ok(VeryLongString { short_name, length })
1011     }
1012 }
1013
1014 #[derive(Clone, Debug)]
1015 pub struct VeryLongStringRecord(Vec<VeryLongString>);
1016
1017 impl VeryLongStringRecord {
1018     pub fn parse(decoder: &Decoder, input: &str, warn: impl Fn(Error)) -> Result<Self, Error> {
1019         let mut very_long_strings = Vec::new();
1020         for tuple in input
1021             .split('\0')
1022             .map(|s| s.trim_end_matches('\t'))
1023             .filter(|s| !s.is_empty())
1024         {
1025             if let Some(vls) = VeryLongString::parse(decoder, tuple).warn_on_error(&warn) {
1026                 very_long_strings.push(vls)
1027             }
1028         }
1029         Ok(VeryLongStringRecord(very_long_strings))
1030     }
1031 }
1032
1033 #[derive(Clone, Debug)]
1034 pub struct Attribute {
1035     pub name: Identifier,
1036     pub values: Vec<String>,
1037 }
1038
1039 impl Attribute {
1040     fn parse<'a>(
1041         decoder: &Decoder,
1042         input: &'a str,
1043         warn: &impl Fn(Error),
1044     ) -> Result<(Option<Attribute>, &'a str), Error> {
1045         let Some((name, mut input)) = input.split_once('(') else {
1046             return Err(Error::TBD);
1047         };
1048         let mut values = Vec::new();
1049         loop {
1050             let Some((value, rest)) = input.split_once('\n') else {
1051                 return Err(Error::TBD);
1052             };
1053             if let Some(stripped) = value
1054                 .strip_prefix('\'')
1055                 .and_then(|value| value.strip_suffix('\''))
1056             {
1057                 values.push(stripped.into());
1058             } else {
1059                 warn(Error::TBD);
1060                 values.push(value.into());
1061             }
1062             if let Some(rest) = rest.strip_prefix(')') {
1063                 let attribute = Identifier::new(name, decoder.encoding)
1064                     .map_err(Error::InvalidAttributeName)
1065                     .warn_on_error(warn)
1066                     .map(|name| Attribute { name, values });
1067                 return Ok((attribute, rest));
1068             };
1069             input = rest;
1070         }
1071     }
1072 }
1073
1074 #[derive(Clone, Debug)]
1075 pub struct AttributeSet(pub Vec<Attribute>);
1076
1077 impl AttributeSet {
1078     fn parse<'a>(
1079         decoder: &Decoder,
1080         mut input: &'a str,
1081         sentinel: Option<char>,
1082         warn: &impl Fn(Error),
1083     ) -> Result<(AttributeSet, &'a str), Error> {
1084         let mut attributes = Vec::new();
1085         let rest = loop {
1086             match input.chars().next() {
1087                 None => break input,
1088                 c if c == sentinel => break &input[1..],
1089                 _ => {
1090                     let (attribute, rest) = Attribute::parse(decoder, input, &warn)?;
1091                     if let Some(attribute) = attribute {
1092                         attributes.push(attribute);
1093                     }
1094                     input = rest;
1095                 }
1096             }
1097         };
1098         Ok((AttributeSet(attributes), rest))
1099     }
1100 }
1101
1102 #[derive(Clone, Debug)]
1103 pub struct FileAttributeRecord(AttributeSet);
1104
1105 impl FileAttributeRecord {
1106     pub fn parse(decoder: &Decoder, input: &str, warn: impl Fn(Error)) -> Result<Self, Error> {
1107         let (set, rest) = AttributeSet::parse(decoder, input, None, &warn)?;
1108         if !rest.is_empty() {
1109             warn(Error::TBD);
1110         }
1111         Ok(FileAttributeRecord(set))
1112     }
1113 }
1114
1115 #[derive(Clone, Debug)]
1116 pub struct VarAttributeSet {
1117     pub long_var_name: Identifier,
1118     pub attributes: AttributeSet,
1119 }
1120
1121 impl VarAttributeSet {
1122     fn parse<'a>(
1123         decoder: &Decoder,
1124         input: &'a str,
1125         warn: &impl Fn(Error),
1126     ) -> Result<(Option<VarAttributeSet>, &'a str), Error> {
1127         let Some((long_var_name, rest)) = input.split_once(':') else {
1128             return Err(Error::TBD);
1129         };
1130         let (attributes, rest) = AttributeSet::parse(decoder, rest, Some('/'), warn)?;
1131         let var_attribute = Identifier::new(long_var_name, decoder.encoding)
1132             .map_err(Error::InvalidAttributeVariableName)
1133             .warn_on_error(warn)
1134             .map(|name| VarAttributeSet {
1135                 long_var_name: name,
1136                 attributes,
1137             });
1138         Ok((var_attribute, rest))
1139     }
1140 }
1141
1142 #[derive(Clone, Debug)]
1143 pub struct VariableAttributeRecord(Vec<VarAttributeSet>);
1144
1145 impl VariableAttributeRecord {
1146     pub fn parse(decoder: &Decoder, mut input: &str, warn: impl Fn(Error)) -> Result<Self, Error> {
1147         let mut var_attribute_sets = Vec::new();
1148         while !input.is_empty() {
1149             let Some((var_attribute, rest)) =
1150                 VarAttributeSet::parse(decoder, input, &warn).warn_on_error(&warn)
1151             else {
1152                 break;
1153             };
1154             if let Some(var_attribute) = var_attribute {
1155                 var_attribute_sets.push(var_attribute);
1156             }
1157             input = rest;
1158         }
1159         Ok(VariableAttributeRecord(var_attribute_sets))
1160     }
1161 }
1162
1163 #[derive(Clone, Debug)]
1164 pub enum MultipleResponseType {
1165     MultipleDichotomy {
1166         value: Value,
1167         labels: CategoryLabels,
1168     },
1169     MultipleCategory,
1170 }
1171
1172 impl MultipleResponseType {
1173     fn decode(
1174         decoder: &Decoder,
1175         mr_set: &Identifier,
1176         input: &raw::MultipleResponseType,
1177         min_width: VarWidth,
1178         warn: &impl Fn(Error),
1179     ) -> Result<Self, Error> {
1180         let mr_type = match input {
1181             raw::MultipleResponseType::MultipleDichotomy { value, labels } => {
1182                 let value = decoder.decode_string_cow(&value.0, warn);
1183                 let value = match min_width {
1184                     VarWidth::Numeric => {
1185                         let number: f64 = value.trim().parse().map_err(|_| {
1186                             Error::InvalidMDGroupCountedValue {
1187                                 mr_set: mr_set.clone(),
1188                                 number: value.into(),
1189                             }
1190                         })?;
1191                         Value::Number(Some(number.into()))
1192                     }
1193                     VarWidth::String(max_width) => {
1194                         let value = value.trim_end_matches(' ');
1195                         let width = value.len();
1196                         if width > max_width as usize {
1197                             return Err(Error::TooWideMDGroupCountedValue {
1198                                 mr_set: mr_set.clone(),
1199                                 value: value.into(),
1200                                 width,
1201                                 max_width,
1202                             });
1203                         };
1204                         Value::String(value.into())
1205                     }
1206                 };
1207                 MultipleResponseType::MultipleDichotomy {
1208                     value,
1209                     labels: *labels,
1210                 }
1211             }
1212             raw::MultipleResponseType::MultipleCategory => MultipleResponseType::MultipleCategory,
1213         };
1214         Ok(mr_type)
1215     }
1216 }
1217
1218 #[derive(Clone, Debug)]
1219 pub struct MultipleResponseSet {
1220     pub name: Identifier,
1221     pub min_width: VarWidth,
1222     pub max_width: VarWidth,
1223     pub label: String,
1224     pub mr_type: MultipleResponseType,
1225     pub dict_indexes: Vec<DictIndex>,
1226 }
1227
1228 impl MultipleResponseSet {
1229     fn decode(
1230         decoder: &Decoder,
1231         input: &raw::MultipleResponseSet<Cow<str>>,
1232         warn: &impl Fn(Error),
1233     ) -> Result<Self, Error> {
1234         let mr_set_name =
1235             Identifier::new(&input.name, decoder.encoding).map_err(Error::InvalidMrSetName)?;
1236
1237         let mut dict_indexes = Vec::with_capacity(input.short_names.len());
1238         for short_name in input.short_names.iter() {
1239             let short_name = match Identifier::new(&short_name, decoder.encoding) {
1240                 Ok(name) => name,
1241                 Err(error) => {
1242                     warn(Error::InvalidMrSetName(error));
1243                     continue;
1244                 }
1245             };
1246             let Some(&dict_index) = decoder.var_names.get(&short_name) else {
1247                 warn(Error::UnknownMrSetVariable {
1248                     mr_set: mr_set_name.clone(),
1249                     short_name: short_name.clone(),
1250                 });
1251                 continue;
1252             };
1253             dict_indexes.push(dict_index);
1254         }
1255
1256         match dict_indexes.len() {
1257             0 => return Err(Error::EmptyMrSet(mr_set_name)),
1258             1 => return Err(Error::OneVarMrSet(mr_set_name)),
1259             _ => (),
1260         }
1261
1262         let Some((Some(min_width), Some(max_width))) = dict_indexes
1263             .iter()
1264             .map(|dict_index| decoder.variables[dict_index].width)
1265             .map(|w| (Some(w), Some(w)))
1266             .reduce(|(na, wa), (nb, wb)| (VarWidth::narrower(na, nb), VarWidth::wider(wa, wb)))
1267         else {
1268             return Err(Error::MixedMrSet(mr_set_name));
1269         };
1270
1271         let mr_type =
1272             MultipleResponseType::decode(decoder, &mr_set_name, &input.mr_type, min_width, warn)?;
1273
1274         Ok(MultipleResponseSet {
1275             name: mr_set_name,
1276             min_width,
1277             max_width,
1278             label: input.label.to_string(),
1279             mr_type,
1280             dict_indexes,
1281         })
1282     }
1283 }
1284
1285 #[derive(Clone, Debug)]
1286 pub struct MultipleResponseRecord(pub Vec<MultipleResponseSet>);
1287
1288 impl TryDecode for MultipleResponseRecord {
1289     type Input<'a> = raw::MultipleResponseRecord<Cow<'a, str>>;
1290
1291     fn try_decode(
1292         decoder: &mut Decoder,
1293         input: &Self::Input<'_>,
1294         warn: impl Fn(Error),
1295     ) -> Result<Option<Self>, Error> {
1296         let mut sets = Vec::with_capacity(input.0.len());
1297         for set in &input.0 {
1298             match MultipleResponseSet::decode(decoder, set, &warn) {
1299                 Ok(set) => sets.push(set),
1300                 Err(error) => warn(error),
1301             }
1302         }
1303         Ok(Some(MultipleResponseRecord(sets)))
1304     }
1305 }
1306
1307 #[derive(Clone, Debug)]
1308 pub struct LongStringMissingValues {
1309     /// Variable name.
1310     pub var_name: Identifier,
1311
1312     /// Missing values.
1313     pub missing_values: MissingValues,
1314 }
1315
1316 impl LongStringMissingValues {
1317     fn decode(
1318         decoder: &Decoder,
1319         input: &raw::LongStringMissingValues,
1320         warn: &impl Fn(Error),
1321     ) -> Result<Self, Error> {
1322         let var_name = decoder.decode_string(&input.var_name.0, warn);
1323         let var_name = Identifier::new(var_name.trim_end(), decoder.encoding)
1324             .map_err(Error::InvalidLongStringValueLabelName)?;
1325
1326         let missing_values = MissingValues::decode(decoder, &input.missing_values, warn);
1327
1328         Ok(LongStringMissingValues {
1329             var_name,
1330             missing_values,
1331         })
1332     }
1333 }
1334
1335 #[derive(Clone, Debug)]
1336 pub struct LongStringMissingValuesRecord(Vec<LongStringMissingValues>);
1337
1338 impl TryDecode for LongStringMissingValuesRecord {
1339     type Input<'a> = raw::LongStringMissingValueRecord;
1340
1341     fn try_decode(
1342         decoder: &mut Decoder,
1343         input: &Self::Input<'_>,
1344         warn: impl Fn(Error),
1345     ) -> Result<Option<Self>, Error> {
1346         let mut labels = Vec::with_capacity(input.0.len());
1347         for label in &input.0 {
1348             match LongStringMissingValues::decode(decoder, label, &warn) {
1349                 Ok(set) => labels.push(set),
1350                 Err(error) => warn(error),
1351             }
1352         }
1353         Ok(Some(LongStringMissingValuesRecord(labels)))
1354     }
1355 }
1356
1357 #[derive(Clone, Debug)]
1358 pub struct LongStringValueLabels {
1359     pub var_name: Identifier,
1360     pub width: VarWidth,
1361     pub labels: Vec<ValueLabel>,
1362 }
1363
1364 impl LongStringValueLabels {
1365     fn decode(
1366         decoder: &Decoder,
1367         input: &raw::LongStringValueLabels,
1368         warn: &impl Fn(Error),
1369     ) -> Result<Self, Error> {
1370         let var_name = decoder.decode_string(&input.var_name.0, warn);
1371         let var_name = Identifier::new(var_name.trim_end(), decoder.encoding)
1372             .map_err(Error::InvalidLongStringValueLabelName)?;
1373
1374         let min_width = 9;
1375         let max_width = VarWidth::MAX_STRING;
1376         if input.width < 9 || input.width > max_width as u32 {
1377             return Err(Error::InvalidLongValueLabelWidth {
1378                 name: var_name,
1379                 width: input.width,
1380                 min_width,
1381                 max_width,
1382             });
1383         }
1384         let width = input.width as u16;
1385
1386         let mut labels = Vec::with_capacity(input.labels.len());
1387         for (value, label) in input.labels.iter() {
1388             let value = Value::String(decoder.decode_exact_length(&value.0).into());
1389             let label = decoder.decode_string(&label.0, warn);
1390             labels.push(ValueLabel { value, label });
1391         }
1392
1393         Ok(LongStringValueLabels {
1394             var_name,
1395             width: VarWidth::String(width),
1396             labels,
1397         })
1398     }
1399 }
1400
1401 #[derive(Clone, Debug)]
1402 pub struct LongStringValueLabelRecord(pub Vec<LongStringValueLabels>);
1403
1404 impl TryDecode for LongStringValueLabelRecord {
1405     type Input<'a> = raw::LongStringValueLabelRecord;
1406
1407     fn try_decode(
1408         decoder: &mut Decoder,
1409         input: &Self::Input<'_>,
1410         warn: impl Fn(Error),
1411     ) -> Result<Option<Self>, Error> {
1412         let mut labels = Vec::with_capacity(input.0.len());
1413         for label in &input.0 {
1414             match LongStringValueLabels::decode(decoder, label, &warn) {
1415                 Ok(set) => labels.push(set),
1416                 Err(error) => warn(error),
1417             }
1418         }
1419         Ok(Some(LongStringValueLabelRecord(labels)))
1420     }
1421 }
1422
1423 #[cfg(test)]
1424 mod test {
1425     use encoding_rs::WINDOWS_1252;
1426
1427     #[test]
1428     fn test() {
1429         let mut s = String::new();
1430         s.push(char::REPLACEMENT_CHARACTER);
1431         let encoded = WINDOWS_1252.encode(&s).0;
1432         let decoded = WINDOWS_1252.decode(&encoded[..]).0;
1433         println!("{:?}", decoded);
1434     }
1435
1436     #[test]
1437     fn test2() {
1438         let charset: Vec<u8> = (0..=255).collect();
1439         println!("{}", charset.len());
1440         let decoded = WINDOWS_1252.decode(&charset[..]).0;
1441         println!("{}", decoded.len());
1442         let encoded = WINDOWS_1252.encode(&decoded[..]).0;
1443         println!("{}", encoded.len());
1444         assert_eq!(&charset[..], &encoded[..]);
1445     }
1446 }