ctb_formats_dcstring/error.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//! Error types for UTF-8e-128 / DcUtf validation.
21
22#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::fmt;
30
31/// An error returned when validating a byte slice as UTF-8e-128 / DcUtf.
32#[derive(Copy, Clone, Debug, Eq, PartialEq)]
33pub struct DcUtfError {
34 pub(crate) valid_up_to: usize,
35 pub(crate) error_len: Option<usize>,
36}
37
38impl DcUtfError {
39 /// Returns the index in the given byte slice up to which valid UTF-8e-128
40 /// was verified.
41 #[must_use]
42 pub const fn valid_up_to(&self) -> usize {
43 self.valid_up_to
44 }
45
46 /// Returns the length of the invalid sequence if known, or `None` if the
47 /// input ended unexpectedly before completing a sequence.
48 #[must_use]
49 pub const fn error_len(&self) -> Option<usize> {
50 self.error_len
51 }
52}
53
54impl fmt::Display for DcUtfError {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 if let Some(len) = self.error_len {
57 write!(
58 f,
59 "invalid UTF-8e-128 sequence of {len} bytes starting at index {}",
60 self.valid_up_to
61 )
62 } else {
63 write!(
64 f,
65 "unexpected end of data while decoding UTF-8e-128 at index {}",
66 self.valid_up_to
67 )
68 }
69 }
70}
71
72impl std::error::Error for DcUtfError {}