I want to write a macro to instantiate a big integer in a clean manner, and the first step is to read the integer literal correctly. The first version I have is
macro_rules! bigint {
($tt:tt) => {
println!("caught {}", ::core::stringify!($tt)); // for debug
// some logic to create a big integer from the string
};
}
and this macro can nicely handle very long literals like bigint!(100000000000000000000000000000000000000000000000000000000000000000000000)
.
One drawback of this approach is that it has to invocate the string parser even if the integer is small enough to fit in a native integer type (i.e. u128
), so then what I tried next is
macro_rules! bigint {
($val:literal) => {
println!("caught literal {}", $val);
let val: u128 = $val;
// some logic to create a big integer from val
};
($tt:tt) => {
println!("caught {}", ::core::stringify!($tt));
// some logic to create a big integer from the string
};
}
but this time bigint!(100000000000000000000000000000000000000000000000000000000000000000000000)
will cause an compilation error: error: integer literal is too large
. I'm wondering if the first matching arm failed, why wouldn't the second arm be tried?