Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
uint_128_t_adaptor.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <msgpack.hpp>
4
8
9namespace msgpack::adaptor {
10
11// Helper to convert uint128_t to decimal string
13{
14 if (v == 0) {
15 return "0";
16 }
17 std::string result;
18 while (v > 0) {
19 result = static_cast<char>('0' + static_cast<uint8_t>(v % 10)) + result;
20 v = v / 10;
21 }
22 return result;
23}
24
25// Pack function for uint128_t
26template <> struct pack<uint128_t> {
27 template <typename Stream> msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, uint128_t const& v) const
28 {
29 // If value fits in u64, pack as positive integer for efficiency
30 constexpr uint128_t max_u64 = static_cast<uint128_t>(UINT64_MAX);
31 if (v <= max_u64) {
32 o.pack_uint64(static_cast<uint64_t>(v));
33 } else {
34 // Convert to decimal string for larger values
35 std::string str = uint128_to_decimal_string(v);
36 o.pack_str(static_cast<uint32_t>(str.size()));
37 o.pack_str_body(str.c_str(), static_cast<uint32_t>(str.size()));
38 }
39 return o;
40 }
41};
42
43template <> struct convert<uint128_t> {
44 msgpack::object const& operator()(msgpack::object const& o, uint128_t& v) const
45 {
46 if (o.type == msgpack::type::POSITIVE_INTEGER) {
47 v = static_cast<uint128_t>(o.via.u64);
48 } else if (o.type == msgpack::type::STR) {
49 // When the bigint is too large to fit in a u64, msgpackr will serialize it as a digits string.
50 // Configured on the TS side with largeBigIntToString: true.
51 uint128_t result = 0;
52 // 2**128 is 39 digits long in base 10.
53 if (o.via.str.size > 39) {
54 throw_or_abort("uint128_t deserialization failed: string too long");
55 }
56
57 for (size_t i = 0; i < o.via.str.size; ++i) {
58 char c = o.via.str.ptr[i];
59 if (c < '0' || c > '9') {
60 throw_or_abort("uint128_t deserialization failed: Non-digit character in input");
61 }
62
63 result = result * 10 + (static_cast<uint128_t>(c - '0'));
64 }
65
66 v = result;
67 } else {
68 throw_or_abort("Invalid type for uint128_t deserialization");
69 }
70 return o;
71 }
72};
73
74} // namespace msgpack::adaptor
constexpr std::array< uint8_t, S > convert(const std::string_view &in)
std::string uint128_to_decimal_string(uint128_t v)
unsigned __int128 uint128_t
Definition serialize.hpp:44
msgpack::object const & operator()(msgpack::object const &o, uint128_t &v) const
msgpack::packer< Stream > & operator()(msgpack::packer< Stream > &o, uint128_t const &v) const
void throw_or_abort(std::string const &err)