Skip to content

Commit b921776

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 b921776

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

src/ascii_char.rs

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,38 @@ 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+
ALL.get(digit as usize)
404+
}
405+
374406
/// Create an `AsciiChar` from a `char`, in a `const fn` way.
375407
///
376408
/// Within non-`const fn` functions the more general
@@ -794,8 +826,8 @@ macro_rules! impl_into_partial_eq_ord {
794826
($wider:ty, $to_wider:expr) => {
795827
impl From<AsciiChar> for $wider {
796828
#[inline]
797-
fn from(a: AsciiChar) -> $wider {
798-
$to_wider(a)
829+
fn from(ch: AsciiChar) -> $wider {
830+
$to_wider(ch)
799831
}
800832
}
801833
impl PartialEq<$wider> for AsciiChar {

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy