ctb_formats_dcstring/
character_description.rs1#[allow(
24 unused_imports,
25 clippy::wildcard_imports,
26 reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use anyhow::{Context, Result, anyhow};
31pub use ctb_formats_unicode::character_description::{
32 ControlNameFormat, DescriptionMode, DescriptionOptions, UnicodeVersion,
33 describe as describe_unicode, describe_codepoint,
34 describe_codepoint_with_options,
35 describe_with_options as describe_unicode_with_options,
36};
37use ctb_storage_minimal::global_graph_layout::{
38 FORMAT_REGION_END, FORMAT_REGION_START, SHORT_DC_REGION_END,
39 SHORT_DC_REGION_START, dc_to_gid,
40};
41
42use crate::converters::dcal::dcal_to_dclist;
43
44#[must_use]
46pub fn describe_graph_id(id: u128, options: DescriptionOptions) -> String {
47 if id <= 0x10_FFFF {
48 if let Ok(cp) = u32::try_from(id) {
49 return describe_codepoint_with_options(cp, options);
50 }
51 }
52
53 if (SHORT_DC_REGION_START..=SHORT_DC_REGION_END).contains(&id) {
54 let diff = id.saturating_sub(SHORT_DC_REGION_START);
55 if let Ok(short_dc) = u32::try_from(diff) {
56 return describe_dc_id(id, short_dc);
57 }
58 }
59
60 if (FORMAT_REGION_START..=FORMAT_REGION_END).contains(&id) {
61 let diff = id.saturating_sub(FORMAT_REGION_START);
62 if let Ok(short_fmt) = usize::try_from(diff) {
63 return describe_format_id(id, short_fmt);
64 }
65 }
66
67 format!("{id} : <reserved> (Global Graph Block)")
68}
69
70fn describe_dc_id(gid: u128, short_dc: u32) -> String {
71 let defn = ctb_formats_dcdata::get_dc_defn(gid);
72 let (is_known, name) = match defn {
73 Some(d) => (true, d.name.clone()),
74 None => (false, format!("<unknown Dc {short_dc}>")),
75 };
76
77 let mut annotations = Vec::new();
78 let mut abbreviation = None;
79
80 if let Some(d) = defn {
81 if let Some(syntax) = &d.syntax {
82 annotations.push(format!("syntax: `{}`", syntax.raw));
83 }
84 for alias in &d.aliases {
85 let trimmed = alias.trim();
86 if trimmed.starts_with('[') && trimmed.ends_with(']') {
87 abbreviation = Some(trimmed.to_string());
88 } else {
89 annotations.push(trimmed.to_string());
90 }
91 }
92 for xref in &d.cross_references {
93 annotations.push(xref.clone());
94 }
95 for decomp in &d.decompositions {
96 annotations.push(decomp.clone());
97 }
98 }
99
100 let display_name = if is_known && !name.starts_with('<') {
101 format!("<Dc> {name}")
102 } else {
103 name
104 };
105
106 let mut out = format!("{gid} : {display_name}");
107 if let Some(abbr) = abbreviation {
108 out.push(' ');
109 out.push_str(&abbr);
110 }
111 if !annotations.is_empty() {
112 let joined = annotations.join("; ");
113 out.push_str(&format!(" {{{joined}}}"));
114 }
115
116 out
117}
118
119pub fn describe_dc(short_dc: u32) -> Result<String> {
121 let short_usize =
122 usize::try_from(short_dc).context("Dc ID exceeds usize range")?;
123 let defn = ctb_formats_dcdata::get_short_dc_defn(short_usize)
124 .ok_or_else(|| anyhow!("Unknown Dc ID: {short_dc}"))?;
125
126 let gid = dc_to_gid(u64::from(short_dc));
127
128 let mut lines = Vec::new();
129 lines.push(format!("{gid}"));
130 lines.push(defn.name.clone());
131 lines.push(String::new());
132
133 if !defn.script.is_empty() {
134 lines.push(format!("Category: {}", defn.script));
135 }
136 let bidi = defn.bidi_class.as_str();
137 if !bidi.is_empty() {
138 lines.push(format!("Bidirectional class: {bidi}"));
139 }
140 lines.push(format!("Combining class: {}", defn.combining_class));
141
142 let cat_str = defn.general_category.as_str();
143 if !cat_str.is_empty() {
144 let desc = match cat_str {
145 "!Cx" => "Control: Dc special".to_string(),
146 other => ctb_formats_utilities::describe_general_category(other),
147 };
148 let type_desc = if desc == cat_str {
149 cat_str.to_string()
150 } else {
151 format!("{cat_str} ({desc})")
152 };
153 lines.push(format!("Type: {type_desc}"));
154 }
155
156 if let Some(casing) = defn.casing_partner {
157 lines.push(format!("Casing: {casing}"));
158 }
159
160 if let Some(syntax) = &defn.syntax {
161 lines.push(format!("Syntax: {}", syntax.raw));
162 }
163 if !defn.aliases.is_empty() {
164 lines.push(format!("Aliases: {}", defn.aliases.join(", ")));
165 }
166 if !defn.cross_references.is_empty() {
167 lines.push(format!(
168 "Cross-references: {}",
169 defn.cross_references.join(", ")
170 ));
171 }
172 if !defn.decompositions.is_empty() {
173 lines
174 .push(format!("Decomposition: {}", defn.decompositions.join(", ")));
175 }
176 if !defn.description.is_empty() {
177 lines.push(format!("Description: {}", defn.description));
178 }
179
180 Ok(lines.join("\n"))
181}
182
183fn describe_format_id(gid: u128, short_fmt: usize) -> String {
184 if let Some(info) = ctb_formats_utilities::get_format_info(short_fmt) {
185 let mut out = format!("{gid} : {}", info.label);
186 if !info.category.is_empty() {
187 out.push_str(&format!(" [{}]", info.category));
188 }
189 if !info.extensions.is_empty() {
190 out.push_str(&format!(" {{{}}}", info.extensions));
191 }
192 out
193 } else {
194 format!("{gid} : Format {short_fmt}")
195 }
196}
197
198#[must_use]
200pub fn describe_dclist(dclist: &[u128], options: DescriptionOptions) -> String {
201 let mut out = String::new();
202 for &id in dclist {
203 let line = describe_graph_id(id, options);
204 out.push_str(&line);
205 out.push('\n');
206 }
207 out
208}
209
210pub fn describe_dcal(
212 input: &str,
213 options: DescriptionOptions,
214) -> Result<String> {
215 let conv = dcal_to_dclist(input.as_bytes())?;
216 conv.log.auto_log();
217 Ok(describe_dclist(&conv.result, options))
218}
219
220#[cfg(test)]
221#[allow(
222 clippy::panic,
223 clippy::expect_used,
224 clippy::unwrap_used,
225 clippy::unwrap_in_result,
226 clippy::panic_in_result_fn,
227 clippy::indexing_slicing,
228 clippy::arithmetic_side_effects,
229 reason = "Standard repository test boilerplate"
230)]
231mod tests {
232 use super::*;
233
234 #[crate::ctb_test]
235 fn test_describe_graph_id_unicode() {
236 let desc = describe_graph_id(0x41, DescriptionOptions::default());
237 assert_eq!(desc, "U+0041 : LATIN CAPITAL LETTER A");
238
239 let desc_excl = describe_graph_id(0x21, DescriptionOptions::default());
240 assert!(desc_excl.starts_with("U+0021 : EXCLAMATION MARK"));
241 assert!(desc_excl.contains("factorial") || desc_excl.contains("bang"));
242 }
243
244 #[crate::ctb_test]
245 fn test_describe_graph_id_dc() {
246 let desc_296 =
247 describe_graph_id(1114408, DescriptionOptions::default());
248 assert!(desc_296.starts_with("1114408 : <Dc> Next number is a Dc-equivalent reference to a local node/document"));
249 assert!(
250 desc_296.contains("{syntax: `:~ [number]`}")
251 || desc_296.contains("syntax: `:~ [number]`")
252 );
253
254 let desc_21 = describe_graph_id(1114133, DescriptionOptions::default());
255 assert!(desc_21.starts_with("1114133 : <Dc> Number sign"));
256 assert!(desc_21.contains("octothorpe") || desc_21.contains("hash"));
257 }
258
259 #[crate::ctb_test]
260 fn test_describe_graph_id_format() {
261 let desc_fmt =
262 describe_graph_id(2228304, DescriptionOptions::default());
263 assert!(desc_fmt.starts_with("2228304 : String"));
264 assert!(desc_fmt.contains("[semantic]"));
265 }
266
267 #[crate::ctb_test]
268 fn test_describe_dcal() {
269 let text = "65 1114408 2228304";
270 let out = describe_dcal(text, DescriptionOptions::default()).unwrap();
271 let lines: Vec<&str> = out.lines().collect();
272 assert_eq!(lines.len(), 3);
273 assert_eq!(lines[0], "U+0041 : LATIN CAPITAL LETTER A");
274 assert!(lines[1].starts_with(
275 "1114408 : <Dc> Next number is a Dc-equivalent reference"
276 ));
277 assert!(lines[2].starts_with("2228304 : String"));
278 }
279
280 #[crate::ctb_test]
281 fn test_describe_dc_296() -> Result<()> {
282 let desc = describe_dc(296)?;
283 assert_eq!(
284 desc,
285 "1114408\nNext number is a Dc-equivalent reference to a local node/document\n\nCategory: .Miscellaneous\nBidirectional class: BN\nCombining class: 0\nType: !Cx (Control: Dc special)\nSyntax: :~ [number]"
286 );
287 Ok(())
288 }
289
290 #[crate::ctb_test]
291 fn test_describe_dcmstring_with_character_token_dc203() -> Result<()> {
292 let (doc, _) = crate::converters::dcal::dcsh_to_dcmstring_with_options(
293 b"298 605 203 299",
294 false,
295 )?;
296 let mut lines = Vec::new();
297 for chunk in doc.chunks() {
298 if let Some(txt) = chunk.as_text() {
299 for ch in txt.chars() {
300 lines.push(describe_graph_id(
301 ch.0,
302 DescriptionOptions::default(),
303 ));
304 }
305 }
306 }
307 assert_eq!(lines.len(), 4);
308 assert!(
309 lines[2].starts_with("1114315 : <Dc> Begin encapsulated binary data")
310 );
311 Ok(())
312 }
313}