spinoso_string/
encoding.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
use core::fmt;

// ```
// [2.6.3] > Encoding::UTF_8.names
// => ["UTF-8", "CP65001", "locale", "external", "filesystem"]
// ```
const UTF8_NAMES: &[&str] = &["UTF-8", "CP65001"];
// ```
// [2.6.3] > Encoding::ASCII.names
// => ["US-ASCII", "ASCII", "ANSI_X3.4-1968", "646"]
// ```
const ASCII_NAMES: &[&str] = &["US-ASCII", "ASCII", "ANSI_X3.4-1968", "646"];
// ```
// [2.6.3] > Encoding::BINARY.names
// => ["ASCII-8BIT", "BINARY"]
// ```
const BINARY_NAMES: &[&str] = &["ASCII-8BIT", "BINARY"];

/// Error returned when failing to deserialize an [`Encoding`].
///
/// This error is returned from [`Encoding::try_from_flag`]. See its
/// documentation for more detail.
///
/// When the **std** feature of `spinoso-string` is enabled, this struct
/// implements [`std::error::Error`].
///
/// # Examples
///
/// ```
/// # use spinoso_string::{Encoding, InvalidEncodingError};
/// assert_eq!(
///     Encoding::try_from_flag(255),
///     Err(InvalidEncodingError::new())
/// );
/// assert_eq!(Encoding::try_from(255), Err(InvalidEncodingError::new()));
/// ```
///
/// [`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html
#[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct InvalidEncodingError {
    _private: (),
}

impl InvalidEncodingError {
    /// Construct a new `InvalidEncodingError`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_string::InvalidEncodingError;
    /// const ERR: InvalidEncodingError = InvalidEncodingError::new();
    /// ```
    #[must_use]
    pub const fn new() -> Self {
        Self { _private: () }
    }
}

impl fmt::Display for InvalidEncodingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Could not parse encoding")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for InvalidEncodingError {}

/// An Encoding instance represents a character encoding usable in Ruby.
///
/// `spinoso-string` supports three `String` encodings:
///
/// - [UTF-8](Self::Utf8)
/// - [ASCII](Self::Ascii)
/// - [Binary](Self::Binary)
///
/// A `String`'s encoding makes no assertions about the byte content of the
/// `String`'s internal buffer. The `Encoding` associated with a [`String`]
/// modifies how character-oriented APIs behave, for example
/// [`String::char_len`]. A `String` with an UTF-8 encoding is only
/// [conventionally UTF-8] and may contain invalid UTF-8 byte sequences.
///
/// Ruby provides the [`String#encode`] API which can transcode the bytes of a
/// `String` to another encoding. Calling `String#encode` on any of the
/// encodings defined in this enum is a no-op.
///
/// [`String`]: crate::String
/// [`String::char_len`]: crate::String::char_len
/// [UTF-8]: Self::Utf8
/// [conventionally UTF-8]: https://docs.rs/bstr/0.2.*/bstr/#differences-with-standard-strings
/// [`String#encode`]: https://ruby-doc.org/core-3.1.2/String.html#method-i-encode
#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum Encoding {
    /// Conventionally UTF-8.
    Utf8,
    /// Conventionally ASCII.
    Ascii,
    /// ASCII-8BIT, binary, arbitrary bytes.
    Binary,
}

impl Default for Encoding {
    #[inline]
    fn default() -> Self {
        Self::Utf8
    }
}

impl fmt::Debug for Encoding {
    /// Outputs the value of `Encoding#inspect`.
    ///
    /// Returns a string which represents the encoding for programmers. See
    /// [`Encoding::inspect`].
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.inspect())
    }
}

impl fmt::Display for Encoding {
    /// Outputs the value of `Encoding#to_s`.
    ///
    /// Returns the name of the encoding. See [`Encoding::name`].
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

impl TryFrom<u8> for Encoding {
    type Error = InvalidEncodingError;

