spinoso_string/ord.rs
1use core::fmt;
2
3#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
4pub enum OrdError {
5 /// The first character in a [conventionally UTF-8] `String` is an invalid
6 /// UTF-8 byte sequence.
7 ///
8 /// [conventionally UTF-8]: crate::Encoding::Utf8
9 InvalidUtf8ByteSequence,
10 /// The given `String` is empty and has no first character.
11 EmptyString,
12}
13
14impl OrdError {
15 /// `OrdError` corresponds to an [`ArgumentError`] Ruby exception.
16 ///
17 /// [`ArgumentError`]: https://ruby-doc.org/core-3.1.2/ArgumentError.html
18 pub const EXCEPTION_TYPE: &'static str = "ArgumentError";
19
20 /// Construct a new `OrdError` for an invalid UTF-8 byte sequence.
21 ///
22 /// Only [conventionally UTF-8] `String`s can generate this error.
23 ///
24 /// # Examples
25 ///
26 /// ```
27 /// use spinoso_string::{OrdError, String};
28 ///
29 /// let s = String::utf8(b"\xFFabc".to_vec());
30 /// assert_eq!(s.ord(), Err(OrdError::invalid_utf8_byte_sequence()));
31 ///
32 /// let s = String::binary(b"\xFFabc".to_vec());
33 /// assert_eq!(s.ord(), Ok(0xFF));
34 /// ```
35 ///
36 /// [conventionally UTF-8]: crate::Encoding::Utf8
37 #[inline]
38 #[must_use]
39 pub const fn invalid_utf8_byte_sequence() -> Self {
40 Self::InvalidUtf8ByteSequence
41 }
42
43 /// Construct a new `OrdError` for an empty `String`.
44 ///
45 /// Empty `String`s have no first character. Empty `String`s with any
46 /// encoding return this error.
47 ///
48 /// # Examples
49 ///
50 /// ```
51 /// use spinoso_string::{OrdError, String};
52 ///
53 /// let s = String::utf8(b"\xFFabc".to_vec());
54 /// assert_eq!(s.ord(), Err(OrdError::invalid_utf8_byte_sequence()));
55 /// ```
56 #[inline]
57 #[must_use]
58 pub const fn empty_string() -> Self {
59 Self::EmptyString
60 }
61
62 /// Error message for this `OrdError`.
63 ///
64 /// This message is suitable for generating an [`ArgumentError`] exception
65 /// from this `OrdError`.
66 ///
67 /// # Examples
68 ///
69 /// ```
70 /// # use spinoso_string::OrdError;
71 ///
72 /// assert_eq!(
73 /// OrdError::invalid_utf8_byte_sequence().message(),
74 /// "invalid byte sequence in UTF-8"
75 /// );
76 /// assert_eq!(OrdError::empty_string().message(), "empty string");
77 /// ```
78 ///
79 /// [`ArgumentError`]: https://ruby-doc.org/core-3.1.2/ArgumentError.html
80 #[inline]
81 #[must_use]
82 pub const fn message(self) -> &'static str {
83 match self {
84 Self::InvalidUtf8ByteSequence => "invalid byte sequence in UTF-8",
85 Self::EmptyString => "empty string",
86 }
87 }
88}
89
90impl fmt::Display for OrdError {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 f.write_str(self.message())
93 }
94}
95
96#[cfg(feature = "std")]
97impl std::error::Error for OrdError {}