Skip to content

Commit a762eb2

Browse files
committed
Introduce AsciiChar::from_digit constructor
Somewhat mimicking char::from_digit, introduce AsciiChar::from_digit method which returns an ASCII digit character corresponding to given digit.
1 parent 888dfce commit a762eb2

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

Diff for: src/ascii_char.rs

+38-2
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,42 @@ impl AsciiChar {
371371
ALL[ch as usize]
372372
}
373373

374+
/// Converts a digit in base 36 to an `AsciiChar`.
375+
///
376+
/// This is ASCII version of `char::from_digit(digit, 36)` call.
377+
///
378+
/// `from_digit()` will return `None` if the input is greater or equal 36.
379+
///
380+
/// # Examples
381+
///
382+
/// ```
383+
/// # use ascii::AsciiChar;
384+
/// assert_eq!(AsciiChar::from_digit(5), Some(AsciiChar::_5));
385+
/// assert_eq!(AsciiChar::from_digit(15), Some(AsciiChar::f));
386+
/// assert_eq!(AsciiChar::from_digit(25), Some(AsciiChar::p));
387+
/// assert_eq!(AsciiChar::from_digit(37), None);
388+
/// ```
389+
#[inline]
390+
#[must_use]
391+
pub const fn from_digit(digit: u32) -> Option<Self> {
392+
// This `use` is restricted to this function, and without it we'd need
393+
// to specify `AsciiChar::` or `Self::` 36 times.
394+
#[allow(clippy::enum_glob_use)]
395+
use AsciiChar::*;
396+
397+
#[rustfmt::skip]
398+
const ALL: [AsciiChar; 36] = [
399+
_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, a, b, c, d, e, f,
400+
g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z,
401+
];
402+
403+
if digit < 36 {
404+
Some(ALL[digit as usize])
405+
} else {
406+
None
407+
}
408+
}
409+
374410
/// Create an `AsciiChar` from a `char`, in a `const fn` way.
375411
///
376412
/// Within non-`const fn` functions the more general
@@ -794,8 +830,8 @@ macro_rules! impl_into_partial_eq_ord {
794830
($wider:ty, $to_wider:expr) => {
795831
impl From<AsciiChar> for $wider {
796832
#[inline]
797-
fn from(a: AsciiChar) -> $wider {
798-
$to_wider(a)
833+
fn from(ch: AsciiChar) -> $wider {
834+
$to_wider(ch)
799835
}
800836
}
801837
impl PartialEq<$wider> for AsciiChar {

0 commit comments

Comments
 (0)