1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::{Result, anyhow, bail};
30use const_default::ConstDefault;
31
32use crate::formats::FormatLog;
33use crate::formats::dcbasenb::dca_to_dcbnb_utf8;
34use crate::formats::utf8::{UTF8FormatSettings, dca_from_utf8};
35use crate::util::ascii::{ascii_is_digit, ascii_is_newline, crlf};
36
37#[derive(ConstDefault, Default, Debug, Clone)]
38pub struct SEMSFormatSettings {
39 pub strict: bool,
40}
41
42fn get_index(res: &[u32]) -> u64 {
43 u64::try_from(res.len()).unwrap_or(0)
45}
46
47pub fn dca_from_sems(
50 content: &[u8],
51 settings: &SEMSFormatSettings,
52) -> Result<(Vec<u32>, FormatLog)> {
53 let bool_strict = settings.strict;
55
56 let mut log: FormatLog = FormatLog::default();
57 let mut res: Vec<u32> = Vec::new();
58 let mut parser_state = "dc";
59 let mut current_dc = String::new();
60
61 let mut idx = 0usize;
62 while let Some(&b) = content.get(idx) {
63 match parser_state {
64 "dc" => {
65 if ascii_is_digit(b) {
66 current_dc.push(char::from(b));
67 } else if b == b' ' || b == b'\n' || b == b'\r' {
68 if !current_dc.is_empty() {
69 let val = current_dc.parse::<u32>()?;
71 res.push(val);
72 current_dc.clear();
73 }
74 } else if b == b'#' {
75 if !current_dc.is_empty() {
76 if bool_strict {
78 log.import_error(get_index(&res), "No trailing space before comment present in sems format while importing. This is not allowed in strict mode.");
79 return Ok((res, log));
80 }
81 log.import_warning(get_index(&res), "No trailing space before comment present in sems format while importing.");
82 let val = current_dc.parse::<u32>()?;
83 res.push(val);
84 current_dc.clear();
85 }
86 res.push(246);
88 parser_state = "comment";
89 } else {
90 log.import_error(
91 get_index(&res),
92 "Invalid character in sems format while importing.",
93 );
94 return Ok((res, log));
95 }
96 }
97 "comment" => {
98 let mut until_next_newline = Vec::new();
101 let mut i = 0usize;
102 while idx.saturating_add(i) < content.len() {
103 let offset = idx.saturating_add(i);
104 let b = content
105 .get(offset)
106 .copied()
107 .ok_or_else(|| anyhow!("Index out of bounds"))?;
108 if ascii_is_newline(b) {
109 parser_state = "dc";
110 break;
113 }
114 until_next_newline.push(b);
115 i = i.saturating_add(1);
116 if idx.saturating_add(i) == content.len() {
117 break;
119 }
120 }
121 let (mapped, inner_log) = dca_from_utf8(
122 &until_next_newline,
123 &UTF8FormatSettings::default(),
124 )?;
125 res.extend(mapped);
126 log.merge(&inner_log);
127 res.push(248);
129 idx = idx.saturating_add(i);
130 }
131 _ => bail!(
132 "Internal error: unexpected parser state while parsing SEMS document"
133 ),
134 }
135
136 idx = idx.saturating_add(1);
137 }
138
139 if parser_state == "comment" {
141 if !current_dc.is_empty() {
142 log.import_error(
143 get_index(&res),
144 format!(
145 "Internal error while parsing sems document: Unconsumed characters at end: {current_dc}."
146 )
147 .as_str(),
148 );
149 return Ok((res, log));
150 }
151 } else if !current_dc.is_empty() {
152 if bool_strict {
153 log.import_error(
154 get_index(&res),
155 "No trailing space present in sems format while importing. This is not allowed in strict mode.",
156 );
157 return Ok((res, log));
158 }
159 log.import_warning(
160 get_index(&res),
161 "No trailing space present in sems format while importing.",
162 );
163 let val = current_dc.parse::<u32>()?;
165 res.push(val);
166 }
167
168 Ok((res, log))
169}
170
171pub fn dca_to_sems(dc_array: &[u32]) -> Result<(Vec<u8>, FormatLog)> {
178 let mut log: FormatLog = FormatLog::default();
179 let mut out: Vec<u8> = Vec::new();
180
181 let mut in_comment = false;
182 let mut at_comment_end = false;
183 let mut current_comment: Vec<u32> = Vec::new();
184
185 for &dc in dc_array {
186 if at_comment_end {
187 at_comment_end = false;
188 }
189 if dc == 246 {
190 in_comment = true;
191 out.push(b'#');
192 } else if dc == 248 {
193 in_comment = false;
194 at_comment_end = true;
195 let (enc, dcbnb_log) = dca_to_dcbnb_utf8(
196 ¤t_comment,
197 &UTF8FormatSettings::default(),
198 )?;
199 log.merge(&dcbnb_log);
200 out.extend(enc);
201 current_comment.clear();
202 out.extend(crlf());
203 } else if in_comment {
204 current_comment.push(dc);
205 } else {
206 out.extend(dc.to_string().as_bytes());
207 out.push(b' ');
208 }
209 }
210
211 if !at_comment_end {
212 out.extend(crlf());
213 }
214
215 Ok((out, log))
216}
217
218#[cfg(test)]
219#[allow(
220 clippy::panic,
221 clippy::expect_used,
222 clippy::unwrap_used,
223 clippy::unwrap_in_result,
224 clippy::panic_in_result_fn,
225 clippy::indexing_slicing,
226 clippy::arithmetic_side_effects,
227 reason = "Standard repository test boilerplate"
228)]
229mod tests {
230 use crate::utilities::assert_vec_u32_eq;
231 use crate::{
232 assert_vec_dc_ok_eq_no_errors, assert_vec_dc_ok_eq_no_warnings,
233 };
234 use ctb_formats_utilities::assert_vec_u8_ok_eq_no_warnings;
235
236 use super::*;
237
238 const SETTINGS: SEMSFormatSettings =
239 <SEMSFormatSettings as ConstDefault>::DEFAULT;
240
241 #[crate::ctb_test]
270 fn test_dca_from_sems_basic_no_trailing_space() {
271 let input = [49u8, 32, 50];
273 let expected = [1, 2];
274 let (actual, _log) =
275 dca_from_sems(&input, &SEMSFormatSettings::default())
276 .expect("dca_from_sems failed");
277 assert_vec_u32_eq(&expected, &actual);
278 }
279
280 #[crate::ctb_test]
292 fn test_dca_to_sems_basic_trailing_space_crlf() {
293 let input = [1, 2];
295 let expected = [49u8, 32, 50, 32, 13, 10];
296 assert_vec_u8_ok_eq_no_warnings(&expected, dca_to_sems(&input));
297 }
298
299 #[crate::ctb_test]
300 fn test_dca_from_sems_comment_preservation() {
301 let input = [49u8, 32, 50, 35, 65];
303 let expected = [1u32, 2, 246, 50, 248];
304 let (_out, log) = assert_vec_dc_ok_eq_no_errors(
305 &expected,
306 dca_from_sems(&input, &SETTINGS),
307 );
308 assert!(log.has_warnings());
309 }
310
311 #[crate::ctb_test]
312 fn test_dca_to_sems_comment_preservation() {
313 let input = [1, 2, 246, 50, 248];
318 let expected = [49u8, 32, 50, 32, 35, 65, 13, 10];
319 assert_vec_u8_ok_eq_no_warnings(&expected, dca_to_sems(&input));
320 }
321
322 #[crate::ctb_test]
323 fn test_dca_from_sems_utf8_comments() {
324 let input: Vec<u8> = vec![
329 50, 53, 54, 32, 50, 53, 56, 32, 50, 54, 48, 32, 50, 54, 50, 32, 50,
330 54, 52, 32, 50, 54, 51, 32, 53, 55, 32, 56, 54, 32, 57, 51, 32, 57,
331 51, 32, 57, 54, 32, 51, 48, 32, 49, 56, 32, 50, 56, 54, 32, 55, 50,
332 32, 57, 54, 32, 57, 57, 32, 57, 51, 32, 56, 53, 32, 50, 56, 55, 32,
333 49, 57, 32, 49, 56, 32, 50, 56, 52, 32, 50, 54, 49, 32, 50, 53, 57,
334 32, 35, 32, 115, 97, 121, 32, 34, 72, 101, 108, 108, 111, 44, 32,
335 47, 87, 111, 114, 108, 100, 47, 33, 32, 226, 154, 189, 34, 10, 49,
336 32, 50, 32, 35, 32, 226, 154, 189, 10,
337 ];
338
339 let expected: Vec<u32> = vec![
340 256, 258, 260, 262, 264, 263, 57, 86, 93, 93, 96, 30, 18, 286, 72,
341 96, 99, 93, 85, 287, 19, 18, 284, 261, 259, 246, 18, 100, 82, 106,
342 18, 20, 57, 86, 93, 93, 96, 30, 18, 33, 72, 96, 99, 93, 85, 33, 19,
343 18, 281, 20, 248, 1, 2, 246, 18, 281, 248,
344 ];
345
346 assert_vec_dc_ok_eq_no_warnings(
347 &expected,
348 dca_from_sems(&input, &SEMSFormatSettings::default()),
349 );
350 }
351
352 #[crate::ctb_test]
353 fn test_sems_comment_basic() {
354 let input = b"12 34 #hello\n56 ";
356 let (dca, _log) =
357 dca_from_sems(input, &SEMSFormatSettings::default()).unwrap();
358 assert!(dca.starts_with(&[12, 34, 246]));
360 assert!(dca.contains(&248));
361 assert!(dca.ends_with(&[56]));
362 }
363}