find bad utf8
[pspp] / rust / src / main.rs
1 /* PSPP - a program for statistical analysis.
2  * Copyright (C) 2023 Free Software Foundation, Inc.
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 use anyhow::Result;
18 use clap::Parser;
19 use pspp::raw::{Reader, Record, UnencodedStr, Value};
20 use std::fs::File;
21 use std::io::BufReader;
22 use std::path::{Path, PathBuf};
23 use std::str::{self, from_utf8};
24
25 /// A utility to dissect SPSS system files.
26 #[derive(Parser, Debug)]
27 #[command(author, version, about, long_about = None)]
28 struct Args {
29     /// Maximum number of cases to print.
30     #[arg(long = "data", default_value_t = 0)]
31     max_cases: u64,
32
33     /// Files to dissect.
34     #[arg(required = true)]
35     files: Vec<PathBuf>,
36 }
37
38 fn main() -> Result<()> {
39     let Args { max_cases, files } = Args::parse();
40
41     for file in files {
42         if let Err(error) = dissect(&file, max_cases) {
43             println!("{}: {error}", file.display());
44         }
45     }
46     Ok(())
47 }
48
49 fn dissect(file_name: &Path, _max_cases: u64) -> Result<()> {
50     let reader = File::open(file_name)?;
51     let reader = BufReader::new(reader);
52     let mut reader = Reader::new(reader)?;
53     let records: Vec<Record> = reader.collect_headers()?;
54
55     let mut character_code = None;
56     for record in records {
57         //println!("{record:?}");
58         if let Record::IntegerInfo(ref info) = record {
59             character_code = Some(info.character_code);
60         }
61         if let Record::EndOfHeaders(_) = record {
62             break;
63         };
64     }
65
66     if character_code != Some(65001) {
67         return Ok(());
68     }
69     let mut n = 0;
70     while let Some(Ok(Record::Case(data))) = reader.next() {
71         n += 1;
72         let mut strings = Vec::new();
73         for value in data.iter() {
74             if let Value::String(UnencodedStr(s)) = value {
75                 strings.extend_from_slice(&s[..]);
76             }
77         }
78
79         let mut rest = &strings[..];
80         let mut any_errors = false;
81         while let Err(error) = from_utf8(&rest) {
82             if !any_errors {
83                 print!("{}: UTF-8 error", file_name.display());
84                 any_errors = true;
85             }
86             let start = error.valid_up_to();
87             let len = match error.error_len() {
88                 Some(len) => len,
89                 None => rest.len() - start
90             };
91 //            print!(" {}", (start + len) % 8);
92             print!("[");
93             for i in 0..len {
94                 print!("{:02x}", rest[i + start]);
95             }
96             print!("]");
97             rest = &rest[start + len..];
98         }
99         if any_errors {
100             println!();
101             println!("Lossy: {}", String::from_utf8_lossy(&strings[..]).replace(char::REPLACEMENT_CHARACTER, "??????").replace(&[' ', '\0'], ""));
102             return Ok(())
103         }
104         //println!("{:?}", data);
105     }
106     println!("{}: read {n} records", file_name.display());
107     Ok(())
108 }