ctb_formats_dcstring/converters/
ascii.rs1#[allow(
24 unused_imports,
25 clippy::wildcard_imports,
26 reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use anyhow::{Result, anyhow, bail};
31use const_default::ConstDefault;
32use ctb_formats_utilities::FormatLog;
33
34use crate::DcMstring;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub enum AsciiUnmappablePolicy {
40 #[default]
43 Skip,
44 Replace(u8),
47 Transliterate,
51 TransformationPipeline,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct AsciiSettings {
59 pub unmappable_policy: AsciiUnmappablePolicy,
61 pub strict_import: bool,
64 pub normalization: Option<crate::DcNormalizationMode>,
66}
67
68impl Default for AsciiSettings {
69 fn default() -> Self {
70 Self::DEFAULT
71 }
72}
73
74impl ConstDefault for AsciiSettings {
75 const DEFAULT: Self = Self {
76 unmappable_policy: AsciiUnmappablePolicy::Skip,
77 strict_import: true,
78 normalization: None,
79 };
80}
81
82pub fn ascii_to_dcmstring(bytes: &[u8]) -> Result<(DcMstring, FormatLog)> {
84 ascii_to_dcmstring_with_settings(bytes, &AsciiSettings::default())
85}
86
87pub fn ascii_to_dcmstring_with_settings(
89 bytes: &[u8],
90 settings: &AsciiSettings,
91) -> Result<(DcMstring, FormatLog)> {
92 let mut log = FormatLog::default();
93
94 if settings.strict_import {
95 for (idx, &b) in bytes.iter().enumerate() {
96 if b > 0x7F {
97 bail!(
98 "Input is not valid ASCII: non-ASCII byte 0x{b:02X} at index {idx}"
99 );
100 }
101 }
102 let (doc, utf8_log) =
103 crate::converters::utf8::utf8_to_dcmstring(bytes)?;
104 log.merge(&utf8_log);
105 Ok((doc, log))
106 } else {
107 let mut sanitized = Vec::with_capacity(bytes.len());
108 for (idx, &b) in bytes.iter().enumerate() {
109 if b <= 0x7F {
110 sanitized.push(b);
111 } else {
112 let idx_u64 = u64::try_from(idx)
113 .map_err(|e| anyhow!("Index conversion overflow: {e}"))?;
114 log.import_warning(
115 idx_u64,
116 &format!("Replaced non-ASCII byte 0x{b:02X} with replacement character"),
117 );
118 sanitized.extend_from_slice(
119 ctb_formats_utf8::UTF8_REPLACEMENT_CHARACTER,
120 );
121 }
122 }
123 let (doc, utf8_log) =
124 crate::converters::utf8::utf8_to_dcmstring(&sanitized)?;
125 log.merge(&utf8_log);
126 Ok((doc, log))
127 }
128}
129
130pub fn dcmstring_to_ascii(doc: &DcMstring) -> Result<(Vec<u8>, FormatLog)> {
132 dcmstring_to_ascii_with_settings(doc, &AsciiSettings::default())
133}
134
135pub fn dcmstring_to_ascii_with_settings(
137 doc: &DcMstring,
138 settings: &AsciiSettings,
139) -> Result<(Vec<u8>, FormatLog)> {
140 let permissive = !settings.strict_import;
141 let normalization = settings.normalization.unwrap_or(if permissive {
143 crate::DcNormalizationMode::RequiredByTarget
144 } else {
145 crate::DcNormalizationMode::None
146 });
147 let (utf8_bytes, mut log) =
148 crate::converters::utf8::dcmstring_to_utf8_with_normalization(
149 doc,
150 permissive,
151 normalization,
152 )?;
153
154 if utf8_bytes.iter().all(|&b| b <= 0x7F) {
156 return Ok((utf8_bytes, log));
157 }
158
159 let utf8_text = std::str::from_utf8(&utf8_bytes)
160 .map_err(|e| anyhow!("Internal UTF-8 conversion error: {e}"))?;
161
162 match settings.unmappable_policy {
163 AsciiUnmappablePolicy::Transliterate => {
164 let transliterated = ctb_formats_utf8::to_ascii_translit(utf8_text);
165 let mut out = Vec::with_capacity(transliterated.len());
166 for (idx, ch) in transliterated.chars().enumerate() {
167 if ch.is_ascii() {
168 let mut buf = [0u8; 4];
169 let encoded = ch.encode_utf8(&mut buf);
170 if let Some(&first) = encoded.as_bytes().first() {
171 out.push(first);
172 }
173 } else {
174 let idx_u64 = u64::try_from(idx).map_err(|e| {
175 anyhow!("Index conversion overflow: {e}")
176 })?;
177 let cp = u32::from(ch);
178 log.export_warning(
179 idx_u64,
180 &format!(
181 "Character '{ch}' (U+{cp:04X}) remains unmappable after transliteration"
182 ),
183 );
184 }
185 }
186 Ok((out, log))
187 }
188 AsciiUnmappablePolicy::TransformationPipeline => {
189 let transliterated = ctb_formats_utf8::to_ascii_translit(utf8_text);
192 let mut out = Vec::with_capacity(transliterated.len());
193 for ch in transliterated.chars() {
194 if ch.is_ascii() {
195 let mut buf = [0u8; 4];
196 let encoded = ch.encode_utf8(&mut buf);
197 if let Some(&first) = encoded.as_bytes().first() {
198 out.push(first);
199 }
200 }
201 }
202 Ok((out, log))
203 }
204 AsciiUnmappablePolicy::Replace(replacement_byte) => {
205 if replacement_byte > 0x7F {
206 bail!(
207 "Replacement byte 0x{replacement_byte:02X} is not a valid 7-bit ASCII character"
208 );
209 }
210 let mut out = Vec::with_capacity(utf8_text.len());
211 for (idx, ch) in utf8_text.chars().enumerate() {
212 if ch.is_ascii() {
213 let mut buf = [0u8; 4];
214 let encoded = ch.encode_utf8(&mut buf);
215 if let Some(&first) = encoded.as_bytes().first() {
216 out.push(first);
217 }
218 } else {
219 let idx_u64 = u64::try_from(idx).map_err(|e| {
220 anyhow!("Index conversion overflow: {e}")
221 })?;
222 let cp = u32::from(ch);
223 log.export_warning(
224 idx_u64,
225 &format!(
226 "Replaced non-ASCII character '{ch}' (U+{cp:04X}) with 0x{replacement_byte:02X}"
227 ),
228 );
229 out.push(replacement_byte);
230 }
231 }
232 Ok((out, log))
233 }
234 AsciiUnmappablePolicy::Skip => {
235 let mut out = Vec::with_capacity(utf8_text.len());
236 for (idx, ch) in utf8_text.chars().enumerate() {
237 if ch.is_ascii() {
238 let mut buf = [0u8; 4];
239 let encoded = ch.encode_utf8(&mut buf);
240 if let Some(&first) = encoded.as_bytes().first() {
241 out.push(first);
242 }
243 } else {
244 let idx_u64 = u64::try_from(idx).map_err(|e| {
245 anyhow!("Index conversion overflow: {e}")
246 })?;
247 let cp = u32::from(ch);
248 log.export_warning(
249 idx_u64,
250 &format!(
251 "Skipped non-ASCII character '{ch}' (U+{cp:04X})"
252 ),
253 );
254 }
255 }
256 Ok((out, log))
257 }
258 }
259}
260
261pub fn is_ascii_printable(b: u8) -> bool {
263 (0x20..=0x7E).contains(&b)
264}
265
266pub fn is_ascii_newline(b: u8) -> bool {
268 b == b'\n' || b == b'\r'
269}
270
271pub fn is_ascii_safe_subset_char(b: u8) -> bool {
274 is_ascii_printable(b) || is_ascii_newline(b)
275}
276
277pub fn ascii_safe_subset_to_dcmstring(
279 bytes: &[u8],
280) -> Result<(DcMstring, FormatLog)> {
281 ascii_safe_subset_to_dcmstring_with_settings(
282 bytes,
283 &AsciiSettings::default(),
284 )
285}
286
287pub fn ascii_safe_subset_to_dcmstring_with_settings(
289 bytes: &[u8],
290 settings: &AsciiSettings,
291) -> Result<(DcMstring, FormatLog)> {
292 let mut log = FormatLog::default();
293 let mut normalized = Vec::with_capacity(bytes.len());
294 let mut i = 0usize;
295
296 while i < bytes.len() {
297 let Some(&b) = bytes.get(i) else { break };
298 if !is_ascii_safe_subset_char(b) {
299 if settings.strict_import {
300 bail!("Invalid ASCII Safe Subset byte: 0x{b:02X} at index {i}");
301 }
302 log.import_warning(
303 u64::try_from(i)
304 .map_err(|e| anyhow!("Index conversion overflow: {e}"))?,
305 &format!("Invalid ASCII Safe Subset byte: 0x{b:02X}"),
306 );
307 match settings.unmappable_policy {
308 AsciiUnmappablePolicy::Replace(rep) => {
309 normalized.push(rep);
310 }
311 AsciiUnmappablePolicy::Skip
312 | AsciiUnmappablePolicy::Transliterate
313 | AsciiUnmappablePolicy::TransformationPipeline => {}
314 }
315 i = i.saturating_add(1);
316 continue;
317 }
318
319 if b == b'\r' {
320 normalized.push(b'\n');
321 if bytes.get(i.saturating_add(1)) == Some(&b'\n') {
322 i = i.saturating_add(2);
323 continue;
324 }
325 } else {
326 normalized.push(b);
327 }
328 i = i.saturating_add(1);
329 }
330
331 let (doc, inner_log) =
332 ascii_to_dcmstring_with_settings(&normalized, settings)?;
333 log.merge(&inner_log);
334 Ok((doc, log))
335}
336
337pub fn dcmstring_to_ascii_safe_subset(
340 doc: &DcMstring,
341) -> Result<(Vec<u8>, FormatLog)> {
342 dcmstring_to_ascii_safe_subset_with_settings(doc, &AsciiSettings::default())
343}
344
345pub fn dcmstring_to_ascii_safe_subset_with_settings(
347 doc: &DcMstring,
348 settings: &AsciiSettings,
349) -> Result<(Vec<u8>, FormatLog)> {
350 let (ascii_bytes, mut log) =
351 dcmstring_to_ascii_with_settings(doc, settings)?;
352
353 let mut out = Vec::with_capacity(ascii_bytes.len().saturating_add(16));
354 let mut i = 0usize;
355
356 while i < ascii_bytes.len() {
357 let Some(&b) = ascii_bytes.get(i) else { break };
358
359 if b == b'\r' {
360 out.extend_from_slice(b"\r\n");
361 if ascii_bytes.get(i.saturating_add(1)) == Some(&b'\n') {
362 i = i.saturating_add(2);
363 continue;
364 }
365 } else if b == b'\n' {
366 out.extend_from_slice(b"\r\n");
367 } else if is_ascii_printable(b) {
368 out.push(b);
369 } else {
370 let idx_u64 = u64::try_from(i)
371 .map_err(|e| anyhow!("Index conversion overflow: {e}"))?;
372 log.export_warning(
373 idx_u64,
374 &format!(
375 "Control byte 0x{b:02X} is not permitted in ASCII Safe Subset"
376 ),
377 );
378 }
379
380 i = i.saturating_add(1);
381 }
382
383 Ok((out, log))
384}
385
386#[cfg(test)]
387#[allow(
388 clippy::panic,
389 clippy::expect_used,
390 clippy::unwrap_used,
391 clippy::unwrap_in_result,
392 clippy::panic_in_result_fn,
393 clippy::indexing_slicing,
394 clippy::arithmetic_side_effects,
395 reason = "Standard repository test boilerplate"
396)]
397mod tests {
398 use super::*;
399
400 #[crate::ctb_test]
401 fn test_ascii_roundtrip_basic() {
402 let input = b"Hello, World!\nTesting ASCII 123.";
403 let (doc, log) = ascii_to_dcmstring(input).expect("parse ascii");
404 assert!(log.has_no_warnings_or_errors());
405 assert_eq!(doc, "Hello, World!\nTesting ASCII 123.");
406
407 let (bytes, export_log) =
408 dcmstring_to_ascii(&doc).expect("export ascii");
409 assert!(export_log.has_no_warnings_or_errors());
410 assert_eq!(bytes, input);
411 }
412
413 #[crate::ctb_test]
414 fn test_ascii_strict_rejects_non_ascii() {
415 let invalid = b"Hello \xFF World";
416 let res = ascii_to_dcmstring(invalid);
417 assert!(res.is_err());
418 assert!(res.unwrap_err().to_string().contains("0xFF"));
419 }
420
421 #[crate::ctb_test]
422 fn test_ascii_permissive_replaces_non_ascii() {
423 let invalid = b"Hello \x80 World";
424 let settings = AsciiSettings {
425 unmappable_policy: AsciiUnmappablePolicy::Skip,
426 strict_import: false,
427 ..Default::default()
428 };
429 let (doc, log) = ascii_to_dcmstring_with_settings(invalid, &settings)
430 .expect("parse");
431 assert!(log.has_warnings());
432 assert_eq!(doc, "Hello \u{FFFD} World");
433
434 let byte_test = b"a\xffb";
435 let (doc2, log2) =
436 ascii_to_dcmstring_with_settings(byte_test, &settings)
437 .expect("parse");
438 assert!(log2.has_warnings());
439 assert_eq!(doc2, "a\u{FFFD}b");
440 }
441
442 #[crate::ctb_test]
443 fn test_ascii_export_transliterate() {
444 let (doc, _) =
445 crate::converters::utf8::utf8_to_dcmstring("Café naïve".as_bytes())
446 .expect("parse utf8");
447 let settings = AsciiSettings {
448 unmappable_policy: AsciiUnmappablePolicy::Transliterate,
449 strict_import: true,
450 ..Default::default()
451 };
452 let (bytes, _) =
453 dcmstring_to_ascii_with_settings(&doc, &settings).expect("export");
454 assert_eq!(std::str::from_utf8(&bytes).unwrap(), "Cafe naive");
455 }
456
457 #[crate::ctb_test]
458 fn test_ascii_export_replace() {
459 let (doc, _) =
460 crate::converters::utf8::utf8_to_dcmstring("Hello 🌍!".as_bytes())
461 .expect("parse utf8");
462 let settings = AsciiSettings {
463 unmappable_policy: AsciiUnmappablePolicy::Replace(b'?'),
464 strict_import: true,
465 ..Default::default()
466 };
467 let (bytes, log) =
468 dcmstring_to_ascii_with_settings(&doc, &settings).expect("export");
469 assert_eq!(std::str::from_utf8(&bytes).unwrap(), "Hello ?!");
470 assert!(log.has_warnings());
471 }
472
473 #[crate::ctb_test]
474 fn test_ascii_export_skip() {
475 let (doc, _) =
476 crate::converters::utf8::utf8_to_dcmstring("Hello 🌍!".as_bytes())
477 .expect("parse utf8");
478 let (bytes, log) = dcmstring_to_ascii(&doc).expect("export");
479 assert_eq!(std::str::from_utf8(&bytes).unwrap(), "Hello !");
480 assert!(log.has_warnings());
481 }
482
483 #[crate::ctb_test]
484 fn test_ascii_safe_subset_roundtrip() {
485 let input = b"Line 1\r\nLine 2\r\n";
486 let (doc, log) =
487 ascii_safe_subset_to_dcmstring(input).expect("parse safe subset");
488 assert!(log.has_no_warnings_or_errors());
489 assert_eq!(doc, "Line 1\nLine 2\n");
490
491 let (out, out_log) =
492 dcmstring_to_ascii_safe_subset(&doc).expect("export safe subset");
493 assert!(out_log.has_no_warnings_or_errors());
494 assert_eq!(out, input);
495 }
496
497 #[crate::ctb_test]
498 fn test_ascii_safe_subset_rejects_control_chars() {
499 let input = b"Hello\tWorld\n";
501 let res = ascii_safe_subset_to_dcmstring(input);
502 assert!(res.is_err());
503 assert!(res.unwrap_err().to_string().contains("0x09"));
504 }
505
506 #[crate::ctb_test]
507 fn test_ascii_safe_subset_export_normalizes_crlf_and_filters_controls() {
508 let (doc, _) = crate::converters::utf8::utf8_to_dcmstring(
509 "Line 1\twith tab\nLine 2".as_bytes(),
510 )
511 .expect("parse utf8");
512 let (out, log) =
513 dcmstring_to_ascii_safe_subset(&doc).expect("export safe subset");
514 assert_eq!(out, b"Line 1with tab\r\nLine 2");
516 assert!(log.has_warnings());
517 }
518}