is_digit/
lib.rs

1/// Checks if the specified character is an ASCII digit.
2///
3/// This method verifies whether the character's ASCII value falls within the range of '0' (ASCII value 48) to '9' (ASCII value 57).
4/// If so, it returns `true`, indicating that it is a digit. Otherwise, it returns `false`.
5///
6/// # Examples
7///
8/// ```
9/// use is_digit::IsDigit;
10///
11/// let digit = '1';
12/// assert!(digit.is_dec_digit());
13///
14/// let alpha = 'a';
15/// assert!(!alpha.is_dec_digit());
16/// ```
17/// 
18pub trait IsDigit {
19    fn is_dec_digit(&self) -> bool;
20}
21
22macro_rules! prim_impl {
23    ($($t:ty)*) => {
24        $(
25            impl IsDigit for $t {
26                fn is_dec_digit(&self) -> bool {
27                    *self >= '0' as $t && *self <= '9' as $t
28                }
29            }
30        )*
31    };
32}
33
34prim_impl!(char);
35
36macro_rules! adapt_impl {
37    ($($t:ty)*) => {
38        $(
39            impl IsDigit for $t {
40                fn is_dec_digit(&self) -> bool {
41                    self.as_char().unwrap().is_dec_digit()
42                }
43            }
44        )*
45    };
46}
47
48adapt_impl!(&str String);
49
50pub trait AsChar {
51    fn as_char(&self) -> Option<char>;
52}
53
54impl AsChar for &str {
55    fn as_char(&self) -> Option<char> {
56        if self.len() == 1 {
57            self.chars().next()
58        } else {
59            None
60        }
61    }
62}
63
64impl AsChar for String {
65    fn as_char(&self) -> Option<char> {
66        if self.len() == 1 {
67            self.chars().next()
68        } else {
69            None
70        }
71    }
72}