refactor: create mod parse_prefixed_u32

This commit is contained in:
Wataru Otsubo 2025-01-29 21:46:41 +09:00
parent 1b93197ef6
commit 371068e363

View file

@ -1,47 +1,52 @@
//! Module for converting XML custom token string to rust types.
use std::num;
pub(crate) use parse_prefixed_u32::ParsePrefixedU32;
pub use parse_prefixed_u32::ParsePrefixedU32Error;
use thiserror::Error;
mod parse_prefixed_u32 {
use std::num;
#[derive(Debug, Error)]
pub enum ParsePrefixedU32Error {
#[error("invalid prefix: found {found}")]
InvalidPrefix { found: char },
#[error("parse int error")]
ParseIntError(#[from] num::ParseIntError),
}
use thiserror::Error;
pub(crate) trait ParsePrefixedU32 {
fn parse_prefixed_u32(&self) -> Result<u32, ParsePrefixedU32Error>;
}
#[derive(Debug, Error)]
pub enum ParsePrefixedU32Error {
#[error("invalid prefix: found {found}")]
InvalidPrefix { found: char },
#[error("parse int error")]
ParseIntError(#[from] num::ParseIntError),
}
impl ParsePrefixedU32 for &str {
fn parse_prefixed_u32(&self) -> Result<u32, ParsePrefixedU32Error> {
let radix = match self.chars().nth(1) {
Some('x') => 16,
Some(c) if c.is_numeric() => 10,
Some(c) => return Err(ParsePrefixedU32Error::InvalidPrefix { found: c }),
None => return Err(ParsePrefixedU32Error::InvalidPrefix { found: ' ' }),
};
pub(crate) trait ParsePrefixedU32 {
fn parse_prefixed_u32(&self) -> Result<u32, ParsePrefixedU32Error>;
}
match radix {
10 => Ok(self.parse()?),
radix => Ok(u32::from_str_radix(&self[2..], radix)?),
impl ParsePrefixedU32 for &str {
fn parse_prefixed_u32(&self) -> Result<u32, ParsePrefixedU32Error> {
let radix = match self.chars().nth(1) {
Some('x') => 16,
Some(c) if c.is_numeric() => 10,
Some(c) => return Err(ParsePrefixedU32Error::InvalidPrefix { found: c }),
None => return Err(ParsePrefixedU32Error::InvalidPrefix { found: ' ' }),
};
match radix {
10 => Ok(self.parse()?),
radix => Ok(u32::from_str_radix(&self[2..], radix)?),
}
}
}
#[cfg(test)]
mod test {
use super::ParsePrefixedU32;
#[test]
fn parse_prefixed_u32() {
assert_eq!("0xdeadbeef".parse_prefixed_u32().unwrap(), 0xdeadbeef);
assert_eq!("0xDEADBEEF".parse_prefixed_u32().unwrap(), 0xdeadbeef);
assert_eq!("1234".parse_prefixed_u32().unwrap(), 1234);
assert!("0abcde".parse_prefixed_u32().is_err());
}
}
}
#[cfg(test)]
mod test {
use super::ParsePrefixedU32;
#[test]
fn parse_prefixed_u32() {
assert_eq!("0xdeadbeef".parse_prefixed_u32().unwrap(), 0xdeadbeef);
assert_eq!("0xDEADBEEF".parse_prefixed_u32().unwrap(), 0xdeadbeef);
assert_eq!("1234".parse_prefixed_u32().unwrap(), 1234);
assert!("0abcde".parse_prefixed_u32().is_err());
}
}