Debian Codegraph @

src/ascii_char.rs

raw symbols ◀ ▶ SCIP
3 Debian patches touch this file
1 use core::cmp::Ordering;
2 use core::mem;
3 use core::{char, fmt};
4 #[cfg(feature = "std")]
5 use std::error::Error;
6
7 #[allow(non_camel_case_types)]
8 /// An ASCII character. It wraps a `u8`, with the highest bit always zero.
9 #[derive(Clone, PartialEq, PartialOrd, Ord, Eq, Hash, Copy)]
10 #[repr(u8)]
11 pub enum AsciiChar {
12 /// `'\0'`
13 Null = 0,
14 /// [Start Of Heading](http://en.wikipedia.org/wiki/Start_of_Heading)
15 SOH = 1,
16 /// [Start Of teXt](http://en.wikipedia.org/wiki/Start_of_Text)
17 SOX = 2,
18 /// [End of TeXt](http://en.wikipedia.org/wiki/End-of-Text_character)
19 ETX = 3,
20 /// [End Of Transmission](http://en.wikipedia.org/wiki/End-of-Transmission_character)
21 EOT = 4,
22 /// [Enquiry](http://en.wikipedia.org/wiki/Enquiry_character)
23 ENQ = 5,
24 /// [Acknowledgement](http://en.wikipedia.org/wiki/Acknowledge_character)
25 ACK = 6,
26 /// [bell / alarm / audible](http://en.wikipedia.org/wiki/Bell_character)
27 ///
28 /// `'\a'` is not recognized by Rust.
29 Bell = 7,
30 /// [Backspace](http://en.wikipedia.org/wiki/Backspace)
31 ///
32 /// `'\b'` is not recognized by Rust.
33 BackSpace = 8,
34 /// `'\t'`
35 Tab = 9,
36 /// `'\n'`
37 LineFeed = 10,
38 /// [Vertical tab](http://en.wikipedia.org/wiki/Vertical_Tab)
39 ///
40 /// `'\v'` is not recognized by Rust.
41 VT = 11,
42 /// [Form Feed](http://en.wikipedia.org/wiki/Form_Feed)
43 ///
44 /// `'\f'` is not recognized by Rust.
45 FF = 12,
46 /// `'\r'`
47 CarriageReturn = 13,
48 /// [Shift In](http://en.wikipedia.org/wiki/Shift_Out_and_Shift_In_characters)
49 SI = 14,
50 /// [Shift Out](http://en.wikipedia.org/wiki/Shift_Out_and_Shift_In_characters)
51 SO = 15,
52 /// [Data Link Escape](http://en.wikipedia.org/wiki/Data_Link_Escape)
53 DLE = 16,
54 /// [Device control 1, often XON](http://en.wikipedia.org/wiki/Device_Control_1)
55 DC1 = 17,
56 /// Device control 2
57 DC2 = 18,
58 /// Device control 3, Often XOFF
59 DC3 = 19,
60 /// Device control 4
61 DC4 = 20,
62 /// [Negative AcKnowledgement](http://en.wikipedia.org/wiki/Negative-acknowledge_character)
63 NAK = 21,
64 /// [Synchronous idle](http://en.wikipedia.org/wiki/Synchronous_Idle)
65 SYN = 22,
66 /// [End of Transmission Block](http://en.wikipedia.org/wiki/End-of-Transmission-Block_character)
67 ETB = 23,
68 /// [Cancel](http://en.wikipedia.org/wiki/Cancel_character)
69 CAN = 24,
70 /// [End of Medium](http://en.wikipedia.org/wiki/End_of_Medium)
71 EM = 25,
72 /// [Substitute](http://en.wikipedia.org/wiki/Substitute_character)
73 SUB = 26,
74 /// [Escape](http://en.wikipedia.org/wiki/Escape_character)
75 ///
76 /// `'\e'` is not recognized by Rust.
77 ESC = 27,
78 /// [File Separator](http://en.wikipedia.org/wiki/File_separator)
79 FS = 28,
80 /// [Group Separator](http://en.wikipedia.org/wiki/Group_separator)
81 GS = 29,
82 /// [Record Separator](http://en.wikipedia.org/wiki/Record_separator)
83 RS = 30,
84 /// [Unit Separator](http://en.wikipedia.org/wiki/Unit_separator)
85 US = 31,
86 /// `' '`
87 Space = 32,
88 /// `'!'`
89 Exclamation = 33,
90 /// `'"'`
91 Quotation = 34,
92 /// `'#'`
93 Hash = 35,
94 /// `'$'`
95 Dollar = 36,
96 /// `'%'`
97 Percent = 37,
98 /// `'&'`
99 Ampersand = 38,
100 /// `'\''`
101 Apostrophe = 39,
102 /// `'('`
103 ParenOpen = 40,
104 /// `')'`
105 ParenClose = 41,
106 /// `'*'`
107 Asterisk = 42,
108 /// `'+'`
109 Plus = 43,
110 /// `','`
111 Comma = 44,
112 /// `'-'`
113 Minus = 45,
114 /// `'.'`
115 Dot = 46,
116 /// `'/'`
117 Slash = 47,
118 /// `'0'`
119 _0 = 48,
120 /// `'1'`
121 _1 = 49,
122 /// `'2'`
123 _2 = 50,
124 /// `'3'`
125 _3 = 51,
126 /// `'4'`
127 _4 = 52,
128 /// `'5'`
129 _5 = 53,
130 /// `'6'`
131 _6 = 54,
132 /// `'7'`
133 _7 = 55,
134 /// `'8'`
135 _8 = 56,
136 /// `'9'`
137 _9 = 57,
138 /// `':'`
139 Colon = 58,
140 /// `';'`
141 Semicolon = 59,
142 /// `'<'`
143 LessThan = 60,
144 /// `'='`
145 Equal = 61,
146 /// `'>'`
147 GreaterThan = 62,
148 /// `'?'`
149 Question = 63,
150 /// `'@'`
151 At = 64,
152 /// `'A'`
153 A = 65,
154 /// `'B'`
155 B = 66,
156 /// `'C'`
157 C = 67,
158 /// `'D'`
159 D = 68,
160 /// `'E'`
161 E = 69,
162 /// `'F'`
163 F = 70,
164 /// `'G'`
165 G = 71,
166 /// `'H'`
167 H = 72,
168 /// `'I'`
169 I = 73,
170 /// `'J'`
171 J = 74,
172 /// `'K'`
173 K = 75,
174 /// `'L'`
175 L = 76,
176 /// `'M'`
177 M = 77,
178 /// `'N'`
179 N = 78,
180 /// `'O'`
181 O = 79,
182 /// `'P'`
183 P = 80,
184 /// `'Q'`
185 Q = 81,
186 /// `'R'`
187 R = 82,
188 /// `'S'`
189 S = 83,
190 /// `'T'`
191 T = 84,
192 /// `'U'`
193 U = 85,
194 /// `'V'`
195 V = 86,
196 /// `'W'`
197 W = 87,
198 /// `'X'`
199 X = 88,
200 /// `'Y'`
201 Y = 89,
202 /// `'Z'`
203 Z = 90,
204 /// `'['`
205 BracketOpen = 91,
206 /// `'\'`
207 BackSlash = 92,
208 /// `']'`
209 BracketClose = 93,
210 /// `'^'`
211 Caret = 94,
212 /// `'_'`
213 UnderScore = 95,
214 /// `'`'`
215 Grave = 96,
216 /// `'a'`
217 a = 97,
218 /// `'b'`
219 b = 98,
220 /// `'c'`
221 c = 99,
222 /// `'d'`
223 d = 100,
224 /// `'e'`
225 e = 101,
226 /// `'f'`
227 f = 102,
228 /// `'g'`
229 g = 103,
230 /// `'h'`
231 h = 104,
232 /// `'i'`
233 i = 105,
234 /// `'j'`
235 j = 106,
236 /// `'k'`
237 k = 107,
238 /// `'l'`
239 l = 108,
240 /// `'m'`
241 m = 109,
242 /// `'n'`
243 n = 110,
244 /// `'o'`
245 o = 111,
246 /// `'p'`
247 p = 112,
248 /// `'q'`
249 q = 113,
250 /// `'r'`
251 r = 114,
252 /// `'s'`
253 s = 115,
254 /// `'t'`
255 t = 116,
256 /// `'u'`
257 u = 117,
258 /// `'v'`
259 v = 118,
260 /// `'w'`
261 w = 119,
262 /// `'x'`
263 x = 120,
264 /// `'y'`
265 y = 121,
266 /// `'z'`
267 z = 122,
268 /// `'{'`
269 CurlyBraceOpen = 123,
270 /// `'|'`
271 VerticalBar = 124,
272 /// `'}'`
273 CurlyBraceClose = 125,
274 /// `'~'`
275 Tilde = 126,
276 /// [Delete](http://en.wikipedia.org/wiki/Delete_character)
277 DEL = 127,
278 }
279
280 impl AsciiChar {
281 /// Constructs an ASCII character from a `u8`, `char` or other character type.
282 ///
283 /// # Errors
284 /// Returns `Err(())` if the character can't be ASCII encoded.
285 ///
286 /// # Example
287 /// ```
288 /// # #![allow(bindings_with_variant_name)]
289 /// # use ascii::AsciiChar;
290 /// let a = AsciiChar::from_ascii('g').unwrap();
291 /// assert_eq!(a.as_char(), 'g');
292 /// ```
293 #[inline]
294 pub fn from_ascii<C: ToAsciiChar>(ch: C) -> Result<Self, ToAsciiCharError> {
295 ch.to_ascii_char()
296 }
297
•298 /// Create an `AsciiChar` from a `char`, panicking if it's not ASCII.
299 ///
300 /// This function is intended for creating `AsciiChar` values from
301 /// hardcoded known-good character literals such as `'K'`, `'-'` or `'\0'`,
302 /// and for use in `const` contexts.
303 /// Use [`from_ascii()`](#method.from_ascii) instead when you're not
304 /// certain the character is ASCII.
305 ///
306 /// # Examples
307 ///
308 /// ```
309 /// # use ascii::AsciiChar;
310 /// assert_eq!(AsciiChar::new('@'), AsciiChar::At);
311 /// assert_eq!(AsciiChar::new('C').as_char(), 'C');
312 /// ```
313 ///
314 /// In a constant:
315 /// ```
316 /// # use ascii::AsciiChar;
317 /// const SPLIT_ON: AsciiChar = AsciiChar::new(',');
318 /// ```
319 ///
320 /// This will not compile:
321 /// ```compile_fail
322 /// # use ascii::AsciiChar;
323 /// const BAD: AsciiChar = AsciiChar::new('Ø');
324 /// ```
325 ///
326 /// # Panics
327 ///
328 /// This function will panic if passed a non-ASCII character.
329 ///
330 /// The panic message might not be the most descriptive due to the
331 /// current limitations of `const fn`.
332 #[must_use]
333 pub const fn new(ch: char) -> AsciiChar {
334 // It's restricted to this function, and without it
335 // we'd need to specify `AsciiChar::` or `Self::` 128 times.
336 #[allow(clippy::enum_glob_use)]
337 use AsciiChar::*;
338
339 #[rustfmt::skip]
340 const ALL: [AsciiChar; 128] = [
341 Null, SOH, SOX, ETX, EOT, ENQ, ACK, Bell,
342 BackSpace, Tab, LineFeed, VT, FF, CarriageReturn, SI, SO,
343 DLE, DC1, DC2, DC3, DC4, NAK, SYN, ETB,
344 CAN, EM, SUB, ESC, FS, GS, RS, US,
345 Space, Exclamation, Quotation, Hash, Dollar, Percent, Ampersand, Apostrophe,
346 ParenOpen, ParenClose, Asterisk, Plus, Comma, Minus, Dot, Slash,
347 _0, _1, _2, _3, _4, _5, _6, _7,
348 _8, _9, Colon, Semicolon, LessThan, Equal, GreaterThan, Question,
349 At, A, B, C, D, E, F, G,
350 H, I, J, K, L, M, N, O,
351 P, Q, R, S, T, U, V, W,
352 X, Y, Z, BracketOpen, BackSlash, BracketClose, Caret, UnderScore,
353 Grave, a, b, c, d, e, f, g,
354 h, i, j, k, l, m, n, o,
355 p, q, r, s, t, u, v, w,
356 x, y, z, CurlyBraceOpen, VerticalBar, CurlyBraceClose, Tilde, DEL,
357 ];
358
359 // We want to slice here and detect `const_err` from rustc if the slice is invalid
360 #[allow(clippy::indexing_slicing)]
361 ALL[ch as usize]
362 }
363
364 /// Constructs an ASCII character from a `u8`, `char` or other character
365 /// type without any checks.
366 ///
367 /// # Safety
368 ///
369 /// This function is very unsafe as it can create invalid enum
370 /// discriminants, which instantly creates undefined behavior.
371 /// (`let _ = AsciiChar::from_ascii_unchecked(200);` alone is UB).
372 ///
373 /// The undefined behavior is not just theoretical either:
374 /// For example, `[0; 128][AsciiChar::from_ascii_unchecked(255) as u8 as usize] = 0`
375 /// might not panic, creating a buffer overflow,
376 /// and `Some(AsciiChar::from_ascii_unchecked(128))` might be `None`.
377 #[inline]
378 #[must_use]
379 pub unsafe fn from_ascii_unchecked(ch: u8) -> Self {
380 // SAFETY: Caller guarantees `ch` is within bounds of ascii.
381 unsafe { ch.to_ascii_char_unchecked() }
382 }
383
384 /// Converts an ASCII character into a `u8`.
385 #[inline]
386 #[must_use]
387 pub const fn as_byte(self) -> u8 {
388 self as u8
389 }
390
391 /// Converts an ASCII character into a `char`.
392 #[inline]
393 #[must_use]
394 pub const fn as_char(self) -> char {
395 self as u8 as char
396 }
397
398 // the following methods are like ctype, and the implementation is inspired by musl.
399 // The ascii_ methods take self by reference for maximum compatibility
400 // with the corresponding methods on u8 and char.
401 // It is bad for both usability and performance, but marking those
402 // that doesn't have a non-ascii sibling #[inline] should
403 // make the compiler optimize away the indirection.
404
405 /// Turns uppercase into lowercase, but also modifies '@' and '<'..='_'
406 #[must_use]
407 const fn to_not_upper(self) -> u8 {
408 self as u8 | 0b010_0000
409 }
410
411 /// Check if the character is a letter (a-z, A-Z)
412 #[inline]
413 #[must_use]
414 pub const fn is_alphabetic(self) -> bool {
415 (self.to_not_upper() >= b'a') & (self.to_not_upper() <= b'z')
416 }
417
418 /// Check if the character is a letter (a-z, A-Z).
419 ///
420 /// This method is identical to [`is_alphabetic()`](#method.is_alphabetic)
421 #[inline]
422 #[must_use]
423 pub const fn is_ascii_alphabetic(&self) -> bool {
424 self.is_alphabetic()
425 }
426
427 /// Check if the character is a digit in the given radix.
428 ///
429 /// If the radix is always 10 or 16,
430 /// [`is_ascii_digit()`](#method.is_ascii_digit) and
431 /// [`is_ascii_hexdigit()`](#method.is_ascii_hexdigit()) will be faster.
432 ///
433 /// # Panics
434 ///
435 /// Radixes greater than 36 are not supported and will result in a panic.
436 #[must_use]
437 pub fn is_digit(self, radix: u32) -> bool {
438 match (self as u8, radix) {
439 (b'0'..=b'9', 0..=36) => u32::from(self as u8 - b'0') < radix,
440 (b'a'..=b'z', 11..=36) => u32::from(self as u8 - b'a') < radix - 10,
441 (b'A'..=b'Z', 11..=36) => u32::from(self as u8 - b'A') < radix - 10,
442 (_, 0..=36) => false,
443 (_, _) => panic!("radixes greater than 36 are not supported"),
444 }
445 }
446
447 /// Check if the character is a number (0-9)
448 ///
449 /// # Examples
450 /// ```
451 /// # use ascii::AsciiChar;
452 /// assert_eq!(AsciiChar::new('0').is_ascii_digit(), true);
453 /// assert_eq!(AsciiChar::new('9').is_ascii_digit(), true);
454 /// assert_eq!(AsciiChar::new('a').is_ascii_digit(), false);
455 /// assert_eq!(AsciiChar::new('A').is_ascii_digit(), false);
456 /// assert_eq!(AsciiChar::new('/').is_ascii_digit(), false);
457 /// ```
458 #[inline]
459 #[must_use]
460 pub const fn is_ascii_digit(&self) -> bool {
461 (*self as u8 >= b'0') & (*self as u8 <= b'9')
462 }
463
464 /// Check if the character is a letter or number
465 #[inline]
466 #[must_use]
467 pub const fn is_alphanumeric(self) -> bool {
468 self.is_alphabetic() | self.is_ascii_digit()
469 }
470
471 /// Check if the character is a letter or number
472 ///
473 /// This method is identical to [`is_alphanumeric()`](#method.is_alphanumeric)
474 #[inline]
475 #[must_use]
476 pub const fn is_ascii_alphanumeric(&self) -> bool {
477 self.is_alphanumeric()
478 }
479
480 /// Check if the character is a space or horizontal tab
481 ///
482 /// # Examples
483 /// ```
484 /// # use ascii::AsciiChar;
485 /// assert!(AsciiChar::Space.is_ascii_blank());
486 /// assert!(AsciiChar::Tab.is_ascii_blank());
487 /// assert!(!AsciiChar::VT.is_ascii_blank());
488 /// assert!(!AsciiChar::LineFeed.is_ascii_blank());
489 /// assert!(!AsciiChar::CarriageReturn.is_ascii_blank());
490 /// assert!(!AsciiChar::FF.is_ascii_blank());
491 /// ```
492 #[inline]
493 #[must_use]
494 pub const fn is_ascii_blank(&self) -> bool {
495 (*self as u8 == b' ') | (*self as u8 == b'\t')
496 }
497
498 /// Check if the character one of ' ', '\t', '\n', '\r',
499 /// '\0xb' (vertical tab) or '\0xc' (form feed).
500 #[inline]
501 #[must_use]
502 pub const fn is_whitespace(self) -> bool {
503 let b = self as u8;
504 self.is_ascii_blank() | (b == b'\n') | (b == b'\r') | (b == 0x0b) | (b == 0x0c)
505 }
506
507 /// Check if the character is a ' ', '\t', '\n', '\r' or '\0xc' (form feed).
508 ///
509 /// This method is NOT identical to `is_whitespace()`.
510 #[inline]
511 #[must_use]
512 pub const fn is_ascii_whitespace(&self) -> bool {
513 self.is_ascii_blank()
514 | (*self as u8 == b'\n')
515 | (*self as u8 == b'\r')
516 | (*self as u8 == 0x0c/*form feed*/)
517 }
518
519 /// Check if the character is a control character
520 ///
521 /// # Examples
522 /// ```
523 /// # use ascii::AsciiChar;
524 /// assert_eq!(AsciiChar::new('\0').is_ascii_control(), true);
525 /// assert_eq!(AsciiChar::new('n').is_ascii_control(), false);
526 /// assert_eq!(AsciiChar::new(' ').is_ascii_control(), false);
527 /// assert_eq!(AsciiChar::new('\n').is_ascii_control(), true);
528 /// assert_eq!(AsciiChar::new('\t').is_ascii_control(), true);
529 /// assert_eq!(AsciiChar::EOT.is_ascii_control(), true);
530 /// ```
531 #[inline]
532 #[must_use]
533 pub const fn is_ascii_control(&self) -> bool {
534 ((*self as u8) < b' ') | (*self as u8 == 127)
535 }
536
537 /// Checks if the character is printable (except space)
538 ///
539 /// # Examples
540 /// ```
541 /// # use ascii::AsciiChar;
542 /// assert_eq!(AsciiChar::new('n').is_ascii_graphic(), true);
543 /// assert_eq!(AsciiChar::new(' ').is_ascii_graphic(), false);
544 /// assert_eq!(AsciiChar::new('\n').is_ascii_graphic(), false);
545 /// ```
546 #[inline]
547 #[must_use]
548 pub const fn is_ascii_graphic(&self) -> bool {
549 self.as_byte().wrapping_sub(b' ' + 1) < 0x5E
550 }
551
552 /// Checks if the character is printable (including space)
553 ///
554 /// # Examples
555 /// ```
556 /// # use ascii::AsciiChar;
557 /// assert_eq!(AsciiChar::new('n').is_ascii_printable(), true);
558 /// assert_eq!(AsciiChar::new(' ').is_ascii_printable(), true);
559 /// assert_eq!(AsciiChar::new('\n').is_ascii_printable(), false);
560 /// ```
561 #[inline]
562 #[must_use]
563 pub const fn is_ascii_printable(&self) -> bool {
564 self.as_byte().wrapping_sub(b' ') < 0x5F
565 }
566
567 /// Checks if the character is alphabetic and lowercase (a-z).
568 ///
569 /// # Examples
570 /// ```
571 /// use ascii::AsciiChar;
572 /// assert_eq!(AsciiChar::new('a').is_lowercase(), true);
573 /// assert_eq!(AsciiChar::new('A').is_lowercase(), false);
574 /// assert_eq!(AsciiChar::new('@').is_lowercase(), false);
575 /// ```
576 #[inline]
577 #[must_use]
578 pub const fn is_lowercase(self) -> bool {
579 self.as_byte().wrapping_sub(b'a') < 26
580 }
581
582 /// Checks if the character is alphabetic and lowercase (a-z).
583 ///
584 /// This method is identical to [`is_lowercase()`](#method.is_lowercase)
585 #[inline]
586 #[must_use]
587 pub const fn is_ascii_lowercase(&self) -> bool {
588 self.is_lowercase()
589 }
590
591 /// Checks if the character is alphabetic and uppercase (A-Z).
592 ///
593 /// # Examples
594 /// ```
595 /// # use ascii::AsciiChar;
596 /// assert_eq!(AsciiChar::new('A').is_uppercase(), true);
597 /// assert_eq!(AsciiChar::new('a').is_uppercase(), false);
598 /// assert_eq!(AsciiChar::new('@').is_uppercase(), false);
599 /// ```
600 #[inline]
601 #[must_use]
602 pub const fn is_uppercase(self) -> bool {
603 self.as_byte().wrapping_sub(b'A') < 26
604 }
605
606 /// Checks if the character is alphabetic and uppercase (A-Z).
607 ///
608 /// This method is identical to [`is_uppercase()`](#method.is_uppercase)
609 #[inline]
610 #[must_use]
611 pub const fn is_ascii_uppercase(&self) -> bool {
612 self.is_uppercase()
613 }
614
615 /// Checks if the character is punctuation
616 ///
617 /// # Examples
618 /// ```
619 /// # use ascii::AsciiChar;
620 /// assert_eq!(AsciiChar::new('n').is_ascii_punctuation(), false);
621 /// assert_eq!(AsciiChar::new(' ').is_ascii_punctuation(), false);
622 /// assert_eq!(AsciiChar::new('_').is_ascii_punctuation(), true);
623 /// assert_eq!(AsciiChar::new('~').is_ascii_punctuation(), true);
624 /// ```
625 #[inline]
626 #[must_use]
627 pub const fn is_ascii_punctuation(&self) -> bool {
628 self.is_ascii_graphic() & !self.is_alphanumeric()
629 }
630
631 /// Checks if the character is a valid hex digit
632 ///
633 /// # Examples
634 /// ```
635 /// # use ascii::AsciiChar;
636 /// assert_eq!(AsciiChar::new('5').is_ascii_hexdigit(), true);
637 /// assert_eq!(AsciiChar::new('a').is_ascii_hexdigit(), true);
638 /// assert_eq!(AsciiChar::new('F').is_ascii_hexdigit(), true);
639 /// assert_eq!(AsciiChar::new('G').is_ascii_hexdigit(), false);
640 /// assert_eq!(AsciiChar::new(' ').is_ascii_hexdigit(), false);
641 /// ```
642 #[inline]
643 #[must_use]
644 pub const fn is_ascii_hexdigit(&self) -> bool {
645 self.is_ascii_digit() | ((*self as u8 | 0x20_u8).wrapping_sub(b'a') < 6)
646 }
647
648 /// Unicode has printable versions of the ASCII control codes, like '␛'.
649 ///
650 /// This function is identical with `.as_char()`
651 /// for all values `.is_printable()` returns true for,
652 /// but replaces the control codes with those unicodes printable versions.
653 ///
654 /// # Examples
655 /// ```
656 /// # use ascii::AsciiChar;
657 /// assert_eq!(AsciiChar::new('\0').as_printable_char(), '␀');
658 /// assert_eq!(AsciiChar::new('\n').as_printable_char(), '␊');
659 /// assert_eq!(AsciiChar::new(' ').as_printable_char(), ' ');
660 /// assert_eq!(AsciiChar::new('p').as_printable_char(), 'p');
661 /// ```
662 #[must_use]
663 pub fn as_printable_char(self) -> char {
664 match self as u8 {
665 // Non printable characters
666 // SAFETY: From codepoint 0x2400 ('␀') to 0x241f (`␟`), there are characters representing
667 // the unprintable characters from 0x0 to 0x1f, ordered correctly.
668 // As `b` is guaranteed to be within 0x0 to 0x1f, the conversion represents a
669 // valid character.
670 b @ 0x0..=0x1f => unsafe { char::from_u32_unchecked(u32::from('␀') + u32::from(b)) },
671
672 // 0x7f (delete) has it's own character at codepoint 0x2420, not 0x247f, so it is special
673 // cased to return it's character
674 0x7f => '␡',
675
676 // All other characters are printable, and per function contract use `Self::as_char`
677 _ => self.as_char(),
678 }
679 }
680
681 /// Replaces letters `a` to `z` with `A` to `Z`
682 pub fn make_ascii_uppercase(&mut self) {
683 *self = self.to_ascii_uppercase();
684 }
685
686 /// Replaces letters `A` to `Z` with `a` to `z`
687 pub fn make_ascii_lowercase(&mut self) {
688 *self = self.to_ascii_lowercase();
689 }
690
691 /// Maps letters a-z to A-Z and returns any other character unchanged.
692 ///
693 /// # Examples
694 /// ```
695 /// # use ascii::AsciiChar;
696 /// assert_eq!(AsciiChar::new('u').to_ascii_uppercase().as_char(), 'U');
697 /// assert_eq!(AsciiChar::new('U').to_ascii_uppercase().as_char(), 'U');
698 /// assert_eq!(AsciiChar::new('2').to_ascii_uppercase().as_char(), '2');
699 /// assert_eq!(AsciiChar::new('=').to_ascii_uppercase().as_char(), '=');
700 /// assert_eq!(AsciiChar::new('[').to_ascii_uppercase().as_char(), '[');
701 /// ```
702 #[inline]
703 #[must_use]
704 #[allow(clippy::indexing_slicing)] // We're sure it'll either access one or the other, as `bool` is either `0` or `1`
705 pub const fn to_ascii_uppercase(&self) -> Self {
706 [*self, AsciiChar::new((*self as u8 & 0b101_1111) as char)][self.is_lowercase() as usize]
707 }
708
709 /// Maps letters A-Z to a-z and returns any other character unchanged.
710 ///
711 /// # Examples
712 /// ```
713 /// # use ascii::AsciiChar;
714 /// assert_eq!(AsciiChar::new('U').to_ascii_lowercase().as_char(), 'u');
715 /// assert_eq!(AsciiChar::new('u').to_ascii_lowercase().as_char(), 'u');
716 /// assert_eq!(AsciiChar::new('2').to_ascii_lowercase().as_char(), '2');
717 /// assert_eq!(AsciiChar::new('^').to_ascii_lowercase().as_char(), '^');
718 /// assert_eq!(AsciiChar::new('\x7f').to_ascii_lowercase().as_char(), '\x7f');
719 /// ```
720 #[inline]
721 #[must_use]
722 #[allow(clippy::indexing_slicing)] // We're sure it'll either access one or the other, as `bool` is either `0` or `1`
723 pub const fn to_ascii_lowercase(&self) -> Self {
724 [*self, AsciiChar::new(self.to_not_upper() as char)][self.is_uppercase() as usize]
725 }
726
727 /// Compares two characters case-insensitively.
728 #[inline]
729 #[must_use]
730 pub const fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
731 (self.as_byte() == other.as_byte())
732 | (self.is_alphabetic() & (self.to_not_upper() == other.to_not_upper()))
733 }
734 }
735
736 impl fmt::Display for AsciiChar {
737 #[inline]
738 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
739 self.as_char().fmt(f)
740 }
741 }
742
743 impl fmt::Debug for AsciiChar {
744 #[inline]
745 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
746 self.as_char().fmt(f)
747 }
748 }
749
750 impl Default for AsciiChar {
751 fn default() -> AsciiChar {
752 AsciiChar::Null
753 }
754 }
755
756 macro_rules! impl_into_partial_eq_ord {
757 ($wider:ty, $to_wider:expr) => {
758 impl From<AsciiChar> for $wider {
759 #[inline]
760 fn from(ch: AsciiChar) -> $wider {
761 $to_wider(ch)
762 }
763 }
764 impl PartialEq<$wider> for AsciiChar {
765 #[inline]
766 fn eq(&self, rhs: &$wider) -> bool {
767 $to_wider(*self) == *rhs
768 }
769 }
770 impl PartialEq<AsciiChar> for $wider {
771 #[inline]
772 fn eq(&self, rhs: &AsciiChar) -> bool {
773 *self == $to_wider(*rhs)
774 }
775 }
776 impl PartialOrd<$wider> for AsciiChar {
777 #[inline]
778 fn partial_cmp(&self, rhs: &$wider) -> Option<Ordering> {
779 $to_wider(*self).partial_cmp(rhs)
780 }
781 }
782 impl PartialOrd<AsciiChar> for $wider {
783 #[inline]
784 fn partial_cmp(&self, rhs: &AsciiChar) -> Option<Ordering> {
785 self.partial_cmp(&$to_wider(*rhs))
786 }
787 }
788 };
789 }
790 impl_into_partial_eq_ord! {u8, AsciiChar::as_byte}
791 impl_into_partial_eq_ord! {char, AsciiChar::as_char}
792
793 /// Error returned by `ToAsciiChar`.
794 #[derive(Clone, Copy, PartialEq, Eq)]
795 pub struct ToAsciiCharError(());
796
•797 const ERRORMSG_CHAR: &str = "not an ASCII character";
798
799 #[cfg(not(feature = "std"))]
800 impl ToAsciiCharError {
801 /// Returns a description for this error, like `std::error::Error::description`.
802 #[inline]
803 #[must_use]
804 #[allow(clippy::unused_self)]
805 pub const fn description(&self) -> &'static str {
806 ERRORMSG_CHAR
807 }
808 }
809
810 impl fmt::Debug for ToAsciiCharError {
811 fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
812 write!(fmtr, "{}", ERRORMSG_CHAR)
813 }
814 }
815
816 impl fmt::Display for ToAsciiCharError {
817 fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
818 write!(fmtr, "{}", ERRORMSG_CHAR)
819 }
820 }
821
822 #[cfg(feature = "std")]
823 impl Error for ToAsciiCharError {
824 #[inline]
825 fn description(&self) -> &'static str {
826 ERRORMSG_CHAR
827 }
828 }
829
830 /// Convert `char`, `u8` and other character types to `AsciiChar`.
831 pub trait ToAsciiChar {
832 /// Convert to `AsciiChar`.
833 ///
834 /// # Errors
835 /// If `self` is outside the valid ascii range, this returns `Err`
836 fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError>;
837
838 /// Convert to `AsciiChar` without checking that it is an ASCII character.
839 ///
840 /// # Safety
841 /// Calling this function with a value outside of the ascii range, `0x0` to `0x7f` inclusive,
842 /// is undefined behavior.
843 // TODO: Make sure this is the contract we want to express in this function.
844 // It is ambigous if numbers such as `0xffffff20_u32` are valid ascii characters,
845 // as this function returns `Ascii::Space` due to the cast to `u8`, even though
846 // `to_ascii_char` returns `Err()`.
847 unsafe fn to_ascii_char_unchecked(self) -> AsciiChar;
848 }
849
850 impl ToAsciiChar for AsciiChar {
851 #[inline]
852 fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
853 Ok(self)
854 }
855
856 #[inline]
857 unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
858 self
859 }
860 }
861
862 impl ToAsciiChar for u8 {
863 #[inline]
864 fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
865 u32::from(self).to_ascii_char()
866 }
867 #[inline]
868 unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
869 // SAFETY: Caller guarantees `self` is within bounds of the enum
870 // variants, so this cast successfully produces a valid ascii
871 // variant
872 unsafe { mem::transmute::<u8, AsciiChar>(self) }
873 }
874 }
875
876 // Note: Casts to `u8` here does not cause problems, as the negative
877 // range is mapped outside of ascii bounds and we don't mind losing
878 // the sign, as long as negative numbers are mapped outside ascii range.
879 #[allow(clippy::cast_sign_loss)]
880 impl ToAsciiChar for i8 {
881 #[inline]
882 fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
883 u32::from(self as u8).to_ascii_char()
884 }
885 #[inline]
886 unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
887 // SAFETY: Caller guarantees `self` is within bounds of the enum
888 // variants, so this cast successfully produces a valid ascii
889 // variant
890 unsafe { mem::transmute::<u8, AsciiChar>(self as u8) }
891 }
892 }
893
894 impl ToAsciiChar for char {
895 #[inline]
896 fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
897 u32::from(self).to_ascii_char()
898 }
899 #[inline]
900 unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
901 // SAFETY: Caller guarantees we're within ascii range.
902 unsafe { u32::from(self).to_ascii_char_unchecked() }
903 }
904 }
905
906 impl ToAsciiChar for u32 {
907 fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
908 match self {
909 // SAFETY: We're within the valid ascii range in this branch.
910 0x0..=0x7f => Ok(unsafe { self.to_ascii_char_unchecked() }),
911 _ => Err(ToAsciiCharError(())),
912 }
913 }
914
915 #[inline]
916 unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
917 // Note: This cast discards the top bytes, this may cause problems, see
918 // the TODO on this method's documentation in the trait.
919 // SAFETY: Caller guarantees we're within ascii range.
920 #[allow(clippy::cast_possible_truncation)] // We want to truncate it
921 unsafe {
922 (self as u8).to_ascii_char_unchecked()
923 }
924 }
925 }
926
927 impl ToAsciiChar for u16 {
928 fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
929 u32::from(self).to_ascii_char()
930 }
931 #[inline]
932 unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
933 // Note: This cast discards the top bytes, this may cause problems, see
934 // the TODO on this method's documentation in the trait.
935 // SAFETY: Caller guarantees we're within ascii range.
936 #[allow(clippy::cast_possible_truncation)] // We want to truncate it
937 unsafe {
938 (self as u8).to_ascii_char_unchecked()
939 }
940 }
941 }
942
943 #[cfg(test)]
944 mod tests {
945 use super::{AsciiChar, ToAsciiChar, ToAsciiCharError};
946
947 #[test]
948 fn to_ascii_char() {
949 fn generic<C: ToAsciiChar>(ch: C) -> Result<AsciiChar, ToAsciiCharError> {
950 ch.to_ascii_char()
951 }
952 assert_eq!(generic(AsciiChar::A), Ok(AsciiChar::A));
953 assert_eq!(generic(b'A'), Ok(AsciiChar::A));
954 assert_eq!(generic('A'), Ok(AsciiChar::A));
955 assert!(generic(200_u16).is_err());
956 assert!(generic('λ').is_err());
957 }
958
959 #[test]
960 fn as_byte_and_char() {
961 assert_eq!(AsciiChar::A.as_byte(), b'A');
962 assert_eq!(AsciiChar::A.as_char(), 'A');
963 }
964
965 #[test]
966 fn new_array_is_correct() {
967 for byte in 0..128_u8 {
968 assert_eq!(AsciiChar::new(byte as char).as_byte(), byte);
969 }
970 }
971
972 #[test]
973 fn is_all() {
974 #![allow(clippy::is_digit_ascii_radix)] // testing it
975 for byte in 0..128_u8 {
976 let ch = byte as char;
977 let ascii = AsciiChar::new(ch);
978 assert_eq!(ascii.is_alphabetic(), ch.is_alphabetic());
979 assert_eq!(ascii.is_ascii_alphabetic(), ch.is_ascii_alphabetic());
980 assert_eq!(ascii.is_alphanumeric(), ch.is_alphanumeric());
981 assert_eq!(ascii.is_ascii_alphanumeric(), ch.is_ascii_alphanumeric());
982 assert_eq!(ascii.is_digit(8), ch.is_digit(8), "is_digit(8) {:?}", ch);
983 assert_eq!(ascii.is_digit(10), ch.is_digit(10), "is_digit(10) {:?}", ch);
984 assert_eq!(ascii.is_digit(16), ch.is_digit(16), "is_digit(16) {:?}", ch);
985 assert_eq!(ascii.is_digit(36), ch.is_digit(36), "is_digit(36) {:?}", ch);
986 assert_eq!(ascii.is_ascii_digit(), ch.is_ascii_digit());
987 assert_eq!(ascii.is_ascii_hexdigit(), ch.is_ascii_hexdigit());
988 assert_eq!(ascii.is_ascii_control(), ch.is_ascii_control());
989 assert_eq!(ascii.is_ascii_graphic(), ch.is_ascii_graphic());
990 assert_eq!(ascii.is_ascii_punctuation(), ch.is_ascii_punctuation());
991 assert_eq!(
992 ascii.is_whitespace(),
993 ch.is_whitespace(),
994 "{:?} ({:#04x})",
995 ch,
996 byte
997 );
998 assert_eq!(
999 ascii.is_ascii_whitespace(),
1000 ch.is_ascii_whitespace(),
1001 "{:?} ({:#04x})",
1002 ch,
1003 byte
1004 );
1005 assert_eq!(ascii.is_uppercase(), ch.is_uppercase());
1006 assert_eq!(ascii.is_ascii_uppercase(), ch.is_ascii_uppercase());
1007 assert_eq!(ascii.is_lowercase(), ch.is_lowercase());
1008 assert_eq!(ascii.is_ascii_lowercase(), ch.is_ascii_lowercase());
1009 assert_eq!(ascii.to_ascii_uppercase(), ch.to_ascii_uppercase());
1010 assert_eq!(ascii.to_ascii_lowercase(), ch.to_ascii_lowercase());
1011 }
1012 }
1013
1014 #[test]
1015 fn is_digit_strange_radixes() {
•1016 //assert_eq!(AsciiChar::_0.is_digit(0), '0'.is_digit(0));
1017 //assert_eq!(AsciiChar::_0.is_digit(1), '0'.is_digit(1));
1018 assert_eq!(AsciiChar::_5.is_digit(5), '5'.is_digit(5));
1019 assert_eq!(AsciiChar::z.is_digit(35), 'z'.is_digit(35));
1020 }
1021
1022 #[test]
1023 #[should_panic]
1024 fn is_digit_bad_radix() {
1025 let _ = AsciiChar::_7.is_digit(37);
1026 }
1027
1028 #[test]
1029 fn cmp_wider() {
1030 assert_eq!(AsciiChar::A, 'A');
1031 assert_eq!(b'b', AsciiChar::b);
1032 assert!(AsciiChar::a < 'z');
1033 }
1034
1035 #[test]
1036 fn ascii_case() {
1037 assert_eq!(AsciiChar::At.to_ascii_lowercase(), AsciiChar::At);
1038 assert_eq!(AsciiChar::At.to_ascii_uppercase(), AsciiChar::At);
1039 assert_eq!(AsciiChar::A.to_ascii_lowercase(), AsciiChar::a);
1040 assert_eq!(AsciiChar::A.to_ascii_uppercase(), AsciiChar::A);
1041 assert_eq!(AsciiChar::a.to_ascii_lowercase(), AsciiChar::a);
1042 assert_eq!(AsciiChar::a.to_ascii_uppercase(), AsciiChar::A);
1043
1044 let mut mutable = (AsciiChar::A, AsciiChar::a);
1045 mutable.0.make_ascii_lowercase();
1046 mutable.1.make_ascii_uppercase();
1047 assert_eq!(mutable.0, AsciiChar::a);
1048 assert_eq!(mutable.1, AsciiChar::A);
1049
1050 assert!(AsciiChar::LineFeed.eq_ignore_ascii_case(&AsciiChar::LineFeed));
1051 assert!(!AsciiChar::LineFeed.eq_ignore_ascii_case(&AsciiChar::CarriageReturn));
1052 assert!(AsciiChar::z.eq_ignore_ascii_case(&AsciiChar::Z));
1053 assert!(AsciiChar::Z.eq_ignore_ascii_case(&AsciiChar::z));
1054 assert!(AsciiChar::A.eq_ignore_ascii_case(&AsciiChar::a));
1055 assert!(!AsciiChar::K.eq_ignore_ascii_case(&AsciiChar::C));
1056 assert!(!AsciiChar::Z.eq_ignore_ascii_case(&AsciiChar::DEL));
1057 assert!(!AsciiChar::BracketOpen.eq_ignore_ascii_case(&AsciiChar::CurlyBraceOpen));
1058 assert!(!AsciiChar::Grave.eq_ignore_ascii_case(&AsciiChar::At));
1059 assert!(!AsciiChar::Grave.eq_ignore_ascii_case(&AsciiChar::DEL));
1060 }
1061
1062 #[test]
1063 #[cfg(feature = "std")]
1064 fn fmt_ascii() {
1065 assert_eq!(format!("{}", AsciiChar::t), "t");
1066 assert_eq!(format!("{:?}", AsciiChar::t), "'t'");
1067 assert_eq!(format!("{}", AsciiChar::LineFeed), "\n");
1068 assert_eq!(format!("{:?}", AsciiChar::LineFeed), "'\\n'");
1069 }
1070 }