Skip to content

Commit

Permalink
multiprecision: update parsing code
Browse files Browse the repository at this point in the history
  • Loading branch information
ioxid committed Feb 27, 2025
1 parent 2a07934 commit 863d2ac
Showing 1 changed file with 10 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,14 @@ namespace nil::crypto3::multiprecision {
return (c - 'A') + 10;
}

constexpr bool has_hex_prefix(std::string_view str) {
return str.size() >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X');
}

template<std::size_t Bits>
constexpr big_uint<Bits> parse_int_hex(std::string_view str) {
if (str.size() < 2 || str[0] != '0' || str[1] != 'x') {
throw std::invalid_argument("hex literal should start with 0x");
if (!has_hex_prefix(str)) {
throw std::invalid_argument("hex number should start with 0x");
}

big_uint<Bits> result{0};
Expand All @@ -44,7 +48,7 @@ namespace nil::crypto3::multiprecision {
for (std::size_t i = 2; i < str.size(); ++i) {
char c = str[i];
if (!is_valid_hex_digit(c)) {
throw std::invalid_argument("non-hex character in literal");
throw std::invalid_argument("non-hex character in hex number");
}
result <<= 4;
if (bits != 0) {
Expand All @@ -57,7 +61,7 @@ namespace nil::crypto3::multiprecision {
}
}
if (bits > Bits) {
throw std::range_error("not enough bits to store literal");
throw std::range_error("not enough bits to store number");
}
return result;
}
Expand All @@ -69,7 +73,7 @@ namespace nil::crypto3::multiprecision {
for (std::size_t i = 0; i < str.size(); ++i) {
char c = str[i];
if (c < '0' || c > '9') {
throw std::invalid_argument("non decimal character in literal");
throw std::invalid_argument("non-decimal character in number");
}
result *= 10u;
result += static_cast<unsigned>(c - '0');
Expand All @@ -79,7 +83,7 @@ namespace nil::crypto3::multiprecision {

template<std::size_t Bits>
constexpr big_uint<Bits> parse_int(std::string_view str) {
if (str.size() >= 2 && str[0] == '0' && str[1] == 'x') {
if (has_hex_prefix(str)) {
return parse_int_hex<Bits>(str);
}
return parse_int_decimal<Bits>(str);
Expand Down

0 comments on commit 863d2ac

Please sign in to comment.