ctb_formats_utilities/
utilities.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! File format detection, magic number lookup, and extension mapping tools.
21
22pub mod extension_rule;
23pub mod platform;
24pub use extension_rule::{CaseSensitivity, ExtensionRule};
25
26pub mod detection {
27    pub use crate::platform::{current_platform_os, is_os_match};
28    pub mod extension {
29        pub use crate::extension_rule::{CaseSensitivity, ExtensionRule};
30    }
31}
32#[rustfmt::skip]
33#[path = "encoding.generated.rs"]
34pub mod encoding;
35#[rustfmt::skip]
36#[path = "extension_data.generated.rs"]
37pub mod extension_data;
38pub mod format_info;
39
40pub use ctb_utilities::FormatId;
41pub use ctb_utilities::format_id;
42pub use format_info::{
43    FormatInfo, FormatInfoOptionExt, describe_format,
44    format_categorized_help_table, format_help_table, get_format_info,
45    get_format_info_by_id, infer_decompressed_path, strip_format_extension,
46};
47pub mod cli_document;
48pub mod cli_io;
49pub use cli_document::{
50    CliAutoDocumentInputArgs, CliDocumentInputArgs, CliDocumentOutputArgs,
51    parse_supported_dc_input_format, parse_supported_dc_output_format,
52    parse_supported_dc_transformation,
53};
54pub use cli_io::{CliInputSourceArgs, CliOutputDestArgs};
55
56#[allow(
57    unused_imports,
58    clippy::wildcard_imports,
59    reason = "Standard workspace crate prelude"
60)]
61pub(crate) use ctb_utilities::*;
62
63// Trait to extend char with a as_utf8_bytes() convenience method
64pub trait CharUtfBytesExt {
65    fn as_utf8_bytes(&self) -> Vec<u8>;
66}
67
68impl CharUtfBytesExt for char {
69    /// Similar to `encode_utf8` - more convenient, but slower and copies.
70    fn as_utf8_bytes(&self) -> Vec<u8> {
71        let mut buf = [0u8; 4];
72        let s = self.encode_utf8(&mut buf);
73        s.as_bytes().to_vec()
74    }
75}
76
77pub use ctb_formats_dcdata::describe_general_category;
78
79/// Output wrapper for format conversion operations, returning the converted result
80/// alongside any accumulated conversion log warnings/errors.
81#[derive(Debug)]
82#[must_use]
83pub struct ConversionOutput<T> {
84    pub result: T,
85    pub log: FormatLog,
86}
87
88impl<T> ConversionOutput<T> {
89    pub fn new(result: T, log: FormatLog) -> Self {
90        Self { result, log }
91    }
92}
93
94#[derive(Default, Debug)]
95#[must_use]
96pub struct FormatLog {
97    errors: Vec<String>,
98    warnings: Vec<String>,
99    debug_messages: Vec<String>,
100    /// Stores the order and type of all log entries, so that formatting can preserve log order and type.
101    log_order: Vec<(LogType, usize)>,
102}
103
104/// Tracks the type of log entry.
105#[derive(Copy, Clone, Debug)]
106enum LogType {
107    Error,
108    Warning,
109    Debug,
110}
111
112impl FormatLog {
113    /// Record a serious error that may indicate the document could not be fully processed.
114    pub fn error(&mut self, message: &str) {
115        #[cfg(debug_assertions)]
116        crate::debug!("FormatLog error: {}", message);
117        self.errors.push(message.to_string());
118        self.log_order
119            .push((LogType::Error, self.errors.len().saturating_sub(1)));
120    }
121
122    pub fn warn(&mut self, message: &str) {
123        #[cfg(debug_assertions)]
124        crate::debug!("FormatLog warn: {}", message);
125        self.warnings.push(message.to_string());
126        self.log_order
127            .push((LogType::Warning, self.warnings.len().saturating_sub(1)));
128    }
129
130    #[cfg(not(debug_assertions))]
131    pub fn debug(&mut self, message: &str) {}
132
133    #[cfg(debug_assertions)]
134    pub fn debug(&mut self, message: &str) {
135        #[cfg(debug_assertions)]
136        crate::debug!("FormatLog debug: {}", message);
137        self.debug_messages.push(message.to_string());
138        self.log_order.push((
139            LogType::Debug,
140            self.debug_messages.len().saturating_sub(1),
141        ));
142    }
143
144    pub fn get_errors(&self) -> Vec<String> {
145        self.errors.clone()
146    }
147
148    pub fn get_warnings(&self) -> Vec<String> {
149        self.warnings.clone()
150    }
151
152    pub fn has_errors(&self) -> bool {
153        !self.errors.is_empty()
154    }
155
156    pub fn has_no_errors(&self) -> bool {
157        !self.has_errors()
158    }
159
160    pub fn has_warnings(&self) -> bool {
161        !self.warnings.is_empty()
162    }
163
164    pub fn has_debug_messages(&self) -> bool {
165        !self.debug_messages.is_empty()
166    }
167
168    pub fn has_any(&self) -> bool {
169        self.has_errors() || self.has_warnings() || self.has_debug_messages()
170    }
171
172    pub fn has_warnings_or_errors(&self) -> bool {
173        self.has_warnings() || self.has_errors()
174    }
175
176    pub fn has_no_warnings_or_errors(&self) -> bool {
177        !self.has_warnings_or_errors()
178    }
179
180    /// Add an import error at a specific character index and problem description.
181    pub fn import_error(&mut self, index: u64, problem: &str) {
182        let error = format!(
183            "An unrecoverable problem was encountered while importing at character {index}: {problem}"
184        );
185        self.error(error.as_str());
186    }
187
188    /// Add an import warning for a specific character index and problem description.
189    pub fn import_warning(&mut self, index: u64, problem: &str) {
190        let warn = format!(
191            "A problem was encountered while importing at character {index}: {problem}"
192        );
193        self.warn(warn.as_str());
194    }
195
196    /// Add an export error at a specific character index and problem description.
197    pub fn export_error(&mut self, index: u64, problem: &str) {
198        let error = format!(
199            "An unrecoverable problem was encountered while exporting at character {index}: {problem}"
200        );
201        self.error(error.as_str());
202    }
203
204    /// Add an export warning for a specific character index and problem description.
205    pub fn export_warning(&mut self, index: u64, problem: &str) {
206        let warn = format!(
207            "A problem was encountered while exporting at character {index}: {problem}"
208        );
209        self.warn(warn.as_str());
210    }
211
212    pub fn export_warning_unmappable(
213        &mut self,
214        index: u64,
215        problem_dc: u32,
216        format: &str,
217    ) {
218        self.export_warning(index, format!("The character {problem_dc} could not be represented in the chosen export format ({format}).").as_str());
219    }
220
221    pub fn merge(&mut self, other: &FormatLog) {
222        let error_offset = self.errors.len();
223        let warning_offset = self.warnings.len();
224        let debug_offset = self.debug_messages.len();
225
226        self.errors.extend(other.errors.clone());
227        self.warnings.extend(other.warnings.clone());
228        self.debug_messages.extend(other.debug_messages.clone());
229
230        for &(typ, idx) in &other.log_order {
231            let adjusted_idx = match typ {
232                LogType::Error => idx.saturating_add(error_offset),
233                LogType::Warning => idx.saturating_add(warning_offset),
234                LogType::Debug => idx.saturating_add(debug_offset),
235            };
236            self.log_order.push((typ, adjusted_idx));
237        }
238    }
239
240    /// Formats all log messages in the order they were logged, with proper prefixing.
241    pub fn format_all(&self) -> String {
242        if !self.has_any() {
243            return String::new();
244        }
245        let mut output = String::new();
246        output.push_str("Messages during format processing:\n");
247        // idx are not consecutive if printed, this uses them to encode the sort
248        // order, I think. They're consecutive w/i each message type.
249        for &(typ, idx) in &self.log_order {
250            match typ {
251                LogType::Error => {
252                    output.push_str("* [ERROR] ");
253                    if let Some(msg) = self.errors.get(idx) {
254                        output.push_str(msg);
255                    }
256                }
257                LogType::Warning => {
258                    output.push_str("- [WARNING] ");
259                    if let Some(msg) = self.warnings.get(idx) {
260                        output.push_str(msg);
261                    }
262                }
263                LogType::Debug => {
264                    output.push_str("- [DEBUG] ");
265                    if let Some(msg) = self.debug_messages.get(idx) {
266                        output.push_str(msg);
267                    }
268                }
269            }
270            output.push('\n');
271        }
272        output
273    }
274
275    pub fn format_errors(&self) -> String {
276        let mut errors = String::new();
277        if self.has_errors() {
278            for e in &self.errors {
279                errors.push_str("- ");
280                errors.push_str(e);
281                errors.push('\n');
282            }
283            format!("Errors during format processing:\n{errors}")
284        } else {
285            String::new()
286        }
287    }
288
289    pub fn format_warnings(&self) -> String {
290        let mut warnings = String::new();
291        if self.has_warnings() {
292            for w in &self.warnings {
293                warnings.push_str("- ");
294                warnings.push_str(w);
295                warnings.push('\n');
296            }
297            format!("Warnings during format processing:\n{warnings}")
298        } else {
299            String::new()
300        }
301    }
302
303    pub fn format_debug(&self) -> String {
304        let mut debug = String::new();
305        if self.debug_messages.is_empty() {
306            String::new()
307        } else {
308            for d in &self.debug_messages {
309                debug.push_str("- ");
310                debug.push_str(d);
311                debug.push('\n');
312            }
313            format!("Debug messages during format processing:\n{debug}")
314        }
315    }
316
317    pub fn auto_log(&self) {
318        if self.has_any() {
319            if self.has_errors() {
320                error_fmt!("{}", self.format_errors().trim_end());
321            }
322            if self.has_warnings() {
323                warn_fmt!("{}", self.format_warnings().trim_end());
324            }
325            if self.has_debug_messages() {
326                debug_fmt!("{}", self.format_debug().trim_end());
327            }
328        } else {
329            debug!("No errors or warnings during format processing.");
330        }
331    }
332}
333
334impl std::fmt::Display for FormatLog {
335    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
336        if self.has_any() {
337            writeln!(f, "{}", self.format_all())?;
338        } else {
339            writeln!(f, "No errors or warnings during format processing.")?;
340        }
341        Ok(())
342    }
343}
344
345// Test helpers
346#[expect(
347    clippy::unwrap_used,
348    reason = "Assertion helper function in test utilities"
349)]
350pub fn assert_vec_u8_ok_eq_no_warnings(
351    expected: &[u8],
352    actual: Result<(Vec<u8>, FormatLog)>,
353) -> Vec<u8> {
354    let (actual_bytes, log) = actual.unwrap();
355    assert!(
356        log.has_no_warnings_or_errors(),
357        "Warnings or errors found:\n{}",
358        log.format_all()
359    );
360    assert_vec_u8_eq_log(expected, &actual_bytes, &log);
361    actual_bytes
362}
363
364#[expect(
365    clippy::unwrap_used,
366    reason = "Assertion helper function in test utilities"
367)]
368pub fn assert_vec_u8_ok_eq_no_errors(
369    expected: &[u8],
370    actual: Result<(Vec<u8>, FormatLog)>,
371) -> (Vec<u8>, FormatLog) {
372    let (actual_bytes, log) = actual.unwrap();
373
374    assert!(log.has_no_errors(), "Errors found:\n{}", log.format_all());
375    assert_vec_u8_eq_log(expected, &actual_bytes, &log);
376    (actual_bytes, log)
377}
378
379#[expect(
380    clippy::unwrap_used,
381    reason = "Assertion helper function in test utilities"
382)]
383fn _assert_vec_u32_ok_eq_log(
384    expected: &[u32],
385    actual: Result<(Vec<u32>, FormatLog)>,
386    disallow_warnings: bool,
387) -> (Vec<u32>, FormatLog) {
388    let (actual_vec, log) = actual.unwrap();
389
390    let mut log_problem_type = "Errors";
391    if disallow_warnings {
392        log_problem_type = "Warnings or errors";
393    }
394    let message = format!("{log_problem_type} found:\n{}", log.format_all());
395
396    if disallow_warnings {
397        assert!(log.has_no_warnings_or_errors(), "{message}");
398    } else {
399        assert!(log.has_no_errors(), "{message}");
400    }
401
402    assert_vec_u32_eq_log(expected, &actual_vec, &log);
403
404    (actual_vec, log)
405}
406
407pub fn assert_vec_u32_ok_eq_no_warnings(
408    expected: &[u32],
409    actual: Result<(Vec<u32>, FormatLog)>,
410) -> Vec<u32> {
411    let (actual_vec, log) = _assert_vec_u32_ok_eq_log(expected, actual, true);
412    log.auto_log();
413    actual_vec
414}
415
416pub fn assert_vec_u32_ok_eq_no_errors(
417    expected: &[u32],
418    actual: Result<(Vec<u32>, FormatLog)>,
419) -> (Vec<u32>, FormatLog) {
420    _assert_vec_u32_ok_eq_log(expected, actual, false)
421}
422
423/// Equivalent to `assert_vec_u32_eq`, but prints the provided log on failure
424pub fn assert_vec_u32_eq_log(
425    expected: &[u32],
426    actual: &[u32],
427    log: &FormatLog,
428) {
429    _assert_vec_u32_eq_log(expected, actual, log);
430}
431
432fn _assert_vec_u32_eq_log(expected: &[u32], actual: &[u32], log: &FormatLog) {
433    let message = format!(
434        "Vectors (u32) differ.\n{}\nLog:      {}",
435        fmt_mismatch_vec_u32(expected, actual),
436        log.format_all()
437    );
438
439    assert_eq!(expected, actual, "{message}");
440}
441
442/// Equivalent to `assert_vec_u8_eq`, but prints the provided log on failure
443pub fn assert_vec_u8_eq_log(expected: &[u8], actual: &[u8], log: &FormatLog) {
444    assert_eq!(
445        expected,
446        actual,
447        "Vectors (u8) differ.\n{}\nLog:      {}",
448        fmt_mismatch_vec_u8(expected, actual),
449        log.format_all()
450    );
451}
452
453pub fn assert_string_eq(expected: &str, actual: String) -> String {
454    let actual_string = actual;
455
456    assert_eq!(
457        expected,
458        &actual_string,
459        "Strings differ.\n{}",
460        fmt_mismatch_string(expected, &actual_string),
461    );
462    actual_string
463}
464
465#[expect(
466    clippy::unwrap_used,
467    reason = "Assertion helper function in test utilities"
468)]
469pub fn assert_string_ok_eq(expected: &str, actual: Result<String>) -> String {
470    let actual_string = actual.unwrap();
471
472    assert_eq!(
473        expected,
474        &actual_string,
475        "Strings differ.\n{}",
476        fmt_mismatch_string(expected, &actual_string),
477    );
478    actual_string
479}
480
481#[expect(
482    clippy::unwrap_used,
483    reason = "Assertion helper function in test utilities"
484)]
485pub fn assert_string_ok_eq_no_warnings(
486    expected: &str,
487    actual: Result<(String, FormatLog)>,
488) -> String {
489    let (actual_string, log) = actual.unwrap();
490
491    assert!(
492        log.has_no_warnings_or_errors(),
493        "Warnings or errors found:\n{}",
494        log.format_all()
495    );
496    assert_eq!(
497        expected,
498        &actual_string,
499        "Strings differ.\n{}\nLog:      {}",
500        fmt_mismatch_string(expected, &actual_string),
501        log.format_all()
502    );
503    actual_string
504}
505
506#[expect(
507    clippy::unwrap_used,
508    reason = "Assertion helper function in test utilities"
509)]
510pub fn assert_string_ok_eq_no_errors(
511    expected: &str,
512    actual: Result<(String, FormatLog)>,
513) -> (String, FormatLog) {
514    let (actual_string, log) = actual.unwrap();
515
516    assert!(log.has_no_errors(), "Errors found:\n{}", log.format_all());
517    assert_eq!(
518        expected,
519        &actual_string,
520        "Strings differ.\n{}\nLog:      {}",
521        fmt_mismatch_string(expected, &actual_string),
522        log.format_all()
523    );
524    (actual_string, log)
525}