ctb_formats_dcstring/converters/
dcts.rs1#[allow(
32 unused_imports,
33 clippy::wildcard_imports,
34 reason = "Standard workspace module prelude"
35)]
36use crate::utilities::*;
37
38use anyhow::Result;
39use ctb_formats_dctf::decode_dctf;
40use ctb_formats_utilities::{ConversionOutput, FormatLog};
41use ctb_storage_minimal::global_graph_layout::{
42 FORMAT_REGION_END, FORMAT_REGION_START, SHORT_DC_REGION_END,
43 SHORT_DC_REGION_START, UNICODE_REGION_END,
44};
45use ctb_storage_minimal::shorthand::DcShorthand;
46
47use super::dctext::{
48 DcList, dcarray_to_dclist, dclist_to_dcarray, dclist_to_dcutf,
49 dctf_to_dclist, dcutf_to_dclist,
50};
51use crate::DcString;
52use crate::dc_char::DcChar;
53use crate::dc_number::{integer_to_dc_number_global, read_dc_number_global};
54use crate::dc_str::DcStr;
55
56pub fn dcts_to_dcstring(document: &[u8]) -> Result<ConversionOutput<DcString>> {
70 let mut log = FormatLog::default();
71 let mut dc_string = DcString::with_capacity(document.len());
72 let mut i = 0usize;
73
74 while i < document.len() {
75 let Some(slice) = document.get(i..) else {
76 break;
77 };
78 let Some(&first_byte) = slice.first() else {
79 break;
80 };
81
82 if first_byte == b'@' {
83 if let Some(rest) = slice.get(1..) {
84 if let Some(end_rel) = rest.iter().position(|&b| b == b'@') {
85 if let Some(token_bytes) = rest.get(..end_rel) {
86 if let Ok(token_str) = std::str::from_utf8(token_bytes)
87 {
88 if token_str.is_empty() {
89 dc_string.push(DcChar(64u128));
91 i = i.saturating_add(2);
92 continue;
93 }
94
95 if let Ok(shorthand) = DcShorthand::parse(token_str)
96 {
97 match shorthand {
98 DcShorthand::Local(int_val) => {
99 let malachite_val =
100 malachite::Integer::from(int_val);
101 match integer_to_dc_number_global(
102 &malachite_val,
103 ) {
104 Ok(dc_num_gids) => {
105 dc_string.push(DcChar(
106 1_114_408u128,
107 ));
108 for gid in dc_num_gids {
109 dc_string.push(DcChar(gid));
110 }
111 i = i
112 .saturating_add(2)
113 .saturating_add(end_rel);
114 continue;
115 }
116 Err(e) => {
117 log.warn(&format!(
118 "Failed to encode Dc number for local node @{token_str}@: {e}"
119 ));
120 }
121 }
122 }
123 other => {
124 if let Ok(gid) = other.to_global_id() {
125 dc_string.push(DcChar(gid));
126 i = i
127 .saturating_add(2)
128 .saturating_add(end_rel);
129 continue;
130 }
131 }
132 }
133 } else {
134 log.warn(&format!(
135 "Unrecognized token @{token_str}@ in Dcts"
136 ));
137 }
138 }
139 }
140 }
141 }
142 }
143
144 if let Some((codepoint, size)) = decode_dctf(slice) {
145 dc_string.push(DcChar(codepoint));
146 i = i.saturating_add(size);
147 } else {
148 dc_string.push(DcChar(u128::from(first_byte)));
149 i = i.saturating_add(1);
150 }
151 }
152
153 Ok(ConversionOutput::new(dc_string, log))
154}
155
156pub fn dcts_to_dclist(document: &[u8]) -> Result<ConversionOutput<DcList>> {
161 let out = dcts_to_dcstring(document)?;
162 Ok(ConversionOutput::new(out.result.to_dclist(), out.log))
163}
164
165pub use ctb_formats_dcdata::dcts::{
166 DctsOptions, dclist_to_dcts, dclist_to_dcts_string_with_options,
167 dclist_to_dcts_with_options,
168};
169
170#[must_use]
172pub fn dcstring_to_dcts(s: &DcStr) -> Vec<u8> {
173 let dclist = s.to_dclist();
174 dclist_to_dcts(&dclist)
175}
176
177pub fn dcts_to_dcmstring(
179 bytes: &[u8],
180) -> Result<(crate::DcMstring, FormatLog)> {
181 dcts_to_dcmstring_with_options(bytes, false)
182}
183
184pub fn dcts_to_dcmstring_with_options(
186 bytes: &[u8],
187 permissive: bool,
188) -> Result<(crate::DcMstring, FormatLog)> {
189 let conv = dcts_to_dcstring(bytes)?;
190 if !permissive && conv.log.has_errors() {
191 bail!(
192 "Invalid Dcts token(s): {}",
193 conv.log.get_errors().join("; ")
194 );
195 }
196 let policy = if permissive {
197 crate::DcProjectionPolicy::forgiving()
198 } else {
199 crate::DcProjectionPolicy::strict()
200 };
201 let doc =
202 crate::DcMstring::from_dc_string_with_policy(&conv.result, &policy)?;
203 Ok((doc, conv.log))
204}
205
206pub fn dcmstring_to_dcts(
208 doc: &crate::DcMstring,
209) -> Result<(Vec<u8>, FormatLog)> {
210 let dc_string = super::document_dc_string(doc)?;
211 let bytes = dcstring_to_dcts(&dc_string);
212 Ok((bytes, FormatLog::default()))
213}
214
215pub fn dcts_to_dctf(document: Vec<u8>) -> Result<Vec<u8>> {
220 let out = dcts_to_dcstring(&document)?;
221 out.log.auto_log();
222 Ok(out.result.into_bytes())
223}
224
225#[must_use]
227pub fn dctf_to_dcts(document: Vec<u8>) -> Vec<u8> {
228 let dclist = dctf_to_dclist(&document);
229 dclist_to_dcts(&dclist)
230}
231
232pub fn dcts_to_dcutf(document: Vec<u8>) -> Result<Vec<u8>> {
237 let out = dcts_to_dcstring(&document)?;
238 out.log.auto_log();
239 Ok(dclist_to_dcutf(&out.result.to_dclist()))
240}
241
242#[must_use]
244pub fn dcutf_to_dcts(document: Vec<u8>) -> Vec<u8> {
245 let dclist = dcutf_to_dclist(&document);
246 dclist_to_dcts(&dclist)
247}
248
249pub fn dcarray_to_dcts(dc_array: &[u32]) -> Result<ConversionOutput<Vec<u8>>> {
254 let conv = dcarray_to_dclist(dc_array)?;
255 let text_bytes = dclist_to_dcts(&conv.result);
256 Ok(ConversionOutput::new(text_bytes, conv.log))
257}
258
259pub fn dcts_to_dcarray(document: &[u8]) -> Result<ConversionOutput<Vec<u32>>> {
264 let conv = dcts_to_dcstring(document)?;
265 let array_conv = dclist_to_dcarray(&conv.result.to_dclist())?;
266 let mut total_log = conv.log;
267 total_log.merge(&array_conv.log);
268 Ok(ConversionOutput::new(array_conv.result, total_log))
269}
270
271#[cfg(test)]
272#[allow(
273 clippy::panic,
274 clippy::expect_used,
275 clippy::unwrap_used,
276 clippy::unwrap_in_result,
277 clippy::panic_in_result_fn,
278 clippy::indexing_slicing,
279 clippy::arithmetic_side_effects,
280 reason = "Standard repository test boilerplate"
281)]
282mod tests {
283 use super::*;
284
285 #[crate::ctb_test]
286 fn test_dcts_tokens() {
287 let input = b"a @123@ @@ @l123@ @L42@ @u123a@ @f123@";
295 let conv = dcts_to_dcstring(input).expect("parse dcts");
296 assert!(!conv.log.has_warnings());
297 let list = conv.result.to_dclist();
298
299 assert_eq!(list.first().copied(), Some(97)); assert_eq!(list.get(1).copied(), Some(32)); assert_eq!(list.get(2).copied(), Some(1_114_235)); assert_eq!(list.get(3).copied(), Some(32)); assert_eq!(list.get(4).copied(), Some(64)); assert_eq!(list.get(5).copied(), Some(32)); assert_eq!(list.get(6).copied(), Some(123)); assert_eq!(list.get(7).copied(), Some(32)); assert_eq!(list.get(8).copied(), Some(1_114_408)); assert_eq!(list.get(list.len().saturating_sub(3)).copied(), Some(4666)); assert_eq!(list.get(list.len().saturating_sub(2)).copied(), Some(32)); assert_eq!(list.last().copied(), Some(2_228_347)); }
314
315 #[crate::ctb_test]
316 fn test_dcts_serialization_roundtrip() {
317 let input = "a @123@ @@ @l100000000000@ @L42@ \u{123a} @f123@";
318 let conv = dcts_to_dcstring(input.as_bytes()).expect("parse dcts");
319 assert!(!conv.log.has_warnings());
320
321 let serialized = dcstring_to_dcts(&conv.result);
322 let s = String::from_utf8(serialized).expect("valid utf-8");
323 assert_eq!(s, input);
324 }
325
326 #[crate::ctb_test]
327 fn test_dcts_u_token_serializes_to_char_or_surrogate() {
328 let conv = dcts_to_dcstring(b"@u61@").expect("parse");
330 assert_eq!(conv.result.to_dclist(), vec![97]);
331 let out = dcstring_to_dcts(&conv.result);
332 assert_eq!(String::from_utf8(out).unwrap(), "a");
333
334 let conv_surr = dcts_to_dcstring(b"@ud800@").expect("parse surrogate");
336 assert_eq!(conv_surr.result.to_dclist(), vec![0xd800]);
337 let out_surr = dcstring_to_dcts(&conv_surr.result);
338 assert_eq!(String::from_utf8(out_surr).unwrap(), "@ud800@");
339 }
340
341 #[crate::ctb_test]
342 fn test_dcts_dcarray_conversions() {
343 let original_dcarray = vec![0, 1, 18, 50, 200, 297];
344 let conv = dcarray_to_dcts(&original_dcarray).expect("to dcts");
345 assert!(!conv.log.has_warnings());
346 assert_eq!(
347 String::from_utf8(conv.result.clone()).unwrap(),
348 "@0@@1@@18@@50@@200@@297@"
349 );
350
351 let back = dcts_to_dcarray(&conv.result).expect("back to dcarray");
352 assert!(!back.log.has_warnings());
353 assert_eq!(back.result, original_dcarray);
354 }
355
356 #[crate::ctb_test]
357 fn test_dcts_dcstring_and_dcutf_roundtrip() {
358 let input = "hello @123@ @f461@ @L7@ world";
359 let out = dcts_to_dcstring(input.as_bytes()).expect("dcstring");
360 assert!(!out.log.has_warnings());
361
362 let roundtrip_bytes = dcstring_to_dcts(&out.result);
363 assert_eq!(String::from_utf8(roundtrip_bytes).unwrap(), input);
364
365 let dcutf = dcts_to_dcutf(input.as_bytes().to_vec()).unwrap();
366 let roundtrip_from_dcutf = dcutf_to_dcts(dcutf);
367 assert_eq!(String::from_utf8(roundtrip_from_dcutf).unwrap(), input);
368 }
369
370 #[crate::ctb_test]
371 fn test_dcts_warnings_on_invalid_tokens() {
372 let conv = dcts_to_dcstring(b"@uzzz@").expect("parse");
374 assert!(conv.log.has_warnings());
375
376 let conv2 = dcts_to_dcstring(b"@u110000@").expect("parse");
378 assert!(conv2.log.has_warnings());
379
380 let conv3 = dcts_to_dcstring(b"@fxyz@").expect("parse");
382 assert!(conv3.log.has_warnings());
383
384 let conv4 = dcts_to_dcstring(b"@lxyz@").expect("parse");
386 assert!(conv4.log.has_warnings());
387
388 let conv5 = dcts_to_dcstring(b"@U123@").expect("parse");
390 assert!(conv5.log.has_warnings());
391
392 let conv6 = dcts_to_dcstring(b"@F123@").expect("parse");
393 assert!(conv6.log.has_warnings());
394 }
395}