ctb_formats_wfscan/
wfscan.rs1#[allow(
26 unused_imports,
27 clippy::wildcard_imports,
28 reason = "Standard workspace crate prelude"
29)]
30pub(crate) use ctb_utilities::*;
31
32pub mod cli;
33
34use regex::Regex;
35use std::path::Path;
36
37#[cfg(test)]
39pub fn get_wfscan_data(key: &str) -> Option<Vec<u8>> {
40 ctb_utilities::load_manifest_fixture(env!("CARGO_MANIFEST_DIR"), key)
41}
42
43pub fn wfparse(data: &[u8]) -> Result<Vec<u8>> {
46 let decoded = ctb_formats_perl::unicode::perl_utf8_decode(data)?;
47
48 let re_open = Regex::new(r"<\w+>")?;
49 let mut s = re_open.replace_all(&decoded, " ").into_owned();
50
51 let re_close = Regex::new(r"<\\\W+>")?;
52 s = re_close.replace_all(&s, " ").into_owned();
53
54 let re_start_c = Regex::new(r"^C")?;
55 s = re_start_c.replace_all(&s, " ").into_owned();
56
57 s = s.replace('\u{FFFD}', " ");
58 s.push('\n');
59
60 Ok(s.into_bytes())
61}
62
63pub fn wfparse_file<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
65 let data = std::fs::read(path)?;
66 wfparse(&data)
67}
68
69pub fn wfscan(data: &[u8]) -> Result<Vec<u8>> {
72 let mut s: String = data.iter().map(|&b| char::from(b)).collect();
73
74 s = s.replace('\n', " ");
75
76 let re_open = Regex::new(r"<[a-zA-Z0-9_]+>")?;
77 s = re_open.replace_all(&s, " ").into_owned();
78
79 let re_close = Regex::new(r"<\\[^a-zA-Z0-9_]+>")?;
80 s = re_close.replace_all(&s, " ").into_owned();
81
82 let re_non_word = Regex::new(r"[^a-zA-Z0-9_]")?;
83 s = re_non_word.replace_all(&s, " ").into_owned();
84
85 let re_spaces = Regex::new(r" +")?;
86 s = re_spaces.replace_all(&s, " ").into_owned();
87
88 s = s.to_ascii_lowercase();
89
90 s = s.replace(" ,", ",");
91 s.push('\n');
92
93 Ok(s.into_bytes())
94}
95
96pub fn wfscan_file<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
98 let data = std::fs::read(path)?;
99 wfscan(&data)
100}
101
102#[cfg(test)]
103#[allow(
104 clippy::panic,
105 clippy::expect_used,
106 clippy::unwrap_used,
107 clippy::unwrap_in_result,
108 clippy::panic_in_result_fn,
109 clippy::indexing_slicing,
110 clippy::arithmetic_side_effects,
111 reason = "Standard repository test boilerplate"
112)]
113mod tests {
114 use super::*;
115
116 #[crate::ctb_test]
117 fn test_wfparser_wfscan_fixtures() {
118 let input_data = get_wfscan_data("fixtures/Sample with patterns.pan")
119 .expect("input fixture not found");
120 let parser_expected = get_wfscan_data(
121 "fixtures/Sample_with_patterns.pan.parser.expected",
122 )
123 .expect("parser expected fixture not found");
124 let scanner_expected = get_wfscan_data(
125 "fixtures/Sample_with_patterns.pan.scanner.expected",
126 )
127 .expect("scanner expected fixture not found");
128
129 let parser_actual = wfparse(&input_data).expect("wfparse failed");
130 let scanner_actual = wfscan(&input_data).expect("wfscan failed");
131
132 assert_eq!(parser_actual, parser_expected);
133 assert_eq!(scanner_actual, scanner_expected);
134 }
135}