refactor(specctra-core/read): use macro to produce repetitive impl ReadDsn via FromStr

This commit is contained in:
Alain Emilia Anna Zscheile 2024-12-06 16:02:52 +01:00 committed by mikolaj
parent 5f4496ffce
commit e90449b75e
1 changed files with 19 additions and 46 deletions

View File

@ -89,55 +89,28 @@ impl<R: std::io::BufRead> ReadDsn<R> for bool {
} }
} }
impl<R: std::io::BufRead> ReadDsn<R> for i32 { /// `impl_ReadDsn_via_FromStr!((TYPE, TYPE-NAME); ...)`
fn read_dsn(tokenizer: &mut ListTokenizer<R>) -> Result<Self, ParseErrorContext> { macro_rules! impl_ReadDsn_via_FromStr {
tokenizer ($(($t:ty, $name:expr));* $(;)?) => {
.consume_token()? $( impl<R: std::io::BufRead> ReadDsn<R> for $t {
.expect_leaf()? fn read_dsn(tokenizer: &mut ListTokenizer<R>) -> Result<Self, ParseErrorContext> {
.parse() tokenizer
.map_err(|_| tokenizer.add_context(ParseError::Expected("i32"))) .consume_token()?
.expect_leaf()?
.parse()
.map_err(|_| tokenizer.add_context(ParseError::Expected($name)))
}
} )*
} }
} }
impl<R: std::io::BufRead> ReadDsn<R> for u32 { impl_ReadDsn_via_FromStr!(
fn read_dsn(tokenizer: &mut ListTokenizer<R>) -> Result<Self, ParseErrorContext> { (i32, "i32");
tokenizer (u32, "u32");
.consume_token()? (usize, "usize");
.expect_leaf()? (f32, "f32");
.parse() (f64, "f64");
.map_err(|_| tokenizer.add_context(ParseError::Expected("u32"))) );
}
}
impl<R: std::io::BufRead> ReadDsn<R> for usize {
fn read_dsn(tokenizer: &mut ListTokenizer<R>) -> Result<Self, ParseErrorContext> {
tokenizer
.consume_token()?
.expect_leaf()?
.parse()
.map_err(|_| tokenizer.add_context(ParseError::Expected("usize")))
}
}
impl<R: std::io::BufRead> ReadDsn<R> for f32 {
fn read_dsn(tokenizer: &mut ListTokenizer<R>) -> Result<Self, ParseErrorContext> {
tokenizer
.consume_token()?
.expect_leaf()?
.parse()
.map_err(|_| tokenizer.add_context(ParseError::Expected("f32")))
}
}
impl<R: std::io::BufRead> ReadDsn<R> for f64 {
fn read_dsn(tokenizer: &mut ListTokenizer<R>) -> Result<Self, ParseErrorContext> {
tokenizer
.consume_token()?
.expect_leaf()?
.parse()
.map_err(|_| tokenizer.add_context(ParseError::Expected("f64")))
}
}
pub struct ListTokenizer<R: std::io::BufRead> { pub struct ListTokenizer<R: std::io::BufRead> {
reader: R, reader: R,