    /// Try to deserialize an `Encoding` from a bitflag.
    ///
    /// See [`Encoding::try_from_flag`].
    #[inline]
    fn try_from(flag: u8) -> Result<Self, InvalidEncodingError> {
        Self::try_from_flag(flag)
    }
}

impl From<Encoding> for u8 {
    /// Serialize an `Encoding` to a bitflag.
    ///
    /// See [`Encoding::to_flag`].
    #[inline]
    fn from(encoding: Encoding) -> Self {
        encoding.to_flag()
    }
}

impl Encoding {
    /// The total number of supported encodings.
    ///
    /// `spinoso-string` supports three encodings:
    ///
    /// - [UTF-8](Self::Utf8)
    /// - [ASCII](Self::Ascii)
    /// - [Binary](Self::Binary)
    pub const NUM_SUPPORTED_ENCODINGS: usize = 3;

    /// Serialize the encoding to a bitflag.
    ///
    /// See [`try_from_flag`] for how to deserialize an encoding.
    ///
    /// This function is used to implement [`From<Encoding>`] for [`u8`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_string::Encoding;
    /// assert_eq!(Encoding::Utf8.to_flag(), 2);
    /// assert_eq!(Encoding::Ascii.to_flag(), 4);
    /// assert_eq!(Encoding::Binary.to_flag(), 8);
    /// ```
    ///
    /// [`try_from_flag`]: Self::try_from_flag
    /// [`From<Encoding>`]: From
    #[inline]
    #[must_use]
    pub const fn to_flag(self) -> u8 {
        match self {
            Self::Utf8 => 1 << 1,
            Self::Ascii => 1 << 2,
            Self::Binary => 1 << 3,
        }
    }

    /// Deserialize an encoding from a bitflag.
    ///
    /// See [`to_flag`] for how to serialize an encoding.
    ///
    /// This function is used to implement [`TryFrom<u8>`] for `Encoding`.
    ///
    /// # Errors
    ///
    /// If the given flag does not map to any [`Encoding`], an error is
    /// returned.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_string::{Encoding, InvalidEncodingError};
    /// assert_eq!(Encoding::try_from_flag(2), Ok(Encoding::Utf8));
    /// assert_eq!(Encoding::try_from_flag(4), Ok(Encoding::Ascii));
    /// assert_eq!(Encoding::try_from_flag(8), Ok(Encoding::Binary));
    /// assert_eq!(
    ///     Encoding::try_from_flag(2 | 4),
    ///     Err(InvalidEncodingError::new())
    /// );
    /// assert_eq!(
    ///     Encoding::try_from_flag(255),
    ///     Err(InvalidEncodingError::new())
    /// );
    /// ```
    ///
    /// [`to_flag`]: Self::to_flag
    /// [`TryFrom<u8>`]: TryFrom
    #[inline]
    pub const fn try_from_flag(flag: u8) -> Result<Self, InvalidEncodingError> {
        match flag {
            x if x == Self::Utf8.to_flag() => Ok(Self::Utf8),
            x if x == Self::Ascii.to_flag() => Ok(Self::Ascii),
            x if x == Self::Binary.to_flag() => Ok(Self::Binary),
            _ => Err(InvalidEncodingError::new()),
        }
    }

    /// Returns a string which represents the encoding for programmers.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_string::Encoding;
    /// assert_eq!(Encoding::Utf8.inspect(), "#<Encoding:UTF-8>");
    /// assert_eq!(Encoding::Ascii.inspect(), "#<Encoding:US-ASCII>");
    /// assert_eq!(Encoding::Binary.inspect(), "#<Encoding:ASCII-8BIT>");
    /// ```
    ///
    /// # Ruby Examples
    ///
    /// ```ruby
    /// Encoding::UTF_8.inspect       #=> "#<Encoding:UTF-8>"
    /// Encoding::ISO_2022_JP.inspect #=> "#<Encoding:ISO-2022-JP (dummy)>"
    /// ```
    #[must_use]
    pub const fn inspect(self) -> &'static str {
        match self {
            // ```
            // [2.6.3] > Encoding::UTF_8.inspect
            // => "#<Encoding:UTF-8>"
            // ```
            Self::Utf8 => "#<Encoding:UTF-8>",
            // ```
            // [2.6.3] > Encoding::ASCII.inspect
            // => "#<Encoding:US-ASCII>"
            // ```
            Self::Ascii => "#<Encoding:US-ASCII>",
            // ```
            // [2.6.3] > Encoding::BINARY.inspect
            // => "#<Encoding:ASCII-8BIT>"
            // ```
            Self::Binary => "#<Encoding:ASCII-8BIT>",
        }
    }

