ctb_formats_dcdata/
dcts.rs1#[allow(
32 unused_imports,
33 clippy::wildcard_imports,
34 reason = "Standard workspace module prelude"
35)]
36use crate::utilities::*;
37
38use ctb_storage_minimal::global_graph_layout::{
39 FORMAT_REGION_END, FORMAT_REGION_START, SHORT_DC_REGION_END,
40 SHORT_DC_REGION_START, UNICODE_REGION_END,
41};
42
43use crate::dc_number_minimal::read_dc_number_u128;
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47pub struct DctsOptions {
48 pub escape_control_chars: bool,
51}
52
53#[must_use]
56pub fn dclist_to_dcts_string_with_options(
57 dclist: &[u128],
58 options: DctsOptions,
59) -> String {
60 let mut output = String::new();
61 let mut i = 0usize;
62
63 while i < dclist.len() {
64 let Some(&dcid) = dclist.get(i) else { break };
65
66 if dcid == 64 {
67 output.push_str("@@");
68 } else if dcid <= UNICODE_REGION_END {
69 if let Ok(cp) = u32::try_from(dcid) {
70 if let Some(ch) = char::from_u32(cp) {
71 if options.escape_control_chars && ch.is_control() {
72 output.push_str(&format!("@u{cp:x}@"));
73 } else {
74 output.push(ch);
75 }
76 } else {
77 output.push_str(&format!("@u{cp:x}@"));
78 }
79 } else {
80 output.push_str(&format!("@u{dcid:x}@"));
81 }
82 } else if dcid == 1_114_408 {
83 if let Some(rest) = dclist.get(i.saturating_add(1)..) {
84 if let Ok((int_val, consumed)) = read_dc_number_u128(rest) {
85 output.push_str(&format!("@L{int_val}@"));
86 i = i.saturating_add(1).saturating_add(consumed);
87 continue;
88 }
89 }
90 output.push_str("@296@");
91 } else if (SHORT_DC_REGION_START..=SHORT_DC_REGION_END).contains(&dcid)
92 {
93 let short_id = dcid.saturating_sub(SHORT_DC_REGION_START);
94 output.push_str(&format!("@{short_id}@"));
95 } else if (FORMAT_REGION_START..=FORMAT_REGION_END).contains(&dcid) {
96 let fmt_id = dcid.saturating_sub(FORMAT_REGION_START);
97 output.push_str(&format!("@f{fmt_id}@"));
98 } else {
99 output.push_str(&format!("@l{dcid}@"));
100 }
101 i = i.saturating_add(1);
102 }
103 output
104}
105
106#[must_use]
109pub fn dclist_to_dcts_with_options(
110 dclist: &[u128],
111 options: DctsOptions,
112) -> Vec<u8> {
113 dclist_to_dcts_string_with_options(dclist, options).into_bytes()
114}
115
116#[must_use]
119pub fn dclist_to_dcts(dclist: &[u128]) -> Vec<u8> {
120 dclist_to_dcts_with_options(dclist, DctsOptions::default())
121}
122
123pub fn parse_dcts_strict_to_dc_chars(bytes: &[u8]) -> Result<Vec<DcChar>> {
132 let text = std::str::from_utf8(bytes)
133 .map_err(|err| anyhow::anyhow!("Invalid UTF-8 in Dcts string: {err}"))?;
134 let mut out = Vec::with_capacity(text.len());
135 let mut chars = text.chars().peekable();
136 while let Some(ch) = chars.next() {
137 if ch != '@' {
138 out.push(DcChar(u128::from(u32::from(ch))));
139 continue;
140 }
141 let mut token = String::new();
142 let mut closed = false;
143 for inner in chars.by_ref() {
144 if inner == '@' {
145 closed = true;
146 break;
147 }
148 token.push(inner);
149 }
150 anyhow::ensure!(
151 closed,
152 "Unclosed '@' shorthand escape in Dcts string"
153 );
154 if token.is_empty() {
155 out.push(DcChar(u128::from(u32::from(b'@'))));
156 continue;
157 }
158 let shorthand = crate::DcShorthand::parse(&token)?;
159 match shorthand {
160 crate::DcShorthand::Local(local_id) => {
161 out.push(crate::dc::DC_LOCAL_NODE);
162 let val = malachite::Integer::from(local_id);
163 out.extend(crate::dc_number_minimal::integer_to_dc_number_chars(
164 &val, None,
165 )?);
166 }
167 other => {
168 let gid = other.to_global_id()?;
169 out.push(DcChar(gid));
170 }
171 }
172 }
173 Ok(out)
174}
175
176#[cfg(test)]
177#[allow(
178 clippy::panic,
179 clippy::expect_used,
180 clippy::unwrap_used,
181 clippy::unwrap_in_result,
182 clippy::panic_in_result_fn,
183 clippy::indexing_slicing,
184 clippy::arithmetic_side_effects,
185 reason = "Standard repository test boilerplate"
186)]
187mod tests {
188 use super::*;
189
190 #[crate::ctb_test]
191 fn test_dclist_to_dcts_plain_and_escapes() {
192 let stream = vec![104, 101, 108, 108, 111];
194 assert_eq!(
195 dclist_to_dcts_string_with_options(&stream, DctsOptions::default()),
196 "hello"
197 );
198
199 let at_stream = vec![64];
201 assert_eq!(
202 dclist_to_dcts_string_with_options(
203 &at_stream,
204 DctsOptions::default()
205 ),
206 "@@"
207 );
208
209 let short_dc = SHORT_DC_REGION_START.saturating_add(123);
211 assert_eq!(
212 dclist_to_dcts_string_with_options(
213 &[short_dc],
214 DctsOptions::default()
215 ),
216 "@123@"
217 );
218
219 let fmt = FORMAT_REGION_START.saturating_add(80);
221 assert_eq!(
222 dclist_to_dcts_string_with_options(&[fmt], DctsOptions::default()),
223 "@f80@"
224 );
225 }
226
227 #[crate::ctb_test]
228 fn test_dclist_to_dcts_control_characters() {
229 let stream = vec![10, 0, 9]; let raw =
233 dclist_to_dcts_string_with_options(&stream, DctsOptions::default());
234 assert_eq!(raw, "\n\0\t");
235
236 let escaped = dclist_to_dcts_string_with_options(
238 &stream,
239 DctsOptions {
240 escape_control_chars: true,
241 },
242 );
243 assert_eq!(escaped, "@ua@@u0@@u9@");
244 let parsed = parse_dcts_strict_to_dc_chars(b"a@ud800@@256@")
246 .expect("parse surrogate and short Dc in strict Dcts");
247 assert_eq!(
248 parsed,
249 vec![
250 DcChar::from(b'a'),
251 DcChar::from_u128(0xD800),
252 DcChar::from_u128(SHORT_DC_REGION_START.saturating_add(256)),
253 ]
254 );
255 }
256}