token-parser 0.3.0

Utilities for parsing texts into data structures
Documentation
use crate::{Context, Error, Result};
use num_traits::Num;

/// A parse context to parse using the specified radix.
pub struct RadixContext(u32);

impl Context for RadixContext {
    #[inline]
    fn radix(&self) -> u32 {
        self.0
    }
}

/// A parse context to parse using the specialized const radix.
pub struct ConstRadixContext<const I: u32>;

impl<const I: u32> Context for ConstRadixContext<I> {
    #[inline]
    fn radix(&self) -> u32 {
        I
    }
}

/// Parses number using the specified radix and returns it as an appropriate parsing result.
/// Mainly used implicitly when deriving radix parsable.
pub fn parse_radix<N: Num>(name: &str, radix: u32) -> Result<N> {
    if let Ok(result) = N::from_str_radix(name, radix) {
        Ok(result)
    } else {
        Err(Error::StringParsing)
    }
}

#[macro_export]
/// Derives `Parsable` from symbol for types which implement `Num` using hexadecimal parsing.
macro_rules! derive_radix_parsable {
    ($t:ty) => {
        impl<C: $crate::Context> $crate::Parsable<C> for $t {
            fn parse_symbol(name: String, context: &C) -> $crate::Result<Self> {
                $crate::radix::parse_radix(name.as_ref(), context.radix())
            }
        }
    };
    ($t:ty, $($rest:ty),+) => {
        derive_radix_parsable!($t);
        derive_radix_parsable!($($rest),+);
    };
}

derive_radix_parsable!(i8, i16, i32, i64, i128);
derive_radix_parsable!(u8, u16, u32, u64, u128);
derive_radix_parsable!(f32, f64);
derive_radix_parsable!(usize);