Short (up to 65,535 bytes) immutable strings to e.g. parse tokens, implemented in Rust. These are sometimes called "German Strings", because Germans have written the paper mentioning them
at main 91 lines 2.1 kB view raw
1// SPDX-FileCopyrightText: Copyright (C) 2024 Roland Csaszar 2// SPDX-License-Identifier: MPL-2.0 3// 4// Project: token-string 5// File: error.rs 6// Date: 22.Nov.2024 7// ============================================================================= 8//! All errors of this crate. 9 10use core::{error, fmt, str}; 11 12use crate::MAX_LENGTH; 13 14#[non_exhaustive] 15#[derive(Debug, PartialEq, Eq)] 16/// The possible errors of this crate. 17pub enum TkStrError { 18 /// Cannot create a [`crate::TokenString`], the length would be bigger than 19 /// [`MAX_LENGTH`]. 20 TooBig(usize), 21 /// An error occurred encoding or decoding UTF-8 bytes. 22 UnicodeError(str::Utf8Error), 23 /// The index is out of bounds. 24 OutOfBounds(usize), 25 /// Too many strings are being concatenated, the [`crate::Builder`] has been 26 /// configured for less. 27 TooMany(usize), 28} 29 30impl fmt::Display for TkStrError { 31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 32 match *self { 33 | Self::TooBig(n) => write!( 34 f, 35 "TokenString would be bigger than MAX_LENGTH, {n} > \ 36 {MAX_LENGTH}" 37 ), 38 | Self::UnicodeError(utf8_error) => 39 write!(f, "encoding TokenString: {utf8_error}"), 40 | Self::OutOfBounds(i) => write!(f, "index {i} is out of bounds"), 41 42 | Self::TooMany(n) => write!( 43 f, 44 "too many strings concatenated, Builder has been configured \ 45 for {n} strings" 46 ), 47 } 48 } 49} 50 51impl error::Error for TkStrError {} 52 53#[cfg(test)] 54mod err_tests { 55 #![expect( 56 clippy::std_instead_of_alloc, 57 reason = "We are testing, this needs std" 58 )] 59 extern crate std; 60 61 use std::string::ToString as _; 62 63 use assert2::check; 64 65 use crate::TkStrError; 66 67 #[test] 68 fn string_too_big() { 69 check!( 70 TkStrError::TooBig(5).to_string() 71 == "TokenString would be bigger than MAX_LENGTH, 5 > 65535" 72 ); 73 } 74 75 #[test] 76 fn string_out_of_bounds() { 77 check!( 78 TkStrError::OutOfBounds(5).to_string() 79 == "index 5 is out of bounds" 80 ); 81 } 82 83 #[test] 84 fn string_too_many() { 85 check!( 86 TkStrError::TooMany(5).to_string() 87 == "too many strings concatenated, Builder has been \ 88 configured for 5 strings" 89 ); 90 } 91}