1#[allow(
37 unused_imports,
38 clippy::wildcard_imports,
39 reason = "Standard workspace module prelude"
40)]
41use crate::utilities::*;
42
43use anyhow::{Context, Result, bail};
44use ctb_formats_dcstring::dc::{SHORT_DC_REGION_END, SHORT_DC_REGION_START};
45use ctb_formats_utilities::FormatLog;
46
47use ctb_formats_dcstring::{DcChar, DcMixedChunk, DcMstr, DcMstring};
48
49fn short_dcs_to_dcmstring(short_dcs: &[u32]) -> Result<DcMstring> {
50 let mut doc = DcMstring::new();
51 for &short_dc in short_dcs {
52 let ch = DcChar::from_short(short_dc);
53 ch.to_short()?;
54 doc.push_char(ch);
55 }
56 Ok(doc)
57}
58
59fn parse_comma_short_dcs(
60 csv_str: &str,
61 log: &mut FormatLog,
62) -> Result<Vec<u32>> {
63 let trimmed = csv_str.trim().trim_end_matches(',');
64 if trimmed.is_empty() {
65 return Ok(Vec::new());
66 }
67 let mut out = Vec::new();
68 for (idx, token) in trimmed.split(',').enumerate() {
69 let piece = token.trim();
70 if piece.is_empty() {
71 out.push(0);
72 continue;
73 }
74 match piece.parse::<u32>() {
75 Ok(val) => out.push(val),
76 Err(_) => {
77 log.import_error(
79 u64::try_from(idx).unwrap_or(u64::MAX),
80 &format!(
81 "Invalid short Dc ID token '{piece}' in dceutils stream"
82 ),
83 );
84 }
85 }
86 }
87 Ok(out)
88}
89
90fn finalize_import_log(
91 raw_log: FormatLog,
92 permissive: bool,
93 format_name: &str,
94) -> Result<FormatLog> {
95 if !permissive && raw_log.has_errors() {
96 let errs = raw_log.get_errors().join("; ");
97 bail!("Input does not conform to valid {format_name} format: {errs}");
98 }
99 if permissive && raw_log.has_errors() {
100 let mut downgraded = FormatLog::default();
101 for w in raw_log.get_warnings() {
102 downgraded.warn(&w);
103 }
104 for err in raw_log.get_errors() {
105 downgraded.warn(&err);
106 }
107 Ok(downgraded)
108 } else {
109 Ok(raw_log)
110 }
111}
112
113pub fn dceutils_to_dcmstring_with_options(
118 bytes: &[u8],
119 format_code: &str,
120 permissive: bool,
121) -> Result<(DcMstring, FormatLog)> {
122 let mut raw_log = FormatLog::default();
123 let doc = match format_code {
124 "cdce" | "legacy_cdce" | "cdce_legacy" | "cdce_lstrict"
125 | "cdce_legacy_strict" => crate::converter::decode_cdce(
126 bytes,
127 format_code != "cdce",
128 matches!(format_code, "cdce_lstrict" | "cdce_legacy_strict"),
129 permissive,
130 &mut raw_log,
131 )?,
132 "dce" | "hex_dce" | "dce_hex" | "3_0a" | "dce_3_0a" | "3_0a_raw"
133 | "dce_3_0a_raw" | "hex_3_0a" | "3_0a_hex" | "dce_3_0a_hex"
134 | "hex_3_0a_raw" | "3_0a_raw_hex" | "dce_3_0a_raw_hex" | "3_01a"
135 | "dce_3_01a" | "3_01a_raw" | "dce_3_01a_raw" | "hex_3_01a"
136 | "3_01a_hex" | "dce_3_01a_hex" | "hex_3_01a_raw" | "3_01a_raw_hex"
137 | "dce_3_01a_raw_hex" | "3_02a" | "dce_3_02a" | "3_02a_raw"
138 | "dce_3_02a_raw" | "hex_3_02a" | "3_02a_hex" | "dce_3_02a_hex"
139 | "hex_3_02a_raw" | "3_02a_raw_hex" | "dce_3_02a_raw_hex" => {
140 let short_dcs =
141 crate::converter::decode_dce_preserving_controls_with_options(
142 bytes,
143 format_code,
144 permissive,
145 &mut raw_log,
146 )?;
147 let body = if let Some(start) =
148 crate::converter::dce_content_start(&short_dcs)
149 {
150 short_dcs
151 .get(start..short_dcs.len().saturating_sub(2))
152 .context("Invalid DCE content boundary")?
153 } else {
154 &short_dcs
155 };
156 short_dcs_to_dcmstring(body)?
157 }
158 "dc" | "dc_id_list" => {
159 let s = std::str::from_utf8(bytes)
160 .context("Invalid UTF-8 in DcIdList document")?;
161 short_dcs_to_dcmstring(&parse_comma_short_dcs(s, &mut raw_log)?)?
162 }
163 "utf8"
164 | "utf32"
165 | "utf8_base64"
166 | "utf8_dc64"
167 | "utf8_dc64_enc"
168 | "utf8_dc64_bin"
169 | "utf8_dc64_bin_hex"
170 | "utf8_dc64_bin_enc"
171 | "utf8_dc64_bin_enc_hex" => {
172 let utf8 = match format_code {
173 "utf8" => bytes.to_vec(),
174 "utf32" => ctb_formats_encoding::unicode::utf32be_to_utf8(bytes)
175 .map_err(|_| anyhow::anyhow!("There was an error decoding UTF-32."))?,
176 "utf8_base64" => ctb_formats_base64::base64_decode(std::str::from_utf8(bytes)?)?,
177 "utf8_dc64" | "utf8_dc64_enc" => crate::converter::decode_utf8_dc64_csv_to_bytes(
178 bytes, format_code == "utf8_dc64_enc", &mut raw_log,
179 )?,
180 _ => crate::converter::decode_utf8_dc64_bin_to_bytes(
181 bytes, format_code.contains("_enc"), format_code.ends_with("_hex"), &mut raw_log,
182 )?,
183 };
184 let (doc, text_log) = ctb_formats_dcstring::converters::utf8::utf8_to_dcmstring_with_options(&utf8, permissive)?;
185 raw_log.merge(&text_log);
186 doc
187 }
188 _ => bail!("Unknown input format."),
189 };
190
191 let (doc, text_log) =
192 ctb_formats_dcstring::converters::utf8::repair_utf8_encapsulations(
193 &doc, permissive,
194 )?;
195 raw_log.merge(&text_log);
196 let log = finalize_import_log(raw_log, permissive, format_code)?;
197 Ok((doc, log))
198}
199
200pub(crate) fn dcmstring_to_dceutils_short_dcs(
205 doc: &ctb_formats_dcstring::DcMstr,
206 target_format: &str,
207 log: &mut FormatLog,
208) -> Result<Vec<u32>> {
209 ctb_formats_dcstring::validate_dcmst(doc.as_bytes())?;
210 let mut short_dcs = Vec::new();
211 let mut char_idx = 0_u64;
212 let mut unmapped_utf8_buf = String::new();
213
214 let supports_b64_encap = matches!(
215 target_format,
216 "dce"
217 | "hex_dce"
218 | "dce_hex"
219 | "3_01a"
220 | "dce_3_01a"
221 | "3_01a_raw"
222 | "dce_3_01a_raw"
223 | "hex_3_01a"
224 | "3_01a_hex"
225 | "dce_3_01a_hex"
226 | "hex_3_01a_raw"
227 | "3_01a_raw_hex"
228 | "dce_3_01a_raw_hex"
229 | "3_02a"
230 | "dce_3_02a"
231 | "3_02a_raw"
232 | "dce_3_02a_raw"
233 | "hex_3_02a"
234 | "3_02a_hex"
235 | "dce_3_02a_hex"
236 | "hex_3_02a_raw"
237 | "3_02a_raw_hex"
238 | "dce_3_02a_raw_hex"
239 | "dc"
240 | "dc_id_list"
241 | "cdce"
242 | "utf8_dc64"
243 | "utf8_dc64_enc"
244 | "utf8_dc64_bin"
245 | "utf8_dc64_bin_hex"
246 | "utf8_dc64_bin_enc"
247 | "utf8_dc64_bin_enc_hex"
248 );
249
250 let flush_unmapped = |buf: &mut String, out: &mut Vec<u32>| {
251 if !buf.is_empty() {
252 out.extend(crate::converter::encode_utf8_to_dc64_encapsulated(
253 buf.as_bytes(),
254 ));
255 buf.clear();
256 }
257 };
258
259 for chunk in doc.chunks() {
260 match chunk {
261 DcMixedChunk::Binary { data, .. }
262 | DcMixedChunk::BinaryWithMetadata { data, .. } => {
263 flush_unmapped(&mut unmapped_utf8_buf, &mut short_dcs);
264 log.export_warning(
265 char_idx,
266 &format!(
267 "Binary encapsulation ({} bytes) cannot be represented in dceutils format ({target_format}) and was omitted.",
268 data.len()
269 ),
270 );
271 char_idx = char_idx.saturating_add(1);
272 }
273 DcMixedChunk::Text(text) => {
274 for DcChar(dcid) in text.chars() {
275 if (SHORT_DC_REGION_START..=SHORT_DC_REGION_END)
276 .contains(&dcid)
277 {
278 flush_unmapped(&mut unmapped_utf8_buf, &mut short_dcs);
279 let offset = dcid.saturating_sub(SHORT_DC_REGION_START);
280 if let Ok(short_id) = u32::try_from(offset) {
281 short_dcs.push(short_id);
282 }
283 } else if dcid <= 0x10_FFFF {
284 let cp = u32::try_from(dcid)
285 .context("Unicode codepoint fits in u32")?;
286 let direct =
287 crate::converter::unicode_codepoint_to_short_dc(cp);
288 if let Some(short_id) = direct {
289 flush_unmapped(
290 &mut unmapped_utf8_buf,
291 &mut short_dcs,
292 );
293 short_dcs.push(short_id);
294 } else if supports_b64_encap
295 && let Some(ch) = char::from_u32(cp)
296 {
297 unmapped_utf8_buf.push(ch);
298 } else {
299 flush_unmapped(
300 &mut unmapped_utf8_buf,
301 &mut short_dcs,
302 );
303 log.export_warning(
304 char_idx,
305 &format!(
306 "Unicode character U+{dcid:04X} cannot be represented in dceutils format ({target_format}) and was omitted."
307 ),
308 );
309 }
310 } else {
311 flush_unmapped(&mut unmapped_utf8_buf, &mut short_dcs);
312 log.export_warning(
313 char_idx,
314 &format!(
315 "Long Dc {dcid} cannot be represented in dceutils format ({target_format}); dceutils formats do not support Dc 308."
316 ),
317 );
318 }
319 char_idx = char_idx.saturating_add(1);
320 }
321 }
322 }
323 }
324
325 flush_unmapped(&mut unmapped_utf8_buf, &mut short_dcs);
326 Ok(short_dcs)
327}
328
329pub fn dcmstring_to_dceutils(
334 doc: &DcMstr,
335 format_code: &str,
336) -> Result<(Vec<u8>, FormatLog)> {
337 dcmstr_to_dceutils_with_options(doc, format_code, false)
338}
339
340pub fn dcmstr_to_dceutils_with_options(
345 doc: &ctb_formats_dcstring::DcMstr,
346 format_code: &str,
347 permissive: bool,
348) -> Result<(Vec<u8>, FormatLog)> {
349 let mut log = FormatLog::default();
350 match format_code {
351 "html" => return ctb_formats_dcstring::converters::eite::dcmstring_to_html(doc),
352 "html_snippet" => return ctb_formats_dcstring::converters::eite::dcmstring_to_html_fragment(doc),
353 _ => {}
354 }
355 if matches!(
356 format_code,
357 "utf8"
358 | "utf32"
359 | "utf8_base64"
360 | "utf8_dc64"
361 | "utf8_dc64_enc"
362 | "utf8_dc64_bin"
363 | "utf8_dc64_bin_hex"
364 | "utf8_dc64_bin_enc"
365 | "utf8_dc64_bin_enc_hex"
366 ) {
367 let (utf8, text_log) = ctb_formats_dcstring::converters::utf8::dcmstr_to_utf8_with_options(
368 doc,
369 &ctb_formats_dcstring::converters::utf8::DcListUtf8Settings {
370 canonicalize_equivalent_dcs: true,
371 permissive,
372 ..Default::default()
373 },
374 )?;
375 log.merge(&text_log);
376 let bytes = match format_code {
377 "utf8" => utf8,
378 "utf32" => ctb_formats_encoding::unicode::utf8_to_utf32be(&utf8)?,
379 "utf8_base64" => {
380 ctb_formats_base64::base64_encode(&utf8).into_bytes()
381 }
382 "utf8_dc64" | "utf8_dc64_enc" => {
383 let digits = if format_code == "utf8_dc64_enc" {
384 crate::converter::encode_utf8_to_dc64_encapsulated(&utf8)
385 } else {
386 crate::converter::encode_bytes_to_dc64(&utf8)
387 };
388 digits
389 .iter()
390 .map(u32::to_string)
391 .collect::<Vec<_>>()
392 .join(",")
393 .into_bytes()
394 }
395 _ => crate::converter::encode_dc64_to_core_bytes(
396 &crate::converter::encode_bytes_to_dc64(&utf8),
397 format_code.contains("_enc"),
398 format_code.ends_with("_hex"),
399 )?,
400 };
401 return Ok((bytes, log));
402 }
403 if matches!(
404 format_code,
405 "cdce"
406 | "legacy_cdce"
407 | "cdce_legacy"
408 | "html_l"
409 | "html_legacy"
410 | "html_legacy_cdce"
411 | "html_snippet_l"
412 | "html_s_legacy"
413 | "html_legacy_cdce_snippet"
414 ) {
415 let bytes = crate::converter::encode_cdce(
416 doc,
417 format_code != "cdce",
418 permissive,
419 &mut log,
420 )?;
421 let bytes = match format_code {
422 "html_l" | "html_legacy" | "html_legacy_cdce" => {
423 crate::legacy::onestep_legacy_cdce_to_html_l(&bytes)?
424 }
425 "html_snippet_l" | "html_s_legacy" | "html_legacy_cdce_snippet" => {
426 crate::legacy::onestep_legacy_cdce_to_html_snippet_l(&bytes)?
427 }
428 _ => bytes,
429 };
430 return Ok((bytes, log));
431 }
432 let short_dcs =
433 dcmstring_to_dceutils_short_dcs(doc, format_code, &mut log)?;
434
435 match format_code {
436 "dce" | "hex_dce" | "dce_hex" | "3_0a" | "dce_3_0a" | "3_0a_raw"
437 | "dce_3_0a_raw" | "hex_3_0a" | "3_0a_hex" | "dce_3_0a_hex"
438 | "hex_3_0a_raw" | "3_0a_raw_hex" | "dce_3_0a_raw_hex" | "3_01a"
439 | "dce_3_01a" | "3_01a_raw" | "dce_3_01a_raw" | "hex_3_01a"
440 | "3_01a_hex" | "dce_3_01a_hex" | "hex_3_01a_raw" | "3_01a_raw_hex"
441 | "dce_3_01a_raw_hex" | "3_02a" | "dce_3_02a" | "3_02a_raw"
442 | "dce_3_02a_raw" | "hex_3_02a" | "3_02a_hex" | "dce_3_02a_hex"
443 | "hex_3_02a_raw" | "3_02a_raw_hex" | "dce_3_02a_raw_hex" => {
444 let bytes = crate::converter::encode_dce_preserving_controls(
445 &short_dcs,
446 format_code,
447 &mut log,
448 )?;
449 Ok((bytes, log))
450 }
451 "dc" | "dc_id_list" => {
452 let short_dcs = crate::converter::content_short_dcs(&short_dcs)?;
453 let csv = short_dcs
454 .iter()
455 .map(u32::to_string)
456 .collect::<Vec<_>>()
457 .join(",");
458 let csv = crate::convert_dc_to_dc_output(&csv, &mut log);
459 Ok((csv.into_bytes(), log))
460 }
461 _ => bail!("Unknown output format."),
462 }
463}
464
465#[cfg(test)]
466#[allow(
467 clippy::panic,
468 clippy::expect_used,
469 clippy::unwrap_used,
470 clippy::unwrap_in_result,
471 clippy::panic_in_result_fn,
472 clippy::indexing_slicing,
473 clippy::arithmetic_side_effects,
474 reason = "Standard repository test boilerplate"
475)]
476mod tests {
477 use super::*;
478
479 #[crate::ctb_test]
480 fn test_dceutils_modern_unicode_export() {
481 let text = "a-b\t\n\r\u{8}\u{b}\u{c}\u{85}\u{fe00}\u{1f304}@123@";
482 let doc = DcMstring::from(text);
483 for format in ["dc", "cdce", "3_01a", "3_01a_raw"] {
484 let (encoded, log) = dcmstring_to_dceutils(&doc, format).unwrap();
485 assert!(
486 log.has_no_errors() && !log.has_warnings(),
487 "{format}: {log:?}"
488 );
489 let decoded =
490 crate::dce_convert_new(&encoded, format, "utf8").unwrap();
491 assert_eq!(decoded, text.as_bytes(), "{format}");
492 }
493 for stubbed in ["3_02a", "3_02a_raw", "hex_3_02a", "hex_3_02a_raw"] {
494 assert!(dcmstring_to_dceutils(&doc, stubbed).is_err());
495 assert!(
496 dceutils_to_dcmstring_with_options(b"\x80A\x81", stubbed, true)
497 .is_err()
498 );
499 }
500 }
501
502 #[crate::ctb_test]
503 fn test_dceutils_modern_wire_roundtrip() {
504 for format in ["3_0a", "3_01a", "3_01a_raw"] {
505 let text = if format == "3_0a" {
506 "Hello!"
507 } else {
508 "\t\n\r\u{8}\u{b}\u{c}\u{fe00}\u{1f304}"
509 };
510 let encoded =
511 crate::dce_convert_new(text.as_bytes(), "utf8", format)
512 .unwrap();
513 let (doc, log) =
514 dceutils_to_dcmstring_with_options(&encoded, format, false)
515 .unwrap();
516 assert!(log.has_no_errors() && !log.has_warnings());
517 let (reencoded, log) = dcmstring_to_dceutils(&doc, format).unwrap();
518 assert!(log.has_no_errors() && !log.has_warnings());
519 assert_eq!(reencoded, encoded, "{format}");
520 }
521 }
522
523 #[crate::ctb_test]
524 fn test_dceutils_permissive_text_import() {
525 for (format, bytes) in [
526 ("3_01a_raw", &b"\x80A\xc3\x9a\xa1\xbf\xa4\xc4B\x81"[..]),
527 ("dc", &b"50,191,151,158,188,161,192,51"[..]),
528 ("utf8_dc64", &b"151,158,188,161"[..]),
529 ] {
530 assert!(
531 dceutils_to_dcmstring_with_options(bytes, format, false)
532 .is_err()
533 );
534 let (doc, log) =
535 dceutils_to_dcmstring_with_options(bytes, format, true)
536 .unwrap();
537 assert!(log.has_warnings() && !log.has_errors());
538 let (text, _) = dcmstring_to_dceutils(&doc, "utf8_dc64").unwrap();
539 let decoded =
540 crate::dce_convert_new(&text, "utf8_dc64", "utf8").unwrap();
541 let expected = if format == "utf8_dc64" {
542 "a\u{FFFD}b"
543 } else {
544 "Aa\u{FFFD}bB"
545 };
546 assert_eq!(decoded, expected.as_bytes(), "{format}");
547 }
548 }
549}