token_string/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// SPDX-FileCopyrightText: Copyright (C) 2024 Roland Csaszar
// SPDX-License-Identifier: MPL-2.0
//
// Project:  token-string
// File:     error.rs
// Date:     22.Nov.2024
// =============================================================================
//! All errors of this crate.

use core::{error, fmt, str};

use crate::MAX_LENGTH;

#[non_exhaustive]
#[derive(Debug, PartialEq, Eq)]
/// The possible errors of this crate.
pub enum TkStrError {
	/// Cannot create a [`crate::TokenString`], the length would be bigger than
	/// [`MAX_LENGTH`].
	TooBig(usize),
	/// An error occurred encoding or decoding UTF-8 bytes.
	UnicodeError(str::Utf8Error),
	/// The index is out of bounds.
	OutOfBounds(usize),
	/// Too many strings are being concatenated, the [`crate::Builder`] has been
	/// configured for less.
	TooMany(usize),
}

impl fmt::Display for TkStrError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match *self {
			| Self::TooBig(n) => write!(
				f,
				"TokenString would be bigger than MAX_LENGTH, {n} > \
				 {MAX_LENGTH}"
			),
			| Self::UnicodeError(utf8_error) =>
				write!(f, "encoding TokenString: {utf8_error}"),
			| Self::OutOfBounds(i) => write!(f, "index {i} is out of bounds"),

			| Self::TooMany(n) => write!(
				f,
				"too many strings concatenated, Builder has been configured \
				 for {n} strings"
			),
		}
	}
}

impl error::Error for TkStrError {}

#[cfg(test)]
mod err_tests {
	#![expect(
		clippy::std_instead_of_alloc,
		reason = "We are testing, this needs std"
	)]
	extern crate std;

	use std::string::ToString as _;

	use assert2::check;

	use crate::TkStrError;

	#[test]
	fn string_too_big() {
		check!(
			TkStrError::TooBig(5).to_string()
				== "TokenString would be bigger than MAX_LENGTH, 5 > 65535"
		);
	}

	#[test]
	fn string_out_of_bounds() {
		check!(
			TkStrError::OutOfBounds(5).to_string()
				== "index 5 is out of bounds"
		);
	}

	#[test]
	fn string_too_many() {
		check!(
			TkStrError::TooMany(5).to_string()
				== "too many strings concatenated, Builder has been \
				    configured for 5 strings"
		);
	}
}