ctb_formats_dcstring/converters/
dctext.rs1#[allow(
28 unused_imports,
29 clippy::wildcard_imports,
30 reason = "Standard workspace module prelude"
31)]
32use crate::utilities::*;
33
34use crate::DcString;
35use crate::dc_char::DcChar;
36use crate::dc_char::DcCharExt;
37use crate::dc_number::{
38 integer_to_dc_number_global, read_dc_number_global,
39 read_dc_number_global_with_resolver, read_dc_number_short,
40};
41use crate::dc_str::DcStr;
42use anyhow::Result;
43use ctb_formats_dcdata::dc::{DC_ESCAPE, DC_LOCAL_NODE, DC_LONG_DC};
44use ctb_formats_dcdata::syntax::{
45 DcRole, SyntaxRuleResolver, default_syntax_resolver,
46};
47use ctb_formats_dctf::{
48 decode_dctf, decode_utf_8e_128, encode_dctf_buf, encode_utf_8e_128_buf,
49};
50use ctb_formats_utilities::{ConversionOutput, FormatLog};
51
52pub type DcList = Vec<u128>;
54
55pub fn dctext_to_dcstring(
73 document: &[u8],
74) -> Result<ConversionOutput<DcString>> {
75 let mut log = FormatLog::default();
76 let mut dc_string = DcString::with_capacity(document.len());
77 let mut i = 0usize;
78
79 while i < document.len() {
80 let Some(slice) = document.get(i..) else {
81 break;
82 };
83 let Some(&first_byte) = slice.first() else {
84 break;
85 };
86
87 if first_byte == b'@' {
88 if let Some(rest) = slice.get(1..) {
89 if let Some(end_rel) = rest.iter().position(|&b| b == b'@') {
90 if let Some(token_bytes) = rest.get(..end_rel) {
91 if let Ok(token_str) = std::str::from_utf8(token_bytes)
92 {
93 if token_str.is_empty() {
94 dc_string.push(DcChar(64u128));
96 i = i.saturating_add(2);
97 continue;
98 }
99
100 if let Ok(ctb_storage_minimal::shorthand::DcShorthand::Local(int_val)) =
101 ctb_storage_minimal::shorthand::DcShorthand::parse(token_str)
102 {
103 let malachite_val = malachite::Integer::from(int_val);
104 match integer_to_dc_number_global(&malachite_val) {
105 Ok(dc_num_gids) => {
106 dc_string.push(DC_LOCAL_NODE);
107 for gid in dc_num_gids {
108 dc_string.push(DcChar(gid));
109 }
110 i = i
111 .saturating_add(2)
112 .saturating_add(end_rel);
113 continue;
114 }
115 Err(e) => {
116 log.warn(&format!(
117 "Failed to encode Dc number for local node @{token_str}@: {e}"
118 ));
119 }
120 }
121 } else if let Ok(dcid) = token_str.parse::<u128>() {
122 dc_string.push(DcChar(dcid));
123 i = i.saturating_add(2).saturating_add(end_rel);
124 continue;
125 }
126 }
127 }
128 }
129 }
130 }
131
132 if let Some((codepoint, size)) =
133 ctb_formats_dctf::decode_dctf_buf(slice)
134 {
135 dc_string.push(DcChar(codepoint));
136 i = i.saturating_add(size);
137 } else if let Some((codepoint, size)) =
138 ctb_formats_dctf::decode_utf_8e_128_buf(slice)
139 {
140 dc_string.push(DcChar(codepoint));
141 i = i.saturating_add(size);
142 } else if let Some((codepoint, size)) = decode_dctf(slice) {
143 dc_string.push(DcChar(codepoint));
144 i = i.saturating_add(size);
145 } else {
146 dc_string.push(DcChar(u128::from(first_byte)));
147 i = i.saturating_add(1);
148 }
149 }
150
151 Ok(ConversionOutput::new(dc_string, log))
152}
153
154pub fn dctext_to_dclist(document: &[u8]) -> Result<ConversionOutput<DcList>> {
159 let out = dctext_to_dcstring(document)?;
160 Ok(ConversionOutput::new(out.result.to_dclist(), out.log))
161}
162
163pub fn dclist_to_dctext(dclist: &[u128]) -> Vec<u8> {
165 dclist_to_dctext_with_resolver(dclist, default_syntax_resolver().as_ref())
166}
167
168pub fn dclist_to_dctext_with_resolver(
170 dclist: &[u128],
171 resolver: &dyn SyntaxRuleResolver,
172) -> Vec<u8> {
173 let mut output = String::new();
174 let mut i = 0;
175 while i < dclist.len() {
176 let Some(&dcid) = dclist.get(i) else { break };
177
178 if dcid == 64 {
179 output.push_str("@@");
180 } else if dcid <= 0x10_FFFF {
181 if let Ok(cp) = u32::try_from(dcid) {
182 if let Some(ch) = char::from_u32(cp) {
183 output.push(ch);
184 } else {
185 output.push_str(&format!("@{dcid}@"));
186 }
187 } else {
188 output.push_str(&format!("@{dcid}@"));
189 }
190 } else if resolver.token_fills_role(dcid, DcRole::LocalNode) {
191 if let Some(rest) = dclist.get(i.saturating_add(1)..) {
192 if let Ok((int_val, consumed)) =
193 read_dc_number_global_with_resolver(rest, resolver)
194 {
195 output.push_str(&format!("@L{int_val}@"));
196 i = i.saturating_add(1).saturating_add(consumed);
197 continue;
198 }
199 }
200 output.push_str(&format!("@{dcid}@"));
201 } else {
202 output.push_str(&format!("@{dcid}@"));
203 }
204 i = i.saturating_add(1);
205 }
206 output.into_bytes()
207}
208
209pub fn dclist_to_dctf(dclist: &[u128]) -> Vec<u8> {
211 let mut output = Vec::new();
212 let mut buf = [0u8; 24];
213 for &dcid in dclist {
214 let n = encode_dctf_buf(&mut buf, dcid);
215 if let Some(slice) = buf.get(..n) {
216 output.extend_from_slice(slice);
217 }
218 }
219 output
220}
221
222pub fn dctf_to_dclist(document: &[u8]) -> DcList {
224 let mut list = Vec::new();
225 let mut i = 0;
226 while i < document.len() {
227 let Some(slice) = document.get(i..) else {
228 break;
229 };
230 if let Some((codepoint, size)) = decode_dctf(slice) {
231 list.push(codepoint);
232 i = i.saturating_add(size);
233 } else {
234 if let Some(&b) = document.get(i) {
235 list.push(u128::from(b));
236 }
237 i = i.saturating_add(1);
238 }
239 }
240 list
241}
242
243pub fn dclist_to_dcutf(dclist: &[u128]) -> Vec<u8> {
245 let mut output = Vec::new();
246 let mut buf = [0u8; 24];
247 for &dcid in dclist {
248 let n = encode_utf_8e_128_buf(&mut buf, dcid);
249 if let Some(slice) = buf.get(..n) {
250 output.extend_from_slice(slice);
251 }
252 }
253 output
254}
255
256pub fn dcutf_to_dclist(document: &[u8]) -> DcList {
258 let mut list = Vec::new();
259 let mut i = 0;
260 while i < document.len() {
261 let Some(slice) = document.get(i..) else {
262 break;
263 };
264 if let Some((codepoint, size)) = decode_utf_8e_128(slice) {
265 list.push(codepoint);
266 i = i.saturating_add(size);
267 } else {
268 if let Some(&b) = document.get(i) {
269 list.push(u128::from(b));
270 }
271 i = i.saturating_add(1);
272 }
273 }
274 list
275}
276
277pub fn dcarray_to_dcstring(
281 dc_array: &[u32],
282) -> Result<ConversionOutput<DcString>> {
283 let conv = dcarray_to_dclist(dc_array)?;
284 let mut dc_string = DcString::with_capacity(conv.result.len());
285 for &dc in &conv.result {
286 dc_string.push(DcChar(dc));
287 }
288 Ok(ConversionOutput::new(dc_string, conv.log))
289}
290
291pub fn dcstring_to_dcarray(s: &DcStr) -> Result<ConversionOutput<Vec<u32>>> {
293 dclist_to_dcarray(&s.to_dclist())
294}
295
296#[must_use]
298pub fn dcstring_to_dctext(s: &DcStr) -> Vec<u8> {
299 let dclist = s.to_dclist();
300 dclist_to_dctext(&dclist)
301}
302
303pub fn dctext_to_dcmstring(
305 bytes: &[u8],
306) -> Result<(crate::DcMstring, FormatLog)> {
307 dctext_to_dcmstring_with_options(bytes, false)
308}
309
310pub fn dctext_to_dcmstring_with_options(
312 bytes: &[u8],
313 permissive: bool,
314) -> Result<(crate::DcMstring, FormatLog)> {
315 let conv = dctext_to_dcstring(bytes)?;
316 if !permissive && conv.log.has_errors() {
317 bail!(
318 "Invalid DcText token(s): {}",
319 conv.log.get_errors().join("; ")
320 );
321 }
322 let policy = if permissive {
323 crate::DcProjectionPolicy::forgiving()
324 } else {
325 crate::DcProjectionPolicy::strict()
326 };
327 let doc =
328 crate::DcMstring::from_dc_string_with_policy(&conv.result, &policy)?;
329 Ok((doc, conv.log))
330}
331
332pub fn dcmstring_to_dctext(
334 doc: &crate::DcMstring,
335) -> Result<(Vec<u8>, FormatLog)> {
336 let dc_string = super::document_dc_string(doc)?;
337 let bytes = dcstring_to_dctext(&dc_string);
338 Ok((bytes, FormatLog::default()))
339}
340
341pub fn dctext_to_dctf(document: Vec<u8>) -> Result<Vec<u8>> {
346 let out = dctext_to_dcstring(&document)?;
347 out.log.auto_log();
348 Ok(out.result.into_bytes())
349}
350
351#[must_use]
353pub fn dctf_to_dctext(document: Vec<u8>) -> Vec<u8> {
354 let dclist = dctf_to_dclist(&document);
355 dclist_to_dctext(&dclist)
356}
357
358pub fn dctext_to_dcutf(document: Vec<u8>) -> Result<Vec<u8>> {
363 let out = dctext_to_dcstring(&document)?;
364 out.log.auto_log();
365 Ok(dclist_to_dcutf(&out.result.to_dclist()))
366}
367
368#[must_use]
370pub fn dcutf_to_dctext(document: Vec<u8>) -> Vec<u8> {
371 let dclist = dcutf_to_dclist(&document);
372 dclist_to_dctext(&dclist)
373}
374
375pub fn dcarray_to_dclist(dc_array: &[u32]) -> Result<ConversionOutput<DcList>> {
384 let mut log = FormatLog::default();
385 let mut list = Vec::with_capacity(dc_array.len());
386 let mut i = 0usize;
387
388 while i < dc_array.len() {
389 let Some(&raw_dc) = dc_array.get(i) else {
390 break;
391 };
392 let dc = DcChar::from_short(raw_dc);
393
394 if dc.fills_role(DcRole::Escape) {
395 if let Some(&next_raw) = dc_array.get(i.saturating_add(1)) {
396 let next_dc = DcChar::from_short(next_raw);
397 if next_dc.fills_role(DcRole::LongDc) {
398 list.push(DC_LONG_DC.to_long());
399 i = i.saturating_add(2);
400 continue;
401 }
402 if next_dc.fills_role(DcRole::Escape) {
403 list.push(DC_ESCAPE.to_long());
404 i = i.saturating_add(2);
405 continue;
406 }
407 }
408 list.push(DC_ESCAPE.to_long());
409 i = i.saturating_add(1);
410 continue;
411 }
412
413 if dc.fills_role(DcRole::LongDc) {
414 if let Some(rest) = dc_array.get(i.saturating_add(1)..) {
415 match read_dc_number_short(rest) {
416 Ok((int_val, consumed)) => {
417 if int_val >= 0 {
418 if let Ok(abs_u128) =
419 u128::try_from(int_val.unsigned_abs_ref())
420 {
421 list.push(abs_u128);
422 i = i
423 .saturating_add(1)
424 .saturating_add(consumed);
425 continue;
426 }
427 }
428 log.warn(&format!(
429 "Embedded long Dc ID {int_val} at index {i} cannot be represented as u128"
430 ));
431 }
432 Err(e) => {
433 log.warn(&format!(
434 "Unescaped Dc 308 at index {i} not followed by valid Dc number: {e}"
435 ));
436 }
437 }
438 } else {
439 log.warn(&format!(
440 "Unescaped Dc 308 at end of stream (index {i}) missing Dc number"
441 ));
442 }
443 list.push(DC_LONG_DC.to_long());
444 i = i.saturating_add(1);
445 continue;
446 }
447
448 if raw_dc > ctb_formats_eite::encoding::pack32::PACK32_MAX {
449 log.warn(&format!(
450 "Short Dc ID {raw_dc} at index {i} exceeds pack32 maximum range (1114111)"
451 ));
452 }
453
454 list.push(dc.to_long());
455 i = i.saturating_add(1);
456 }
457
458 Ok(ConversionOutput::new(list, log))
459}
460
461pub fn dcarray_to_dctext(
463 dc_array: &[u32],
464) -> Result<ConversionOutput<Vec<u8>>> {
465 let conv = dcarray_to_dclist(dc_array)?;
466 let text_bytes = dclist_to_dctext(&conv.result);
467 Ok(ConversionOutput::new(text_bytes, conv.log))
468}
469
470pub fn dclist_to_dcarray(
478 dclist: &[u128],
479) -> Result<ConversionOutput<Vec<u32>>> {
480 let log = FormatLog::default();
481 let mut result = Vec::new();
482
483 for &dcid in dclist {
484 result.extend(DcChar::from_long(dcid).to_short_vec());
485 }
486
487 Ok(ConversionOutput::new(result, log))
488}
489
490pub fn dctext_to_dcarray(
492 document: &[u8],
493) -> Result<ConversionOutput<Vec<u32>>> {
494 let conv = dctext_to_dclist(document)?;
495 let array_conv = dclist_to_dcarray(&conv.result)?;
496 let mut total_log = conv.log;
497 total_log.merge(&array_conv.log);
498 Ok(ConversionOutput::new(array_conv.result, total_log))
499}
500
501pub fn format_blob_preview(data: &[u8], is_dctext: bool) -> String {
506 let raw_bytes = if is_dctext {
507 dctf_to_dctext(data.to_vec())
508 } else {
509 data.to_vec()
510 };
511 if let Ok(s) = String::from_utf8(raw_bytes) {
512 let displayable = s
513 .chars()
514 .all(|c| c.is_ascii_graphic() || c.is_ascii_whitespace());
515 if displayable {
516 if s.len() > 60 {
517 let truncated: String = s.chars().take(60).collect();
518 if s.chars().count() > 60 {
519 format!("{truncated}...")
520 } else {
521 truncated
522 }
523 } else {
524 s
525 }
526 } else {
527 format!("<binary data: {} bytes>", data.len())
528 }
529 } else {
530 format!("<binary data: {} bytes>", data.len())
531 }
532}
533
534#[cfg(test)]
535#[allow(
536 clippy::panic,
537 clippy::expect_used,
538 clippy::unwrap_used,
539 clippy::unwrap_in_result,
540 clippy::panic_in_result_fn,
541 clippy::indexing_slicing,
542 clippy::arithmetic_side_effects,
543 reason = "Standard repository test boilerplate"
544)]
545mod tests {
546 use super::*;
547 use ctb_formats_dcdata::DC_INTEGER;
548 use ctb_formats_dcdata::dc::{
549 DC_BASE64_START, DC_BEGIN_NUMBER, DC_END_NUMBER, SHORT_DC_REGION_START,
550 };
551
552 #[crate::ctb_test]
553 fn test_format_blob_preview() {
554 assert_eq!(format_blob_preview(b"hello world", false), "hello world");
555 assert_eq!(
556 format_blob_preview(&[0u8, 1u8, 2u8], false),
557 "<binary data: 3 bytes>"
558 );
559 let long_str = "a".repeat(70);
560 assert_eq!(
561 format_blob_preview(long_str.as_bytes(), false),
562 format!("{}...", "a".repeat(60))
563 );
564 let dctf_redirect = dctext_to_dctf(b"@1114409@@L42@".to_vec()).unwrap();
565 assert_eq!(format_blob_preview(&dctf_redirect, true), "@1114409@@L42@");
566 }
567
568 #[crate::ctb_test]
569 fn test_dctext_to_dcutf() {
570 let text = "hi @64@ @@ @65@ @128@ there 🥴 @L42@ noncharacter @1114111@ surrogate @56191@ unicode null @0@ dc null @1114112@ @2147483648@ 2^128-1 @340282366920938463463374607431768211455@";
571 let dcutf = dctext_to_dcutf(text.as_bytes().to_vec()).unwrap();
572 assert_eq!(
573 "686920402040204120c28020746865726520f09fa5b420ff84849084a8ff8484908086ff8488a08387ff84849082a9ff8484908087206e6f6e63686172616374657220f48fbfbf20737572726f6761746520edadbf20756e69636f6465206e756c6c2000206463206e756c6c20ff848490808020ff8682808080808020325e3132382d3120ff9683bfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbf",
574 bin2hex(&dcutf)
575 );
576
577 let roundtrip = dcutf_to_dctext(dcutf.clone());
578 let roundtrip_str = String::from_utf8(roundtrip).unwrap();
579
580 let expected_roundtrip = "hi @@ @@ A \u{80} there 🥴 @L42@ noncharacter \u{10ffff} surrogate @56191@ unicode null \u{0} dc null @1114112@ @2147483648@ 2^128-1 @340282366920938463463374607431768211455@";
582 assert!(roundtrip_str.eq(expected_roundtrip));
583 }
584
585 #[crate::ctb_test]
586 fn test_dctext_to_dcstring() {
587 let text = "hi @64@ @@ @65@ @128@ there 🥴 @L42@";
588 let out = dctext_to_dcstring(text.as_bytes()).unwrap();
589 let dc_string = out.result;
590 assert_eq!(
591 dc_string.as_bytes(),
592 dctext_to_dctf(text.as_bytes().to_vec()).unwrap().as_slice()
593 );
594
595 let roundtrip = dcstring_to_dctext(&dc_string);
596 let roundtrip_str = String::from_utf8(roundtrip).unwrap();
597 assert_eq!(roundtrip_str, "hi @@ @@ A \u{80} there 🥴 @L42@");
598 }
599
600 #[crate::ctb_test]
601 fn test_dcarray_to_dctext_and_back() {
602 let original_dcarray = vec![0, 1, 18, 50, 200, 297];
603 let converted = dcarray_to_dctext(&original_dcarray)
604 .expect("conversion should succeed");
605 assert!(!converted.log.has_warnings());
606 assert_eq!(
607 String::from_utf8(converted.result.clone()).expect("valid utf-8"),
608 "@1114112@@1114113@@1114130@@1114162@@1114312@@1114409@"
609 );
610
611 let back = dctext_to_dcarray(&converted.result)
612 .expect("reverse conversion should succeed");
613 assert!(!back.log.has_warnings());
614 assert_eq!(back.result, original_dcarray);
615 }
616
617 #[crate::ctb_test]
618 fn test_dctext_to_dcarray_direct_short_dc() {
619 let input = b"@1114500@";
621 let out = dctext_to_dcarray(input).expect("conversion should succeed");
622 assert!(!out.log.has_warnings());
623 assert_eq!(out.result, vec![388]);
624
625 let back = dcarray_to_dclist(&out.result)
626 .expect("reverse conversion should succeed");
627 assert_eq!(back.result, vec![1_114_500]);
628 }
629
630 #[crate::ctb_test]
631 fn test_dclist_to_dcarray_dc308_embedding_roundtrip() {
632 let original_dclist = vec![2_228_423, 4_294_967_296, 100_000_000_000];
634 let array_out =
635 dclist_to_dcarray(&original_dclist).expect("should succeed");
636 assert!(!array_out.log.has_warnings());
637 assert!(array_out.result.contains(&DC_LONG_DC.to_short().unwrap()));
638
639 let back = dcarray_to_dclist(&array_out.result)
640 .expect("reverse conversion should succeed");
641 assert!(!back.log.has_warnings());
642 assert_eq!(back.result, original_dclist);
643 }
644
645 #[crate::ctb_test]
646 fn test_dclist_to_dcarray_unicode_lossless_roundtrip() {
647 let original_dclist = vec![65, 32, 129_396, 55_296];
649 let array_out =
650 dclist_to_dcarray(&original_dclist).expect("should succeed");
651 assert!(!array_out.log.has_warnings());
652 assert!(array_out.result.contains(&DC_LONG_DC.to_short().unwrap()));
653
654 let back = dcarray_to_dclist(&array_out.result)
655 .expect("reverse conversion should succeed");
656 assert!(!back.log.has_warnings());
657 assert_eq!(back.result, original_dclist);
658 }
659
660 #[crate::ctb_test]
661 fn test_dc308_escaping_roundtrip() {
662 let original_dclist = vec![DC_LONG_DC.to_long()];
664 let array_out =
665 dclist_to_dcarray(&original_dclist).expect("should succeed");
666 assert_eq!(
667 array_out.result,
668 vec![
669 DC_ESCAPE.to_short().unwrap(),
670 DC_LONG_DC.to_short().unwrap()
671 ]
672 );
673
674 let back = dcarray_to_dclist(&array_out.result)
675 .expect("reverse conversion should succeed");
676 assert_eq!(back.result, original_dclist);
677 }
678
679 #[crate::ctb_test]
680 fn test_dc255_escaping_roundtrip() {
681 let original_dclist = vec![DC_ESCAPE.to_long()];
683 let array_out =
684 dclist_to_dcarray(&original_dclist).expect("should succeed");
685 assert_eq!(
686 array_out.result,
687 vec![DC_ESCAPE.to_short().unwrap(), DC_ESCAPE.to_short().unwrap()]
688 );
689
690 let back = dcarray_to_dclist(&array_out.result)
691 .expect("reverse conversion should succeed");
692 assert_eq!(back.result, original_dclist);
693 }
694
695 #[crate::ctb_test]
696 fn test_dc308_followed_by_dc_number_disambiguation() {
697 let original_dclist = vec![
699 DC_LONG_DC.to_long(),
700 DC_BEGIN_NUMBER.to_long(),
701 DC_INTEGER.to_long(),
702 DC_BASE64_START.to_long(),
703 DC_END_NUMBER.to_long(),
704 ];
705 let array_out =
706 dclist_to_dcarray(&original_dclist).expect("should succeed");
707 assert_eq!(
708 array_out.result.get(0..2),
709 Some(
710 &[
711 DC_ESCAPE.to_short().unwrap(),
712 DC_LONG_DC.to_short().unwrap()
713 ][..]
714 )
715 );
716
717 let back = dcarray_to_dclist(&array_out.result)
718 .expect("reverse conversion should succeed");
719 assert_eq!(back.result, original_dclist);
720 }
721
722 #[crate::ctb_test]
723 fn test_dcarray_to_dclist_standalone_dc308() {
724 let dc_array = vec![DC_LONG_DC.to_short().unwrap(), 65];
726 let back = dcarray_to_dclist(&dc_array).expect("should succeed");
727 assert!(back.log.has_warnings());
728 assert_eq!(
729 back.result,
730 vec![
731 DC_LONG_DC.to_long(),
732 SHORT_DC_REGION_START.saturating_add(65)
733 ]
734 );
735 }
736
737 #[crate::ctb_test]
738 fn test_dclist_roundtrip() {
739 let text = b"hi @1114112@ @L42@ @2147483648@";
740 let dclist_out = dctext_to_dclist(text).expect("should succeed");
741 assert!(!dclist_out.log.has_warnings());
742
743 let restored_text = dclist_to_dctext(&dclist_out.result);
744 assert_eq!(
745 std::str::from_utf8(&restored_text).unwrap(),
746 "hi @1114112@ @L42@ @2147483648@"
747 );
748 }
749
750 }