    /// Returns the name of the encoding.
    ///
    /// This function is used to implement [`fmt::Display`] for `Encoding`.
    ///
    /// This function can be used to implement the Ruby functions
    /// `Encoding#name` and `Encoding#to_s`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_string::Encoding;
    /// assert_eq!(Encoding::Utf8.name(), "UTF-8");
    /// assert_eq!(Encoding::Ascii.name(), "US-ASCII");
    /// assert_eq!(Encoding::Binary.name(), "ASCII-8BIT");
    /// ```
    ///
    /// # Ruby Examples
    ///
    /// ```ruby
    /// Encoding::UTF_8.name      #=> "UTF-8"
    /// ```
    #[inline]
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            // ```
            // [2.6.3] > Encoding::UTF_8.name
            // => "UTF-8"
            // ```
            Self::Utf8 => "UTF-8",
            // ```
            // [2.6.3] > Encoding::ASCII.name
            // => "US-ASCII"
            // ```
            Self::Ascii => "US-ASCII",
            // ```
            // [2.6.3] > Encoding::BINARY.name
            // => "ASCII-8BIT"
            // ```
            Self::Binary => "ASCII-8BIT",
        }
    }

    /// Returns the list of name and aliases of the encoding.
    ///
    /// This function can be used to implement the Ruby function
    /// `Encoding#names`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_string::Encoding;
    /// assert_eq!(Encoding::Utf8.names(), ["UTF-8", "CP65001"]);
    /// assert_eq!(
    ///     Encoding::Ascii.names(),
    ///     ["US-ASCII", "ASCII", "ANSI_X3.4-1968", "646"]
    /// );
    /// assert_eq!(Encoding::Binary.names(), ["ASCII-8BIT", "BINARY"]);
    /// ```
    ///
    /// # Ruby Examples
    ///
    /// ```ruby
    /// Encoding::WINDOWS_31J.names  #=> ["Windows-31J", "CP932", "csWindows31J"]
    /// ```
    #[inline]
    #[must_use]
    pub const fn names(self) -> &'static [&'static str] {
        match self {
            Self::Utf8 => UTF8_NAMES,
            Self::Ascii => ASCII_NAMES,
            Self::Binary => BINARY_NAMES,
        }
    }

    /// Returns whether ASCII-compatible or not.
    ///
    /// This function can be used to implement the Ruby function
    /// `Encoding#ascii_compatible?`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_string::Encoding;
    /// assert!(Encoding::Utf8.is_ascii_compatible());
    /// assert!(Encoding::Ascii.is_ascii_compatible());
    /// assert!(Encoding::Binary.is_ascii_compatible());
    /// ```
    ///
    /// # Ruby Examples
    ///
    /// ```ruby
    /// Encoding::UTF_8.ascii_compatible?     #=> true
    /// Encoding::UTF_16BE.ascii_compatible?  #=> false
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_ascii_compatible(self) -> bool {
        matches!(self, Self::Utf8 | Self::Ascii | Self::Binary)
    }

    /// Returns true for dummy encodings.
    ///
    /// A dummy encoding is an encoding for which character handling is not
    /// properly implemented. It is used for stateful encodings.
    ///
    /// This function can be used to implement the Ruby function
    /// `Encoding#dummy?`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_string::Encoding;
    /// assert!(!Encoding::Utf8.is_dummy());
    /// assert!(!Encoding::Ascii.is_dummy());
    /// assert!(!Encoding::Binary.is_dummy());
    /// ```
    ///
    /// # Ruby Examples
    ///
    /// ```ruby
    /// Encoding::ISO_2022_JP.dummy?       #=> true
    /// Encoding::UTF_8.dummy?             #=> false
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_dummy(self) -> bool {
        !matches!(self, Self::Utf8 | Self::Ascii | Self::Binary)
    }
}