1use crate::utilities::*;
35
36use anyhow::{Context, Result, bail, ensure};
37use ctb_formats_utilities::FormatLog;
38
39use crate::dc::data::{
40 dc_data_filter_by_value, dc_data_filter_by_value_greater,
41 dc_data_get_column, dc_data_lookup_by_dc_in_col_0, dc_data_lookup_by_id,
42 dc_data_lookup_by_value,
43};
44use crate::dc::{DC_REPLACEMENT_UNAVAIL_DC, is_known_dc};
45use crate::eite_state::EiteState;
46use crate::encoding::base::{dec_to_hex_single, hex_to_dec_single};
47use crate::encoding::is_supported_char_encoding;
48use crate::encoding::utf8::unicode_scalar_from_utf8;
49use crate::exceptions::{exc_or_empty, excep};
50use crate::formats::ascii::{
51 AsciiSafeSubsetFormatSettings, dca_from_ascii, dca_from_ascii_safe_subset,
52 dca_to_ascii, dca_to_ascii_safe_subset,
53};
54use crate::formats::html::{
55 dc_to_colorcoded, dca_to_colorcoded, dca_to_html, dca_to_html_fragment,
56};
57use crate::formats::integer_list::{
58 dca_from_integer_list, dca_to_integer_list,
59};
60use crate::formats::sems::{SEMSFormatSettings, dca_from_sems};
61use crate::formats::utf8::{UTF8FormatSettings, dca_from_utf8, dca_to_utf8};
62use crate::transform::{DocumentTransformation, apply_prefilters};
63use crate::{debug, json};
64use ctb_formats_utf8::utf8_from_scalar;
65
66pub mod ascii;
67pub mod dcbasenb;
68pub mod elad;
69pub mod html;
70pub mod integer_list;
71pub mod sems;
72pub mod utf8;
73
74#[derive(Debug, Clone)]
75pub enum Format {
76 SEMS {
77 settings: SEMSFormatSettings,
78 },
79 UTF8 {
80 settings: UTF8FormatSettings,
81 },
82 IntegerList,
83 ASCII,
84 ASCIISafeSubset {
85 settings: AsciiSafeSubsetFormatSettings,
86 },
87 HTML,
88 HTMLFragment,
89 ColorCoded,
90}
91
92impl Format {
93 pub fn utf8_default() -> Self {
94 Format::UTF8 {
95 settings: UTF8FormatSettings::default(),
96 }
97 }
98 pub fn sems_default() -> Self {
99 Format::SEMS {
100 settings: SEMSFormatSettings::default(),
101 }
102 }
103 pub fn ascii_safe_subset_default() -> Self {
104 Format::ASCIISafeSubset {
105 settings: AsciiSafeSubsetFormatSettings::default(),
106 }
107 }
108
109 pub fn from_string(format: &str) -> Result<Self> {
110 match format {
111 "sems" => Ok(Format::sems_default()),
112 "utf8" => Ok(Format::utf8_default()),
113 "integerList" => Ok(Format::IntegerList),
114 "ascii" => Ok(Format::ASCII),
115 "asciiSafeSubset" => Ok(Format::ascii_safe_subset_default()),
116 "html" => Ok(Format::HTML),
117 "htmlFragment" => Ok(Format::HTMLFragment),
118 "colorcoded" => Ok(Format::ColorCoded),
119 _ => Err(anyhow::anyhow!("Unknown EITE format: {format}")),
120 }
121 }
122}
123
124impl std::fmt::Display for Format {
125 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126 write!(
127 f,
128 "{}",
129 match self {
130 Format::SEMS { settings: _ } => "sems",
131 Format::UTF8 { settings: _ } => "utf8",
132 Format::IntegerList => "integerList",
133 Format::ASCII => "ascii",
134 Format::ASCIISafeSubset { settings: _ } => "asciiSafeSubset",
135 Format::HTML => "html",
136 Format::HTMLFragment => "htmlFragment",
137 Format::ColorCoded => "colorcoded",
138 }
139 )
140 }
141}
142
143pub fn with_default_log<T, E>(r: Result<T, E>) -> Result<(T, FormatLog), E> {
146 r.map(|val| (val, FormatLog::default()))
147}
148
149fn apply_format_import_settings(
152 state: &EiteState,
153 in_format: &mut Format,
154) -> Result<()> {
155 if let Format::UTF8 { settings } = in_format {
156 let variants = crate::settings::get_enabled_variants_for_format(
157 state, "utf8", "in",
158 )?;
159 settings.dc_basenb_enabled = variants.iter().any(|v| v == "dcBasenb");
160 settings.dc_basenb_fragment_enabled =
161 variants.iter().any(|v| v == "dcBasenbFragment");
162 }
163 Ok(())
164}
165
166fn apply_format_export_settings(
167 state: &EiteState,
168 out_format: &mut Format,
169) -> Result<()> {
170 if let Format::UTF8 { settings } = out_format {
171 let variants = crate::settings::get_enabled_variants_for_format(
172 state, "utf8", "out",
173 )?;
174 settings.dc_basenb_enabled = variants.iter().any(|v| v == "dcBasenb");
175 settings.dc_basenb_fragment_enabled =
176 variants.iter().any(|v| v == "dcBasenbFragment");
177 }
178 Ok(())
179}
180
181pub fn dca_from_format(
184 state: &mut EiteState,
185 in_format: &Format,
186 content_bytes: &[u8],
187) -> Result<(Vec<u32>, FormatLog)> {
188 let format_string = in_format.to_string();
189 ensure!(
190 is_supported_input_format(format_string.as_str()),
191 "Unsupported input format {format_string}"
192 );
193 let mut in_fmt = in_format.clone();
194 apply_format_import_settings(state, &mut in_fmt)?;
195 match &in_fmt {
196 Format::SEMS { settings } => dca_from_sems(content_bytes, settings),
197 Format::IntegerList => {
198 dca_from_integer_list(content_bytes, &Default::default())
199 }
200 Format::ASCII => dca_from_ascii(content_bytes),
201 Format::ASCIISafeSubset { settings } => {
202 dca_from_ascii_safe_subset(content_bytes, settings)
203 }
204 Format::UTF8 { settings } => dca_from_utf8(content_bytes, settings),
205 _other => {
206 bail!("Unimplemented document parsing format: {format_string}")
207 }
208 }
209}
210
211pub fn dca_to_format(
214 state: &mut EiteState,
215 out_format: &Format,
216 dc_array: &[u32],
217 prefilter_settings: &PrefilterSettings,
218) -> Result<(Vec<u8>, FormatLog)> {
219 let format_string = out_format.to_string();
220 ensure!(
221 is_supported_output_format(format_string.as_str()),
222 "Unsupported output format {format_string}"
223 );
224 let mut out_fmt = out_format.clone();
225 apply_format_export_settings(state, &mut out_fmt)?;
226 let dc_array = &apply_prefilters(dc_array, prefilter_settings)?;
227 match &out_fmt {
228 Format::IntegerList => {
229 with_default_log(Ok(dca_to_integer_list(dc_array)))
230 }
231 Format::ASCII => dca_to_ascii(dc_array),
232 Format::ASCIISafeSubset { settings: _ } => {
233 dca_to_ascii_safe_subset(dc_array)
234 }
235 Format::ColorCoded => with_default_log(dca_to_colorcoded(dc_array)),
236 Format::UTF8 { settings } => dca_to_utf8(dc_array, settings),
237 Format::HTML => dca_to_html(dc_array),
238 Format::HTMLFragment => dca_to_html_fragment(dc_array),
239 _other => bail!(
240 "Unimplemented document render output format: {format_string}"
241 ),
242 }
243}
244
245pub fn convert_formats(
248 state: &mut EiteState,
249 in_format: &Format,
250 out_format: &Format,
251 input: &[u8],
252 prefilter_settings: &PrefilterSettings,
253) -> Result<(Vec<u8>, FormatLog)> {
254 let (dc_array, mut log) = dca_from_format(state, in_format, input)?;
255
256 let (out, out_log) =
257 dca_to_format(state, out_format, &dc_array, prefilter_settings)?;
258 log.merge(&out_log);
259
260 Ok((out, log))
261}
262
263pub fn get_export_extension(format: &str) -> Result<String> {
266 if is_supported_char_encoding(format) {
267 return Ok(format!("{}.txt", get_format_extension(format)?));
268 }
269 get_format_extension(format)
270}
271
272pub fn dc_to_format(out_format: &str, dc: u32) -> Result<(Vec<u8>, FormatLog)> {
277 ensure!(
278 is_supported_output_format(out_format),
279 "Unsupported output format {out_format}"
280 );
281 ensure!(is_known_dc(dc)?, "Unknown Dc {dc}");
282 let mut log = FormatLog::default();
283
284 match out_format {
285 "utf8" => {
286 let hex_str = dc_data_lookup_by_value(
288 "mappings/to/unicode",
289 0,
290 dc.to_string().as_str(),
291 1,
292 );
293 if !exc_or_empty(&hex_str)? {
294 let hex_str = hex_str
295 .context(format!("Failed lookup Dc {dc} unicode"))?;
296 let cp = hex_to_dec_single(&hex_str)?;
297 return Ok((utf8_from_scalar(cp)?, log));
298 }
299
300 let row_str = dc_data_lookup_by_value(
302 "mappings/from/unicode",
303 1,
304 &dc.to_string(),
305 0,
306 );
307 if !exc_or_empty(&row_str)? {
308 let row_str = row_str.context(format!(
309 "Failed lookup Dc {dc} unicode fallback"
310 ))?;
311 let cp = hex_to_dec_single(&row_str)?;
312 return Ok((utf8_from_scalar(cp)?, log));
313 }
314
315 log.warn(format!("Could not convert Dc {dc} to UTF-8").as_str());
316
317 Ok((Vec::new(), log))
318 }
319 "colorcoded" => Ok((dc_to_colorcoded(dc)?, log)),
320 "html" => {
321 let html_map =
322 dc_data_lookup_by_dc_in_col_0("mappings/to/html", dc, 1);
323 if !exc_or_empty(&html_map)? {
324 let html_map = html_map.context(format!(
325 "Failed lookup HTML mapping for Dc {dc}"
326 ))?;
327 return Ok((html_map.as_bytes().to_vec(), log));
328 }
329 dc_to_format("utf8", dc)
330 }
331 other => bail!("Unimplemented character output format: {other}"),
332 }
333}
334
335pub fn dc_from_format(
337 in_format: &str,
338 content: &[u8],
339) -> Result<(Vec<u32>, FormatLog)> {
340 ensure!(
341 is_supported_internal_format(in_format),
342 "Unsupported internal/source format {in_format}"
343 );
344 let mut res: Vec<u32> = Vec::new();
345 let mut log = FormatLog::default();
346 match in_format {
347 "ascii" | "unicode" => {
348 if content.is_empty() {
349 return Ok((res, log));
350 }
351 let c = unicode_scalar_from_utf8(content)?;
352 if in_format == "ascii" && c > 0x7F {
353 bail!("Not a 7-bit ASCII char: {c}");
354 }
355 let hex = dec_to_hex_single(c)?;
356 let dc_str =
358 dc_data_lookup_by_value("mappings/from/unicode", 0, &hex, 1);
359 if excep(&dc_str)? || (dc_str.as_ref().is_ok_and(String::is_empty))
360 {
361 log.warn(&format!("Unmapped Unicode character U+{hex}"));
364 res.push(DC_REPLACEMENT_UNAVAIL_DC.to_short()?);
365 return Ok((res, log));
366 }
367 match dc_str {
368 Err(err) => {
369 return Err(err).context(format!(
370 "Unexpected error looking up Unicode char U+{hex}"
371 ));
372 }
373 Ok(dc_s) => {
374 if let Ok(dc_id) = dc_s.parse::<u32>() {
375 res.push(dc_id);
376 }
377 }
378 }
379 }
380 other => bail!("Unimplemented character source format: {other}"),
381 }
382 Ok((res, log))
383}
384
385pub fn import_warning(state: &mut EiteState, index: usize, problem: &str) {
387 let warn = format!(
388 "A problem was encountered while importing at character {index}: {problem}"
389 );
390 state.import_deferred_settings_stack.push(warn.clone());
391 debug!("{}, {}, {}", json!(state), 1, &warn);
392}
393
394pub fn export_warning(state: &mut EiteState, index: usize, problem: &str) {
396 let warn = format!(
397 "A problem was encountered while exporting at character {index}: {problem}"
398 );
399 state.export_deferred_settings_stack.push(warn.clone());
400 debug!("{}, {}, {}", json!(state), 1, &warn);
401}
402
403pub fn get_import_warnings(state: &mut EiteState) -> Vec<String> {
406 let res = state.import_deferred_settings_stack.clone();
407 state.import_deferred_settings_stack.clear();
408 res
409}
410
411pub fn get_export_warnings(state: &mut EiteState) -> Vec<String> {
414 let res = state.export_deferred_settings_stack.clone();
415 state.export_deferred_settings_stack.clear();
416 res
417}
418
419pub fn export_warning_unmappable(state: &mut EiteState, index: usize, dc: u32) {
421 export_warning(
422 state,
423 index,
424 &format!(
425 "The character {dc} could not be represented in the chosen export format."
426 ),
427 );
428}
429
430pub fn list_formats() -> Result<Vec<String>> {
435 dc_data_get_column("formats", 1) }
437
438pub fn is_format(format: &str) -> bool {
441 let Ok(formats) = list_formats() else {
442 return false;
443 };
444 formats.iter().any(|f| f == format)
445}
446
447pub fn list_input_formats() -> Result<Vec<String>> {
450 dc_data_filter_by_value_greater("formats", 3, 0, 1)
451}
452
453pub fn is_supported_input_format(fmt: &str) -> bool {
456 let Ok(input_formats) = list_input_formats() else {
457 return false;
458 };
459 input_formats.iter().any(|f| f == fmt)
460}
461
462pub fn list_internal_formats() -> Result<Vec<String>> {
465 dc_data_filter_by_value("formats", 6, "internal", 1)
466}
467
468pub fn is_supported_internal_format(fmt: &str) -> bool {
471 let Ok(inf) = list_input_formats() else {
472 return false;
473 };
474 let Ok(intern) = list_internal_formats() else {
475 return false;
476 };
477 inf.iter().any(|f| f == fmt) || intern.iter().any(|f| f == fmt)
478}
479
480pub fn list_output_formats() -> Result<Vec<String>> {
483 dc_data_filter_by_value_greater("formats", 4, 0, 1)
484}
485
486pub fn is_supported_output_format(fmt: &str) -> bool {
489 let Ok(output_formats) = list_output_formats() else {
490 return false;
491 };
492 output_formats.iter().any(|f| f == fmt)
493}
494
495pub fn list_data_types() -> Result<Vec<String>> {
497 dc_data_filter_by_value("formats", 6, "data", 1)
498}
499
500#[expect(
502 clippy::expect_used,
503 reason = "ftype starts_with v: guarantees length >= 2"
504)]
505pub fn list_variants_for_format(format: &str) -> Result<Vec<String>> {
506 let normalized = normalize_format(format)?;
507 let all = list_formats()?;
508 let mut res = Vec::new();
509 for f in all {
510 let ftype = get_format_type(&f)?;
511 if ftype.starts_with("v:") {
512 let mut variant_type =
513 ftype.get(2..).expect("ftype starts with v:").to_string();
514 if variant_type == "unicodePua" {
516 variant_type = "unicode".to_string();
517 }
518 if variant_type == normalized {
519 res.push(f);
520 }
521 }
522 }
523 Ok(res)
524}
525
526pub fn get_format_id(format: &str) -> Result<usize> {
528 ensure!(is_format(format), "Unknown format {format}");
529 let id_str = dc_data_lookup_by_value("formats", 1, format, 0)?;
530 let id = id_str
531 .parse::<usize>()
532 .with_context(|| format!("Invalid format id value: {id_str}"))?;
533 Ok(id)
534}
535
536pub fn normalize_format(format: &str) -> Result<String> {
539 ensure!(is_format(format), "Unknown format {format}");
540 if format == "utf8" {
541 return Ok("unicode".to_string());
542 }
543 Ok(format.to_string())
544}
545
546pub fn get_format_name(format: &str) -> Result<String> {
549 let id = get_format_id(format)?;
550 dc_data_lookup_by_id("formats", id, 1)
551}
552
553pub fn get_format_extension(format: &str) -> Result<String> {
556 let id = get_format_id(format)?;
557 dc_data_lookup_by_id("formats", id, 2)
558}
559
560fn parse_support_component(raw: &str, index: usize) -> Result<i32> {
561 let trimmed = raw.trim();
562 if trimmed.is_empty() {
563 return Ok(0);
564 }
565 let parts: Vec<&str> = trimmed.split_whitespace().collect();
566 if let Some(part) = parts.get(index) {
567 part.parse::<i32>().with_context(|| {
568 format!("Invalid integer in support specification '{raw}'")
569 })
570 } else {
571 bail!("Expected support component at index {index} in '{raw}'");
572 }
573}
574
575pub fn get_format_import_support(format: &str) -> Result<i32> {
578 let id = get_format_id(format)?;
579 let v = dc_data_lookup_by_id("formats", id, 3)?;
580 parse_support_component(&v, 0).with_context(|| {
581 format!("Failed to parse general import support integer for format '{format}' from '{v}'")
582 })
583}
584
585pub fn get_format_dc_import_support(format: &str) -> Result<i32> {
588 let id = get_format_id(format)?;
589 let v = dc_data_lookup_by_id("formats", id, 3)?;
590 parse_support_component(&v, 1).with_context(|| {
591 format!("Failed to parse Dc import support integer for format '{format}' from '{v}'")
592 })
593}
594
595pub fn get_format_export_support(format: &str) -> Result<i32> {
598 let id = get_format_id(format)?;
599 let v = dc_data_lookup_by_id("formats", id, 4)?;
600 parse_support_component(&v, 0).with_context(|| {
601 format!("Failed to parse general export support integer for format '{format}' from '{v}'")
602 })
603}
604
605pub fn get_format_dc_export_support(format: &str) -> Result<i32> {
608 let id = get_format_id(format)?;
609 let v = dc_data_lookup_by_id("formats", id, 4)?;
610 parse_support_component(&v, 1).with_context(|| {
611 format!("Failed to parse Dc export support integer for format '{format}' from '{v}'")
612 })
613}
614
615pub fn get_format_tests_status(format: &str) -> Result<i32> {
618 let id = get_format_id(format)?;
619 let v = dc_data_lookup_by_id("formats", id, 5)?;
620 parse_support_component(&v, 0).with_context(|| {
621 format!("Failed to parse test status integer for format '{format}' from '{v}'")
622 })
623}
624
625pub fn get_format_type(format: &str) -> Result<String> {
628 let id = get_format_id(format)?;
629 dc_data_lookup_by_id("formats", id, 6)
630}
631
632pub fn get_format_label(format: &str) -> Result<String> {
635 let id = get_format_id(format)?;
636 dc_data_lookup_by_id("formats", id, 7)
637}
638
639pub fn get_format_variant_types(format: &str) -> Result<Vec<String>> {
644 let id = get_format_id(format)?;
645 let raw = dc_data_lookup_by_id("formats", id, 8)?;
646 Ok(raw
647 .split(',')
648 .filter(|s| !s.is_empty())
649 .map(std::string::ToString::to_string)
650 .collect())
651}
652
653pub fn get_format_comments(format: &str) -> Result<String> {
656 let id = get_format_id(format)?;
657 dc_data_lookup_by_id("formats", id, 9)
658}
659
660pub fn format_is_variant(format: &str) -> Result<bool> {
666 ensure!(is_format(format), "Unknown format {format}");
667 let t = get_format_type(format)?;
668 Ok(t.starts_with("v:"))
669}
670
671pub fn format_is_any_language(format: &str) -> Result<bool> {
673 ensure!(is_format(format), "Unknown format {format}");
674 let t = get_format_type(format)?;
675 Ok(t.eq("language") || t.eq("programming"))
676}
677
678pub fn format_is_human_language(format: &str) -> Result<bool> {
680 ensure!(is_format(format), "Unknown format {format}");
681 let t = get_format_type(format)?;
682 Ok(t.eq("language"))
683}
684
685pub fn format_is_programming_language(format: &str) -> Result<bool> {
687 ensure!(is_format(format), "Unknown format {format}");
688 let t = get_format_type(format)?;
689 Ok(t.eq("programming"))
690}
691
692pub fn is_variant_type(variant_type: &str) -> bool {
696 matches!(variant_type, "encoding" | "unicodePua")
697}
698
699#[expect(
703 clippy::expect_used,
704 reason = "format_is_variant ensures string starts with v: prefix, so length >= 2"
705)]
706pub fn format_get_variant_type(variant: &str) -> Result<String> {
707 ensure!(
708 format_is_variant(variant)?,
709 "Format {variant} is not a variant"
710 );
711 let t = get_format_type(variant)?;
712 Ok(t.get(2..).expect("t starts with v:").to_string())
714}
715
716pub fn format_supports_variant_type(
721 format: &str,
722 variant_type: &str,
723) -> Result<bool> {
724 Ok(get_format_variant_types(format)?
725 .iter()
726 .any(|t| t == variant_type))
727}
728
729pub fn format_supports_variant(format: &str, variant: &str) -> Result<bool> {
733 let vt = format_get_variant_type(variant)?;
734 format_supports_variant_type(format, &vt)
735}
736
737pub fn get_format_metrics_type(format: &str) -> Result<String> {
740 ensure!(is_format(format), "Unknown format {format}");
741 let t = get_format_type(format)?;
742 let res = if t == "text" || matches!(t.as_str(), "encoding" | "terminal") {
743 "character".to_string()
744 } else if t == "internal" {
745 format!("internal-{format}")
746 } else {
747 format!("complex-{format}")
748 };
749 Ok(res)
750}
751
752pub struct DcOutputLanguage {
753 language: String,
754}
755
756impl DcOutputLanguage {
757 pub fn new(language: &str) -> Result<Self> {
758 ensure!(
759 format_is_any_language(language)?,
760 format!("Unknown language {language}")
761 );
762 ensure!(
763 is_supported_output_format(language),
764 format!("Output support for language {language}")
765 );
766 Ok(DcOutputLanguage {
767 language: language.to_string(),
768 })
769 }
770}
771
772impl std::fmt::Display for DcOutputLanguage {
773 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
774 write!(f, "{}", self.language)
775 }
776}
777
778impl Default for DcOutputLanguage {
779 fn default() -> Self {
780 DcOutputLanguage {
781 language: "lang_en".to_string(),
782 }
783 }
784}
785
786#[derive(Default)]
787pub struct PrefilterSettings {
789 pub enabled_prefilters: Vec<DocumentTransformation>,
790}
791
792impl PrefilterSettings {
793 pub fn apply(&self, dc_array_in: &[u32]) -> Result<Vec<u32>> {
794 let mut out = dc_array_in.to_vec();
795
796 for prefilter in &self.enabled_prefilters {
797 out = prefilter.apply(&out)?;
798 }
799
800 Ok(out)
801 }
802}
803
804#[cfg(test)]
805#[allow(
806 clippy::panic,
807 clippy::expect_used,
808 clippy::unwrap_used,
809 clippy::unwrap_in_result,
810 clippy::panic_in_result_fn,
811 clippy::indexing_slicing,
812 clippy::arithmetic_side_effects,
813 reason = "Standard repository test boilerplate"
814)]
815mod tests {
816 use ctb_formats_utilities::assert_vec_u8_ok_eq_no_warnings;
817
818 use super::*;
819
820 #[crate::ctb_test]
821 fn test_import_export_warning_buffers() {
822 let mut state = EiteState::new();
823 import_warning(&mut state, 2, "Example problem");
824 export_warning(&mut state, 5, "Another issue");
825 let iw = get_import_warnings(&mut state);
826 let ew = get_export_warnings(&mut state);
827 assert_eq!(iw.len(), 1);
828 assert_eq!(ew.len(), 1);
829 assert!(get_import_warnings(&mut state).is_empty());
830 assert!(get_export_warnings(&mut state).is_empty());
831 }
832
833 #[crate::ctb_test]
834 fn test_dca_from_format_ascii() {
835 let mut state = EiteState::new();
836 let input = b"ABC";
837 let (res, _log) =
838 dca_from_format(&mut state, &Format::ASCII, input).unwrap();
839 assert_eq!(res, vec![50, 51, 52]);
840 }
841 #[crate::ctb_test]
842 fn test_dca_to_format_ascii() {
843 let mut state = EiteState::new();
844 let input = vec![50, 51, 52];
845 assert_vec_u8_ok_eq_no_warnings(
846 b"ABC",
847 dca_to_format(
848 &mut state,
849 &Format::ASCII,
850 &input,
851 &PrefilterSettings::default(),
852 ),
853 );
854 }
855 #[crate::ctb_test]
856 fn test_convert_formats_ascii_to_utf8() {
857 let mut state = EiteState::new();
858 let input = b"ABC";
859 assert_vec_u8_ok_eq_no_warnings(
860 b"ABC",
861 convert_formats(
862 &mut state,
863 &Format::ASCII,
864 &Format::utf8_default(),
865 input,
866 &PrefilterSettings::default(),
867 ),
868 );
869 }
870 #[crate::ctb_test]
871 fn test_get_export_extension_ascii() {
872 let ext = get_export_extension("ascii").unwrap();
873 assert!(ext.ends_with(".txt"));
874 }
875 #[crate::ctb_test]
876 fn test_dc_to_format_utf8() {
877 let (out, log) = dc_to_format("utf8", 65).unwrap();
878 assert_eq!(out, b"P");
879 assert!(log.has_no_warnings_or_errors());
880 }
881 #[crate::ctb_test]
882 fn test_dc_from_format_ascii() {
883 let (res, _log) = dc_from_format("ascii", b"A").unwrap();
884 assert_eq!(1, res.len());
885 }
886 #[crate::ctb_test]
887 fn test_import_warning_add() {
888 let mut state = EiteState::new();
889 import_warning(&mut state, 0, "test");
890 assert_eq!(state.import_deferred_settings_stack.len(), 1);
891 }
892 #[crate::ctb_test]
893 fn test_export_warning_add() {
894 let mut state = EiteState::new();
895 export_warning(&mut state, 0, "test");
896 assert_eq!(state.export_deferred_settings_stack.len(), 1);
897 }
898 #[crate::ctb_test]
899 fn test_get_import_warnings_clear() {
900 let mut state = EiteState::new();
901 import_warning(&mut state, 0, "test");
902 let _ = get_import_warnings(&mut state);
903 assert!(state.import_deferred_settings_stack.is_empty());
904 }
905 #[crate::ctb_test]
906 fn test_get_export_warnings_clear() {
907 let mut state = EiteState::new();
908 export_warning(&mut state, 0, "test");
909 let _ = get_export_warnings(&mut state);
910 assert!(state.export_deferred_settings_stack.is_empty());
911 }
912 #[crate::ctb_test]
913 fn test_export_warning_unmappable() {
914 let mut state = EiteState::new();
915 export_warning_unmappable(&mut state, 0, 999);
916 assert_eq!(state.export_deferred_settings_stack.len(), 1);
917 }
918 #[crate::ctb_test]
919 fn test_list_formats() -> Result<()> {
920 let formats = list_formats()?;
921 assert!(formats.contains(&"utf8".to_string()));
922 assert!(formats.contains(&"ascii".to_string()));
923 assert!(formats.contains(&"vt100".to_string()));
924 Ok(())
925 }
926 #[crate::ctb_test]
927 fn test_is_format_true_false() {
928 assert!(is_format("utf8"));
929 assert!(!is_format("not_a_format"));
930 }
931 #[crate::ctb_test]
932 fn test_list_input_formats() -> Result<()> {
933 let formats = list_input_formats()?;
934 assert!(formats.contains(&"semanticToText".to_string()));
935 Ok(())
936 }
937 #[crate::ctb_test]
938 fn test_is_supported_input_format_true_false() {
939 assert!(is_supported_input_format("utf8"));
940 assert!(!is_supported_input_format("not_a_format"));
941 }
942 #[crate::ctb_test]
943 fn test_list_internal_formats() -> Result<()> {
944 let formats = list_internal_formats()?;
945 assert!(formats.contains(&"dc".to_string()));
946 assert!(!formats.contains(&"utf8".to_string()));
947 Ok(())
948 }
949 #[crate::ctb_test]
950 fn test_is_supported_internal_format_true_false() {
951 assert!(is_supported_internal_format("unicode"));
952 assert!(!is_supported_internal_format("not_a_format"));
953 }
954 #[crate::ctb_test]
955 fn test_list_output_formats() -> Result<()> {
956 let formats = list_output_formats()?;
957 assert!(formats.contains(&"asciiSafeSubset".to_string()));
958 Ok(())
959 }
960 #[crate::ctb_test]
961 fn test_is_supported_output_format() {
962 assert!(is_supported_output_format("utf8"));
963 assert!(is_supported_output_format("asciiSafeSubset"));
964 assert!(!is_supported_output_format("sems")); assert!(!is_supported_output_format("not_a_format")); }
967 #[crate::ctb_test]
968 fn test_list_data_types() -> Result<()> {
969 let types = list_data_types()?;
970 assert!(types.contains(&"basenb".to_string()));
971 Ok(())
972 }
973 #[crate::ctb_test]
974 fn test_list_variants_for_format() {
975 let res = list_variants_for_format("utf8");
976 assert!(res.unwrap().contains(&"dcBasenb".to_string()));
977 }
978 #[crate::ctb_test]
979 fn test_get_format_id() {
980 let id = get_format_id("utf8").unwrap();
981 assert_eq!(id, 0);
982 let id = get_format_id("sems").unwrap();
983 assert_eq!(id, 6);
984 }
985 #[crate::ctb_test]
986 fn test_normalize_format() {
987 let norm = normalize_format("utf8").unwrap();
988 assert_eq!(norm, "unicode");
989 let norm = normalize_format("sems").unwrap();
990 assert_eq!(norm, "sems");
991 assert!(normalize_format("not_a_format").is_err());
992 }
993 #[crate::ctb_test]
994 fn test_get_format_name_utf8() {
995 let name = get_format_name("utf8").unwrap();
996 assert_eq!(name, "utf8");
997 }
998 #[crate::ctb_test]
999 fn test_get_format_extension_utf8() {
1000 let ext = get_format_extension("utf8").unwrap();
1001 assert_eq!(ext, "utf8");
1002 }
1003 #[crate::ctb_test]
1004 fn test_get_format_import_support_utf8() {
1005 let val = get_format_import_support("utf8").unwrap();
1006 assert_eq!(val, 3);
1007 let dc_val = get_format_dc_import_support("utf8").unwrap();
1008 assert_eq!(dc_val, 1);
1009 }
1010 #[crate::ctb_test]
1011 fn test_get_format_export_support_utf8() {
1012 let val = get_format_export_support("utf8").unwrap();
1013 assert_eq!(val, 3);
1014 let dc_val = get_format_dc_export_support("utf8").unwrap();
1015 assert_eq!(dc_val, 2);
1016 }
1017 #[crate::ctb_test]
1018 fn test_get_format_tests_status_utf8() {
1019 let val = get_format_tests_status("utf8").unwrap();
1020 assert_eq!(val, 1);
1021 }
1022 #[crate::ctb_test]
1023 fn test_get_format_type_utf8() {
1024 let typ = get_format_type("utf8").unwrap();
1025 assert_eq!(typ, "encoding");
1026 }
1027 #[crate::ctb_test]
1028 fn test_get_format_label_utf8() {
1029 let label = get_format_label("utf8").unwrap();
1030 assert_eq!(label, "UTF-8");
1031 }
1032
1033 #[crate::ctb_test]
1034 fn test_get_format_variant_types_utf8() {
1035 let types = get_format_variant_types("utf8").unwrap();
1036 assert_eq!(types, vec!["unicodePua"]);
1037 }
1038
1039 #[crate::ctb_test]
1040 fn test_get_format_variant_types_empty() {
1041 let types = get_format_variant_types("unknown_format");
1042 assert!(types.is_err()); }
1044
1045 #[crate::ctb_test]
1046 fn test_format_is_variant() {
1047 assert!(format_is_variant("dcBasenb").unwrap());
1048 assert!(!format_is_variant("utf8").unwrap());
1049 }
1050
1051 #[crate::ctb_test]
1052 fn test_is_variant_type_known_and_unknown() {
1053 assert!(is_variant_type("encoding"));
1054 assert!(is_variant_type("unicodePua"));
1055 assert!(!is_variant_type("v:unicodePua")); assert!(!is_variant_type("foobar"));
1057 }
1058
1059 #[crate::ctb_test]
1060 fn test_format_get_variant_type_success_and_failure() {
1061 assert_eq!(format_get_variant_type("dcBasenb").unwrap(), "unicodePua");
1063 assert!(format_get_variant_type("utf8").is_err());
1065 assert!(format_get_variant_type("unicodePua").is_err());
1066 assert!(format_get_variant_type("v:unicodePua").is_err());
1067 }
1068
1069 #[crate::ctb_test]
1070 fn test_format_supports_variant_type_true_and_false() {
1071 assert!(format_supports_variant_type("utf8", "unicodePua").unwrap());
1072 assert!(!format_supports_variant_type("utf8", "v:unicodePua").unwrap()); assert!(!format_supports_variant_type("utf8", "encoding").unwrap());
1074 }
1075
1076 #[crate::ctb_test]
1077 fn test_format_supports_variant_utf8() {
1078 let res = format_supports_variant("utf8", "utf8");
1079 assert!(res.is_err(), "utf8 is not a variant of utf8");
1080 let res = format_supports_variant("html", "utf8");
1081 assert!(res.is_err(), "utf8 is a variant of html");
1082 let res = format_supports_variant("utf8", "v:dcBasenb");
1083 assert!(res.is_err()); let res = format_supports_variant("utf8", "dcBasenb");
1085 assert!(res.unwrap()); }
1087
1088 #[crate::ctb_test]
1089 fn test_get_format_comments_utf8() {
1090 let comments = get_format_comments("ascii").unwrap();
1091 assert_eq!(comments, "7-bit ASCII. Variants: Line ending variants");
1092 }
1093
1094 #[crate::ctb_test]
1095 fn test_get_format_metrics_type_utf8() {
1096 let typ = get_format_metrics_type("utf8").unwrap();
1097 assert_eq!(typ, "character");
1098 let typ = get_format_metrics_type("unicode").unwrap();
1099 assert_eq!(typ, "internal-unicode");
1100 let typ = get_format_metrics_type("dcBasenb").unwrap();
1101 assert_eq!(typ, "complex-dcBasenb");
1102 }
1103}