72#ifndef SOFAB_STRICT_UTF8
73# define SOFAB_STRICT_UTF8 1
94 inline constexpr uint32_t
ID_MAX = 0x7fffffffu;
308 if constexpr (std::endian::native == std::endian::big)
309 w = ((w & 0x00000000000000FFull) << 56) | ((w & 0x000000000000FF00ull) << 40) |
310 ((w & 0x0000000000FF0000ull) << 24) | ((w & 0x00000000FF000000ull) << 8) |
311 ((w & 0x000000FF00000000ull) >> 8) | ((w & 0x0000FF0000000000ull) >> 24) |
312 ((w & 0x00FF000000000000ull) >> 40) | ((w & 0xFF00000000000000ull) >> 56);
313 std::memcpy(out, &w,
sizeof w);
325 constexpr uint64_t
spread7(uint64_t v)
noexcept
327 uint64_t w = v & 0x00FFFFFFFFFFFFFFull;
328 w = (w & 0x000000000FFFFFFFull) | ((w & 0x00FFFFFFF0000000ull) << 4);
339 w += 3u * (w & 0x0FFFC0000FFFC000ull);
340 w += (w & 0x3F803F803F803F80ull);
352 constexpr uint64_t
gather7(uint64_t w)
noexcept
354 w = (w & 0x007F007F007F007Full) | ((w & 0x7F007F007F007F00ull) >> 1);
355 w = (w & 0x00003FFF00003FFFull) | ((w & 0x3FFF00003FFF0000ull) >> 2);
356 w = (w & 0x000000000FFFFFFFull) | ((w & 0x0FFFFFFF00000000ull) >> 4);
373 template <std::
unsigned_
integral U>
376 if constexpr (std::endian::native == std::endian::little)
377 std::memcpy(out, &bits,
sizeof bits);
379 for (
size_t i = 0; i <
sizeof(U); ++i)
380 out[i] =
static_cast<uint8_t
>((bits >> (8 * i)) & 0xffu);
384 template <std::
unsigned_
integral U>
388 if constexpr (std::endian::native == std::endian::little)
389 std::memcpy(&bits, in,
sizeof bits);
393 for (
size_t i = 0; i <
sizeof(U); ++i)
394 bits |=
static_cast<U
>(in[i]) << (8 * i);
403 std::memcpy(&w, in,
sizeof w);
404 if constexpr (std::endian::native == std::endian::big)
405 w = ((w & 0x00000000000000FFull) << 56) | ((w & 0x000000000000FF00ull) << 40) |
406 ((w & 0x0000000000FF0000ull) << 24) | ((w & 0x00000000FF000000ull) << 8) |
407 ((w & 0x000000FF00000000ull) >> 8) | ((w & 0x0000FF0000000000ull) >> 24) |
408 ((w & 0x00FF000000000000ull) >> 40) | ((w & 0xFF00000000000000ull) >> 56);
423 return (
static_cast<uint64_t
>(v) << 1) ^
static_cast<uint64_t
>(v >> 63);
432 return static_cast<int64_t
>((u >> 1) ^ (~(u & 1) + 1));
450 template <
typename E,
bool = std::is_enum_v<E>>
453 template <
typename E>
454 struct WireInt<E, true> {
using type = std::underlying_type_t<E>; };
456 template <
typename E>
465 template <std::
floating_po
int F>
468 if constexpr (
sizeof(F) == 4)
return std::bit_cast<uint32_t>(v);
469 else return std::bit_cast<uint64_t>(v);
478 template <std::
floating_po
int F, std::
unsigned_
integral U>
481 return std::bit_cast<F>(bits);
510 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
511 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
512 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
513 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
514 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
515 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
516 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
517 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8,
518 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12,
519 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12,
520 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12,
521 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12,
522 12,36,12,12,12,12,12,12,12,12,12,12,
552 [[nodiscard]]
constexpr uint32_t
utf8Advance(uint32_t state,
const uint8_t *d,
555 for (
size_t i = 0; i < len; ++i)
560 [[nodiscard]]
constexpr bool utf8Valid(
const char *data,
size_t len)
noexcept
575 if (!std::is_constant_evaluated())
585 __builtin_memcpy(&w, data + i, 8);
586 if (w & 0x8080808080808080ULL)
break;
590 while (i < len &&
static_cast<unsigned char>(data[i]) < 0x80) ++i;
591 if (i >= len)
return true;
597 state =
utf8Dfa[256u + state +
utf8Dfa[
static_cast<unsigned char>(data[i])]];
598 if (state == 12)
return false;
600 }
while (state != 0 && i < len);
602 if (state != 0)
return false;
614 template <
typename D>
615 [[gnu::always_inline]]
constexpr void operator()(D &,
size_t)
const noexcept {}
640 template <
typename T>
643 if constexpr (
requires { T::capacity(); })
return static_cast<long>(T::capacity());
676 template <
typename D>
679 if constexpr (
requires { D::capacity(); })
return static_cast<size_t>(D::capacity());
680 else return d.size();
702 template <
typename D>
705 if constexpr (
requires { d.set_len(n); }) d.set_len(n);
706 else if constexpr (
requires { d.resize(n); }) {
if (d.size() != n) d.resize(n); }
722 [[nodiscard]]
constexpr bool utf8_valid(std::string_view bytes)
noexcept
759 inline std::size_t
utf8Prefix(std::string_view sv, std::size_t n)
noexcept
761 while (n > 0 && (
static_cast<unsigned char>(sv[n]) & 0xC0u) == 0x80u)
798 template <std::
size_t N>
801 std::array<char, N + 1> buf_{};
802 std::size_t len_ = 0;
819 assign(s ? std::string_view{s} : std::string_view{});
837 assign(std::string_view{s});
843 assign(s ? std::string_view{s} : std::string_view{});
857 assign(std::string_view{s});
877 for (std::size_t i = 0; i < len_; ++i)
899 len_ = n > N ? N : n;
904 char *
data() noexcept {
return buf_.data(); }
906 const char *
data() const noexcept {
return buf_.data(); }
908 const char *
c_str() const noexcept {
return buf_.data(); }
911 std::size_t
size() const noexcept {
return len_; }
913 std::size_t
length() const noexcept {
return len_; }
915 bool empty() const noexcept {
return len_ == 0; }
917 static constexpr std::size_t
capacity() noexcept {
return N; }
919 static constexpr std::size_t
max_size() noexcept {
return N; }
924 const char &
operator[](std::size_t i)
const noexcept {
return buf_[i]; }
927 char *
begin() noexcept {
return buf_.data(); }
929 char *
end() noexcept {
return buf_.data() + len_; }
931 const char *
begin() const noexcept {
return buf_.data(); }
933 const char *
end() const noexcept {
return buf_.data() + len_; }
943 std::string_view
view() const noexcept
945 return std::string_view{buf_.data(), len_};
954 operator std::string_view() const noexcept
962 return std::string{buf_.data(), len_};
968 return view() == rhs;
974 return view() != rhs;
1004 template <std::
size_t N>
1007 std::array<std::uint8_t, N> buf_{};
1008 std::size_t len_ = 0;
1044 for (std::uint8_t b : init)
1056 std::uint8_t *
data() noexcept {
return buf_.data(); }
1058 const std::uint8_t *
data() const noexcept {
return buf_.data(); }
1061 std::size_t
size() const noexcept {
return len_; }
1063 bool empty() const noexcept {
return len_ == 0; }
1065 static constexpr std::size_t
capacity() noexcept {
return N; }
1067 static constexpr std::size_t
max_size() noexcept {
return N; }
1078 void set_len(std::size_t n)
noexcept { len_ = n < N ? n : N; }
1093 std::uint8_t &
operator[](std::size_t i)
noexcept {
return buf_[i]; }
1095 const std::uint8_t &
operator[](std::size_t i)
const noexcept {
return buf_[i]; }
1098 std::uint8_t *
begin() noexcept {
return buf_.data(); }
1100 std::uint8_t *
end() noexcept {
return buf_.data() + len_; }
1102 const std::uint8_t *
begin() const noexcept {
return buf_.data(); }
1104 const std::uint8_t *
end() const noexcept {
return buf_.data() + len_; }
1113 for (std::size_t i = 0; i < len_; ++i)
1115 if (buf_[i] != o.buf_[i])
1157 template <
typename T, std::
size_t N>
1160 std::array<T, N> buf_{};
1161 std::size_t len_ = 0;
1196 for (
const T &v : init)
1208 std::size_t
size() const noexcept {
return len_; }
1210 bool empty() const noexcept {
return len_ == 0; }
1212 static constexpr std::size_t
capacity() noexcept {
return N; }
1214 static constexpr std::size_t
max_size() noexcept {
return N; }
1249 for (std::size_t i = n; i < len_; ++i)
1253 for (std::size_t i = len_; i < n; ++i)
1269 std::size_t i = len_ < N ? len_++ : N - 1;
1282 void push_back(
const T &v)
noexcept {
if (len_ < N) buf_[len_++] = v; }
1284 void push_back(T &&v)
noexcept {
if (len_ < N) buf_[len_++] =
static_cast<T &&
>(v); }
1287 T &
back() noexcept {
return buf_[len_ - 1]; }
1289 const T &
back() const noexcept {
return buf_[len_ - 1]; }
1294 const T &
operator[](std::size_t i)
const noexcept {
return buf_[i]; }
1297 T *
data() noexcept {
return buf_.data(); }
1299 const T *
data() const noexcept {
return buf_.data(); }
1302 T *
begin() noexcept {
return buf_.data(); }
1304 T *
end() noexcept {
return buf_.data() + len_; }
1306 const T *
begin() const noexcept {
return buf_.data(); }
1308 const T *
end() const noexcept {
return buf_.data() + len_; }
1317 for (std::size_t i = 0; i < len_; ++i)
1319 if (!(buf_[i] == o.buf_[i]))
1335 class OStreamMessage;
1407 [[nodiscard]]
bool empty() const noexcept {
return n_ == 0; }
1409 [[nodiscard]]
size_t size() const noexcept {
return n_; }
1424 if (n_ >=
static_cast<size_t>(
MAX_DEPTH)) [[unlikely]]
return false;
1431 if (n_ == 0)
return;
1514 void initBuffer(uint8_t *buffer,
size_t buflen,
size_t offset)
noexcept
1521 if (offset > buflen ||
1531 end_ = buffer + buflen;
1549 *p++ =
static_cast<uint8_t
>(
static_cast<uint8_t
>(v) | 0x80u);
1552 *p++ =
static_cast<uint8_t
>(v);
1553 return static_cast<size_t>(p - out);
1579 out[0] =
static_cast<uint8_t
>(v);
1586 const size_t bits = 64u -
static_cast<size_t>(std::countl_zero(v));
1587 const size_t n = (bits * 9u + 64u) >> 6;
1592 out[8] =
static_cast<uint8_t
>((
static_cast<uint8_t
>(v >> 56) & 0x7fu) | 0x80u);
1593 out[9] =
static_cast<uint8_t
>(v >> 63);
1594 out[n - 1] =
static_cast<uint8_t
>(out[n - 1] & 0x7fu);
1649 if (
static_cast<size_t>(
end_ -
cursor_) >= len) [[likely]]
1658 for (
size_t i = 0; i < len; ++i)
1714 for (
size_t i = 0; i < n; ++i)
1749 return (
static_cast<uint64_t
>(fieldId) << 3) |
static_cast<uint64_t
>(w);
1762 return (len << 3) |
static_cast<uint64_t
>(ft);
1817 const size_t room =
static_cast<size_t>(
end_ -
cursor_);
1825 if (len) std::memcpy(o,
data, len);
1844 template <std::
floating_po
int F>
1847 constexpr Fix ft = (
sizeof(F) == 4) ? Fix::Fp32 : Fix::Fp64;
1883 template <
typename E>
1884 requires (std::integral<E> || std::is_enum_v<E>)
1888 constexpr bool isSigned = std::is_signed_v<U>;
1895 const uint64_t head = (
static_cast<uint64_t
>(fieldId) << 3) |
1896 static_cast<uint64_t
>(isSigned ? Wire::ArraySigned : Wire::ArrayUnsigned);
1919 const auto word = [](
const E &v)
noexcept -> uint64_t {
1920 if constexpr (std::is_same_v<E, bool>)
1929 static_assert(
sizeof(bool) == 1,
"a bool element is stored as one byte");
1930 return reinterpret_cast<const unsigned char &
>(v) != 0 ? 1u : 0u;
1937 const auto u =
static_cast<U
>(v);
1939 else return static_cast<uint64_t
>(u);
1942 const size_t n = elems.size();
1943 for (
size_t i = 0; i < n; )
1946 if (fit == 0) [[unlikely]]
1954 if (fit > n - i) fit = n - i;
1956 for (
size_t k = 0; k < fit; ++k, ++i)
1976 template <std::
floating_po
int F>
1979 constexpr Fix ft = (
sizeof(F) == 4) ? Fix::Fp32 : Fix::Fp64;
2005 if constexpr (std::endian::native == std::endian::little)
2008 return pushBytes(
reinterpret_cast<const uint8_t *
>(elems.data()), elems.size() *
sizeof(F));
2014 uint8_t tmp[
sizeof(F)];
2045 template <
typename T>
2059 template <
typename T>
2062 if (error_ ==
Error::None && condition) error_ = os_.
write(fieldId, value).error_;
2072 template <
typename T>
2109 [[nodiscard]]
explicit operator bool() const noexcept {
return ok(); }
2113 [[nodiscard]]
Error code() const noexcept {
return error_; }
2164 [[nodiscard]]
const uint8_t *
data() const noexcept {
return buffer_; }
2243 template <
typename T>
2248 if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>)
2250 if constexpr (std::is_unsigned_v<T>)
2251 err =
writeScalar(fieldId, Wire::Unsigned,
static_cast<uint64_t
>(value));
2255 else if constexpr (std::is_same_v<T, bool>)
2257 err =
writeScalar(fieldId, Wire::Unsigned, value ? 1u : 0u);
2259 else if constexpr (std::is_same_v<T, float>) { err =
writeFloatScalar(fieldId, value); }
2260 else if constexpr (std::is_same_v<T, double>) { err =
writeFloatScalar(fieldId, value); }
2261 else if constexpr (std::is_convertible_v<T, std::string_view>)
2263 std::string_view sv{value};
2264#if SOFAB_STRICT_UTF8
2274 reinterpret_cast<const uint8_t *
>(sv.data()), sv.size());
2276 else if constexpr (std::is_base_of_v<OStreamMessage, T>)
2283 if (err ==
Error::None) err = value.serialize(*this).error_;
2286 else if constexpr (
requires {
typename T::value_type; std::span{std::declval<const T &>()}; })
2288 using Elem =
typename T::value_type;
2289 std::span<const Elem> sp{value};
2295 if constexpr (std::is_integral_v<Elem> || std::is_enum_v<Elem>)
2297 else if constexpr (std::is_same_v<Elem, float> || std::is_same_v<Elem, double>)
2300 static_assert(always_false_v<T>,
"Unsupported span element type in OStream::write()");
2304 static_assert(always_false_v<T>,
"Unsupported type passed to OStream::write()");
2307 return Result{*
this, err};
2329 template <
typename T>
2330 requires std::is_base_of_v<OStreamMessage, T>
2334 if (err ==
Error::None) err = value.serialize(*this).error_;
2336 return Result{*
this, err};
2363 static_cast<const uint8_t *
>(value),
static_cast<size_t>(size))};
2374 template <
typename T>
2414 if (fieldId >
ID_MAX) [[unlikely]]
2516 OStream(std::shared_ptr<uint8_t[]> buffer,
size_t buflen,
size_t offset = 0) noexcept
2557 void setBuffer(std::shared_ptr<uint8_t[]> buffer,
size_t buflen,
size_t offset = 0) noexcept
2589 OStreamView(uint8_t *buffer,
size_t buflen,
size_t offset = 0) noexcept
2602 size_t offset = 0) noexcept
2629 void setBuffer(uint8_t *buffer,
size_t buflen,
size_t offset = 0) noexcept
2652 template <
size_t N,
size_t Offset = 0>
2655 static_assert(N > 0,
"Buffer size N must be greater than zero");
2656 static_assert(Offset < N,
"Offset must be less than buffer size N");
2657 std::array<uint8_t, N> bufferOwner_{};
2680 std::derived_from<T, OStreamMessage> &&
2681 requires { { T::_maxSize } -> std::convertible_to<std::size_t>; } &&
2682 std::is_same_v<
decltype(T::_maxSize),
const std::size_t>;
2714 template <OutputMessage MessageType,
size_t N = MessageType::_maxSize,
size_t Offset = 0>
2717 MessageType message_;
2741 const MessageType *
operator->() const noexcept {
return &message_; }
2749 auto result = message_.serialize(
static_cast<OStreamImpl &
>(*
this));
2760 class IStreamMessage;
2765 template <
typename T>
2851 constexpr explicit Limits(
size_t maxBufferedField) noexcept
2899 template <
typename E>
2902 if constexpr (
sizeof(E) >=
sizeof(int64_t))
return ElemBound{};
2904 return ElemBound{
static_cast<int64_t
>(std::numeric_limits<E>::min()),
2905 static_cast<int64_t
>(std::numeric_limits<E>::max())};
2939 size_t skipped_ = 0;
2950 [[nodiscard]]
size_t skipped() const noexcept {
return skipped_; }
2952 [[nodiscard]]
explicit operator bool() const noexcept {
return ok(); }
3001 [[nodiscard]]
Error code() const noexcept {
return error_; }
3144 const uint8_t *
p_ =
nullptr;
3260 [[gnu::always_inline]]
static inline bool getVarintWindowed(
const uint8_t *&p, uint64_t &out,
bool *overflow)
noexcept
3276 const uint64_t term = ~w & 0x8080808080808080ull;
3277 if (term) [[likely]]
3279 const unsigned len = (
static_cast<unsigned>(std::countr_zero(term)) >> 3) + 1u;
3287 const uint8_t b8 = p[8];
3288 v |=
static_cast<uint64_t
>(b8 & 0x7f) << 56;
3300 const uint8_t b9 = p[9];
3307 if (overflow) *overflow =
true;
3310 v |=
static_cast<uint64_t
>(b9) << 63;
3318 const uint64_t term = ~detail::loadLittle64(p) & 0x8080808080808080ull;
3319 if (term) [[likely]]
3321 p += (
static_cast<unsigned>(std::countr_zero(term)) >> 3) + 1u;
3324 const uint8_t b8 = p[8];
3330 const uint8_t b9 = p[9];
3334 if (overflow) *overflow =
true;
3356 [[gnu::always_inline]]
static inline bool getVarint(
const uint8_t *&p,
const uint8_t *end, uint64_t &out,
3357 bool *overflow =
nullptr) noexcept
3365 if (p < end && *p < 0x80) [[likely]]
3382 for (
const uint8_t *q = p; q < end; )
3384 const uint8_t b = *q++;
3385 v |=
static_cast<uint64_t
>(b & 0x7f) << shift;
3410 bool *overflow =
nullptr) noexcept
3413 if (p < end && *p < 0x80) [[likely]]
3421 for (
const uint8_t *q = p; q < end; )
3422 if (!(*q++ & 0x80)) { p = q;
return true; }
3441 uint64_t len = word >> 3;
3442 switch (
static_cast<Fix>(word & 0x7))
3444 case Fix::Fp32:
return len == 4;
3445 case Fix::Fp64:
return len == 8;
3448 default:
return false;
3465 uint64_t esize = word >> 3;
3466 switch (
static_cast<Fix>(word & 0x7))
3468 case Fix::Fp32:
return esize == 4;
3469 case Fix::Fp64:
return esize == 8;
3470 default:
return false;
3480 template <std::
floating_po
int F>
3483 using Bits = std::conditional_t<
sizeof(F) == 4, uint32_t, uint64_t>;
3484 return detail::bitsFloat<F>(detail::loadLittleBits<Bits>(p));
3515 if (
type_ == wantWire)
return true;
3565 template <
typename D>
3568 const size_t avail =
static_cast<size_t>(
end_ -
p_);
3575#if SOFAB_STRICT_UTF8
3578 {
error_ =
true;
return false; }
3611 template <
typename D>
3614 if constexpr (
requires { D::capacity(); })
3635 template <
typename D>
3639 const size_t take = std::min(avail,
fixLen_ - done);
3640 if (!
roomFor(value, done + take))
return false;
3641#if SOFAB_STRICT_UTF8
3650 if (take) std::memcpy(value.data() + done,
p_, take);
3658#if SOFAB_STRICT_UTF8
3660 {
error_ =
true;
return false; }
3680 const uint64_t reach =
static_cast<uint64_t
>(
spanCarry_) +
static_cast<uint64_t
>(n);
3681 if (reach <
static_cast<uint64_t
>(n) || reach > cap)
return false;
3741 fn(
ctx,
id, size, count);
3746 template <
typename Cb>
3750 (*
static_cast<Cb *
>(p))(
id, size, count);
3778 template <
typename Cb>
3801 const uint8_t *
const fieldStart =
p_;
3805 const uint8_t *payload =
p_;
3809 if (!
finishField(fieldStart, payload, fieldId))
return;
3846 const uint8_t *
const fieldStart =
p_;
3877 bool skipElem =
false;
3878 bool boundPending =
false;
3884 else boundPending =
true;
3887 if (
type_ == Wire::SequenceEnd)
3889 if (!stopAtEnd)
error_ =
true;
3950 [[gnu::always_inline]]
inline bool finishField(
const uint8_t *fieldStart,
3951 const uint8_t *payload,
3954 bool declined =
false;
4067 const uint8_t *
const from =
p_;
4070 if (
error_)
return false;
4076 if (
error_)
return false;
4109 type_ = Wire::SequenceStart;
4119 const uint8_t *
const from =
p_;
4126 cb(fieldId,
size_t{0},
size_t{0});
4128 if (
error_)
return false;
4154 case Wire::Unsigned:
4169 const size_t avail =
static_cast<size_t>(
end_ -
p_);
4181 case Wire::ArrayUnsigned:
4182 case Wire::ArraySigned:
4189 if (ovf) {
error_ =
true;
return; }
4198 case Wire::ArrayFixlen:
4202 const size_t avail =
static_cast<size_t>(
end_ -
p_);
4214 case Wire::SequenceStart:
4224 case Wire::SequenceEnd:
4349 const uint8_t *cur = buffer;
4350 size_t left = buflen;
4364 const size_t take = std::min(
CARRY_CAP - held, left);
4365 std::memcpy(stitch,
carry_, held);
4366 std::memcpy(stitch + held, cur, take);
4367 const size_t window = held + take;
4377 std::memcpy(
carry_, stitch + used, window - used);
4382 left -= used - held;
4385 stash(stitch + used, window - used);
4395 stash(cur + used, left - used);
4539 const long i =
static_cast<long>(bad);
4564 [[nodiscard]]
bool atBoundary() const noexcept
4619 void stash(
const uint8_t *p,
size_t n)
noexcept
4631 std::memcpy(
carry_, p, n);
4655 return static_cast<size_t>(
p_ - p);
4670 bool declined =
false;
4678 const uint8_t *
const end =
end_;
4686 const uint8_t *fieldStart =
p_;
4733 const uint8_t *
const withheld =
p_;
4734 const uint8_t *held =
end_;
4779 const uint8_t *payload =
p_;
4822 if ((header >> 3) >
ID_MAX)
4828 type_ =
static_cast<Wire>(header & 0x7);
4866 fixLen_ =
static_cast<size_t>(sub >> 3);
4870 case Wire::ArrayUnsigned:
4871 case Wire::ArraySigned:
4884 count_ =
static_cast<size_t>(n);
4887 case Wire::ArrayFixlen:
4907 count_ =
static_cast<size_t>(n);
4920 fixLen_ =
static_cast<size_t>(sub >> 3);
4946 if (
type_ == Wire::SequenceEnd)
4968 return w == Wire::Fixlen || w == Wire::ArrayUnsigned ||
4969 w == Wire::ArraySigned || w == Wire::ArrayFixlen;
4985 const size_t seen =
spanned();
4989 case Wire::Fixlen: need =
fixLen_;
break;
4990 case Wire::ArrayFixlen: need =
static_cast<uint64_t
>(
count_) *
fixLen_;
break;
4991 case Wire::ArrayUnsigned:
4992 case Wire::ArraySigned: need =
count_;
break;
4993 default: need = 0;
break;
5017 template <
bool Bounded,
typename Elem>
5020 const size_t n = sp.size();
5025 auto admits = [b](uint64_t raw)
noexcept ->
bool {
5026 if constexpr (std::is_unsigned_v<Elem>)
5027 return raw <=
static_cast<uint64_t
>(b.hi) &&
5028 (b.lo <= 0 || raw >=
static_cast<uint64_t
>(b.lo));
5032 return v >= b.lo && v <= b.hi;
5035 auto store = [&](
size_t i, uint64_t raw)
noexcept ->
bool {
5036 if constexpr (Bounded)
5037 if (!admits(raw)) {
error_ =
true;
return false; }
5038 if constexpr (std::is_same_v<Elem, bool>)
5046 static_assert(
sizeof(bool) == 1,
"a bool element is stored as one byte");
5047 reinterpret_cast<unsigned char &
>(sp[i]) = raw != 0 ? 1u : 0u;
5049 else if constexpr (std::is_unsigned_v<Elem>) sp[i] =
static_cast<Elem
>(raw);
5076 if (fit == 0) [[unlikely]]
5082 if (ovf) {
error_ =
true;
return false; }
5089 if (!store(i, raw))
return false;
5093 if (fit > n - i) fit = n - i;
5094 for (
size_t k = 0; k < fit; ++k, ++i)
5102 if (!store(i, raw))
return false;
5109 if (fit == 0) [[unlikely]]
5112 if constexpr (Bounded)
5116 else if (!admits(raw)) {
error_ =
true;
return false; }
5121 if (ovf) {
error_ =
true;
return false; }
5130 for (
size_t k = 0; k < fit; ++k, ++i)
5132 if constexpr (Bounded)
5140 if (!admits(raw)) {
error_ =
true;
return false; }
5192 template <
typename T>
5195 if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>)
5197 constexpr Wire want = std::is_unsigned_v<T> ? Wire::Unsigned : Wire::Signed;
5209 if constexpr (std::is_unsigned_v<T>) value =
static_cast<T
>(raw);
5213 else if constexpr (std::is_same_v<T, bool>)
5216 if (!
tagMatches(Wire::Unsigned))
return false;
5227 else if constexpr (std::is_same_v<T, float> || std::is_same_v<T, double>)
5229 constexpr Fix want = std::is_same_v<T, float> ? Fix::Fp32 : Fix::Fp64;
5230 if (!
tagMatches(Wire::Fixlen, want))
return false;
5231 if (
static_cast<size_t>(
end_ -
p_) <
sizeof(T))
5236 value = loadFloat<T>(
p_);
5240 else if constexpr (std::is_same_v<T, std::string_view>)
5258 static_assert(always_false_v<T>,
5259 "IStream::read() does not decode into std::string_view: a fed chunk is "
5260 "borrowed only for the duration of feed() (CORELIB_PLAN §6), so a view "
5261 "into it dangles as soon as feed() returns. Read into an owning "
5262 "destination instead — std::string, std::vector<uint8_t>, "
5263 "sofab::FixedString<N>, sofab::FixedBytes<N> — via read(), readString() "
5266 else if constexpr (std::is_same_v<T, std::string>)
5277 if (!
tagMatches(Wire::Fixlen, Fix::String, Fix::Blob))
5286 if (!
tagMatches(Wire::SequenceStart))
return false;
5299 if constexpr (
requires { value.prepare(); }) value.prepare();
5324 if constexpr (
requires { value.cap; })
elemSchema_ = value.cap;
5334 static_assert(!(
requires { value.cap; }) || (
requires { value.dynCap; }),
5335 "A wrapper-array collector that publishes a schema `cap` must also "
5336 "publish a receiver `dynCap` (CORELIB_PLAN 6.2.1): without it a "
5337 "schema-unbounded array would be bounded by nothing.");
5338 if constexpr (
requires { value.dynCap; })
elemDyn_ = value.dynCap;
5340 if constexpr (
requires { T::elemDestCap; })
elemDest_ =
static_cast<long>(T::elemDestCap);
5349 if constexpr (
requires { T::elemWire; })
elemWire_ =
static_cast<int>(T::elemWire);
5351 if constexpr (
requires { T::elemFix; })
elemFix_ =
static_cast<int>(T::elemFix);
5361 value.deserialize(*
this, i, s, c);
5379 else if constexpr (
requires {
typename T::value_type; std::span{std::declval<T &>()}; } &&
5380 !std::is_const_v<typename T::value_type>)
5382 using Elem =
typename T::value_type;
5383 std::span<Elem> sp{value};
5384 size_t n = std::min(sp.size(),
count_);
5385 if constexpr (std::is_integral_v<Elem> && !std::is_same_v<Elem, bool>)
5388 constexpr Wire want = std::is_unsigned_v<Elem> ? Wire::ArrayUnsigned : Wire::ArraySigned;
5393 if (!readIntElements<false>(sp.first(n)))
return false;
5395 else if constexpr (std::is_same_v<Elem, bool>)
5403 if (!
tagMatches(Wire::ArrayUnsigned))
return false;
5404 if (!readIntElements<false>(sp.first(n)))
return false;
5406 else if constexpr (std::is_same_v<Elem, float> || std::is_same_v<Elem, double>)
5408 constexpr Fix want = std::is_same_v<Elem, float> ? Fix::Fp32 : Fix::Fp64;
5409 if (!
tagMatches(Wire::ArrayFixlen, want))
return false;
5410 const size_t bytes =
count_ *
sizeof(Elem);
5412 static_cast<size_t>(
end_ -
p_) >= bytes) [[likely]]
5416 if constexpr (std::endian::native == std::endian::little)
5420 if (n) std::memcpy(sp.data(),
p_, n *
sizeof(Elem));
5423 for (
size_t i = 0; i < n; ++i)
5424 sp[i] = loadFloat<Elem>(
p_ + i *
sizeof(Elem));
5436 if (
static_cast<size_t>(
end_ -
p_) <
sizeof(Elem))
5442 if (i < n) sp[i] = loadFloat<Elem>(
p_);
5452 static_assert(always_false_v<T>,
"Unsupported span element type in IStream::read()");
5457 static_assert(always_false_v<T>,
"Unsupported type passed to IStream::read()");
5519 template <
typename S,
typename Sizer = detail::NoSizer>
5547 template <
typename S,
typename Sizer = detail::NoSizer>
5564 template <
typename S,
typename Sizer>
5567 if (!
tagMatches(Wire::Fixlen, Fix::String))
return false;
5568 if (bound >= 0 &&
fixLen_ >
static_cast<size_t>(bound))
5569 {
error_ =
true;
return false; }
5573 if (bound < 0 && dynCap >= 0 &&
fixLen_ >
static_cast<size_t>(dynCap))
5611 template <
typename B,
typename Sizer = detail::NoSizer>
5612 bool readBlob(B &value,
long bound, Sizer sizer = {})
noexcept
5633 template <
typename B,
typename Sizer = detail::NoSizer>
5642 template <
typename B,
typename Sizer>
5645 if (!
tagMatches(Wire::Fixlen, Fix::Blob))
return false;
5646 if (bound >= 0 &&
fixLen_ >
static_cast<size_t>(bound))
5651 if (bound < 0 && dynCap >= 0 &&
fixLen_ >
static_cast<size_t>(dynCap))
5718 template <
typename T,
typename Sizer = detail::NoSizer>
5740 template <
typename T,
typename Sizer = detail::NoSizer>
5749 template <
typename T,
typename Sizer>
5752 using Elem =
typename T::value_type;
5753 if constexpr (std::is_same_v<Elem, float> || std::is_same_v<Elem, double>)
5755 constexpr Fix want = std::is_same_v<Elem, float> ? Fix::Fp32 : Fix::Fp64;
5756 if (!
tagMatches(Wire::ArrayFixlen, want))
return false;
5760 constexpr Wire want = std::is_unsigned_v<Elem> ? Wire::ArrayUnsigned : Wire::ArraySigned;
5763 if (schemaCount >= 0 &&
count_ >
static_cast<size_t>(schemaCount))
5772 if (schemaCount < 0 && dynCap >= 0 &&
count_ >
static_cast<size_t>(dynCap))
5798 if constexpr (
constexpr long destCap = detail::destCapacity<T>(); destCap >= 0)
5804 if (
count_ >
static_cast<size_t>(destCap))
5810 else if constexpr (
requires { dst.resize(
size_t{}); })
5828 const uint64_t readable =
static_cast<uint64_t
>(
end_ -
p_);
5829 const uint64_t fillable =
type_ == Wire::ArrayFixlen
5832 const size_t reach =
static_cast<size_t>(
5833 std::min<uint64_t>(
static_cast<uint64_t
>(
count_),
5834 static_cast<uint64_t
>(
pendDone_) + fillable));
5836 if (reach > dst.size())
5867 else if constexpr (!
requires { dst.resize(
size_t{}); }) dst = T{};
5869 const bool ok = [&]()
noexcept {
5870 if constexpr (std::is_integral_v<Elem> && !std::is_same_v<Elem, bool>)
5876 std::span<Elem> sp{dst};
5877 return readIntElements<true>(sp.first(std::min(sp.size(),
count_)), elem);
5882 if (!ok)
return false;
5911 size_t read(
void *dst,
size_t maxlen)
noexcept
5913 if (!
tagMatches(Wire::Fixlen, Fix::Blob))
return 0;
5915 const size_t avail =
static_cast<size_t>(
end_ -
p_);
5916 const size_t take = std::min(avail,
fixLen_ - done);
5921 if (done < maxlen && take)
5922 std::memcpy(
static_cast<uint8_t *
>(dst) + done,
p_,
5923 std::min(take, maxlen - done));
5939 return std::min(maxlen,
fixLen_);
6001 return static_cast<size_t>(
end_ -
p_);
6084 if (!
tagMatches(Wire::Fixlen, Fix::String))
return false;
6085 if (bound >= 0 &&
fixLen_ >
static_cast<size_t>(bound))
6086 {
error_ =
true;
return false; }
6087 if (bound < 0 && dynCap >= 0 &&
fixLen_ >
static_cast<size_t>(dynCap))
6111 if (!
tagMatches(Wire::Fixlen, Fix::Blob))
return false;
6112 if (bound >= 0 &&
fixLen_ >
static_cast<size_t>(bound))
6113 {
error_ =
true;
return false; }
6114 if (bound < 0 && dynCap >= 0 &&
fixLen_ >
static_cast<size_t>(dynCap))
6155 template <InputMessage MessageType>
6219 template <InputMessage MessageType>
6234 data_.deserialize(*
this,
id, size, count);
6253 std::destroy_at(&data_);
6254 std::construct_at(&data_);
6264 const MessageType &
operator*() const noexcept {
return data_; }
6302 template <InputMessage MessageType>
6318 data_->deserialize(*
this,
id, size, count);
6372 template <
typename D>
6373 concept sizable =
requires(D &d) { d.resize(
size_t{}); } && !
requires { D::capacity(); };
6375 template <
typename D>
6378 if constexpr (
requires { D::capacity(); }) { (void)dst; (void)want; }
6379 else if constexpr (
requires { dst.resize(
size_t{}); })
6381 if (dst.size() < want) dst.resize(want);
6393 template <
typename D>
6407 const uint64_t readable =
static_cast<uint64_t
>(is.available());
6409 ? (is.announcedSize()
6410 ? readable / is.announcedSize()
6413 return static_cast<size_t>(
6414 std::min<uint64_t>(
static_cast<uint64_t
>(is.announcedCount()),
6415 static_cast<uint64_t
>(is.progress()) + fillable));
6419 template <
typename Elem>
6422 if constexpr (std::is_same_v<Elem, float>)
6424 else if constexpr (std::is_same_v<Elem, double>)
6426 else if constexpr (std::is_unsigned_v<Elem>)
6469 template <
typename S>
6473 else return is.readString(dst, maxlen);
6484 template <
typename S>
6488 else return is.readStringCapped(dst, dynCap);
6495 template <
typename B>
6499 else return is.readBlob(dst, maxlen);
6506 template <
typename B>
6510 else return is.readBlobCapped(dst, dynCap);
6532 template <
typename T>
6535 if constexpr (detail::sizable<T>)
return is.
readArray(dst, schemaCount, elem, detail::FitDest{});
6536 else return is.
readArray(dst, schemaCount, elem);
6548 template <
typename T>
6551 if constexpr (detail::sizable<T>)
return is.
readArrayCapped(dst, dynCap, elem, detail::FitDest{});
6564 template <
typename T>
6567 if constexpr (std::is_same_v<T, std::string>)
6569 if (is.
wire() == detail::Wire::Fixlen &&
6570 (is.
fixType() == detail::Fix::String || is.
fixType() == detail::Fix::Blob))
6574 else if constexpr (
requires(T &d) {
6575 typename T::value_type;
6577 requires !std::is_const_v<typename T::value_type>;
6582 if (detail::arrayTagMatches<typename T::value_type>(is))
6583 detail::fitDest(dst, detail::arrayReach(is));
6585 return is.
read(dst);
6636 long destCap)
noexcept
6638 const long i =
static_cast<long>(
id);
6639 const long dyn = dynCap;
6640 if (cap < 0 && dyn < 0 && destCap < 0)
6647 if (i >= cap) { is.
invalidate();
return false; }
6649 else if (dyn >= 0 && i >= dyn)
6654 if (destCap >= 0 && i >= destCap)
6685 template <
typename C = std::vector<std::
string>>
6739 static constexpr long elemDestCap = detail::destCapacity<C>();
6750 static constexpr int elemWire =
static_cast<int>(detail::Wire::Fixlen);
6752 static constexpr int elemFix =
static_cast<int>(detail::Fix::String);
6773 long indexCap,
long elemLenCap) noexcept
6774 : out(o), cap(capacity), emax(elemMax), dynCap(indexCap),
6775 elemDynCap(elemLenCap) {}
6825 if (!detail::seqIndexAdmitted(is,
id, cap, dynCap, elemDestCap))
return;
6826 while (out.size() <=
static_cast<size_t>(
id)) out.emplace_back();
6827 auto &slot = out[
static_cast<size_t>(
id)];
6840 template <
typename C = std::vector<std::vector<u
int8_t>>>
6849 static constexpr long elemDestCap = detail::destCapacity<C>();
6852 static constexpr int elemWire =
static_cast<int>(detail::Wire::Fixlen);
6854 static constexpr int elemFix =
static_cast<int>(detail::Fix::Blob);
6860 explicit BlobSeq(C &o,
long capacity,
long elemMax,
6861 long indexCap,
long elemLenCap) noexcept
6862 : out(o), cap(capacity), emax(elemMax), dynCap(indexCap),
6863 elemDynCap(elemLenCap) {}
6876 if (!detail::seqIndexAdmitted(is,
id, cap, dynCap, elemDestCap))
return;
6877 while (out.size() <=
static_cast<size_t>(
id)) out.emplace_back();
6878 auto &slot = out[
static_cast<size_t>(
id)];
6904 template <
typename A>
6907 if constexpr (
requires {
typename A::value_type; })
6909 using V =
typename A::value_type;
6910 return std::is_base_of_v<IStreamMessage, V> ||
requires {
typename V::value_type; };
6938 template <
typename A>
6942 using Container = std::conditional_t<detail::namesSeqContainer<A>(), A, std::vector<A>>;
6944 using Elem =
typename Container::value_type;
7009 long rowDynCap = -1;
7011 static constexpr long elemDestCap = detail::destCapacity<Container>();
7022 static constexpr int elemWire = []()
constexpr ->
int {
7023 if constexpr (std::is_base_of_v<IStreamMessage, Elem>)
7024 return static_cast<int>(detail::Wire::SequenceStart);
7025 else if constexpr (
requires {
typename Elem::value_type; })
7027 using RowElem =
typename Elem::value_type;
7030 if constexpr (std::is_integral_v<RowElem>)
7031 return static_cast<int>(std::is_unsigned_v<RowElem> ? detail::Wire::ArrayUnsigned
7032 : detail::Wire::ArraySigned);
7033 else if constexpr (std::is_same_v<RowElem, float> || std::is_same_v<RowElem, double>)
7034 return static_cast<int>(detail::Wire::ArrayFixlen);
7043 void prepare() noexcept {
if (out) out->clear(); }
7057 if constexpr (elemWire >= 0)
7059 if (
static_cast<int>(is.
wire()) != elemWire)
return;
7067 if (!detail::seqIndexAdmitted(is,
id, cap, dynCap, elemDestCap))
return;
7076 while (out->size() <=
static_cast<size_t>(
id)) (void)out->emplace_back();
7077 Elem &row = (*out)[
static_cast<size_t>(
id)];
7078 if constexpr (std::is_base_of_v<IStreamMessage, Elem>)
7082 else if constexpr (
requires { row.resize(
size_t{}); })
7093 if constexpr (detail::destCapacity<Elem>() >= 0)
7095 else if (rowCap >= 0)
7180 template <
typename C,
typename Reader>
7186 using Elem =
typename C::value_type;
7197 static constexpr long elemDestCap = detail::destCapacity<C>();
7201 static constexpr int elemWire =
static_cast<int>(Reader::wire());
7213 explicit RowSeq(C &o,
long capacity,
long indexCap, Reader reader = {})
noexcept
7214 : out(o), cap(capacity), dynCap(indexCap), readRow(reader) {}
7225 if (
static_cast<int>(is.
wire()) != elemWire)
return;
7226 if (!detail::seqIndexAdmitted(is,
id, cap, dynCap, elemDestCap))
return;
7227 while (out.size() <=
static_cast<size_t>(
id)) (void)out.emplace_back();
7228 readRow(is, out[
static_cast<size_t>(
id)]);
Bit-pattern equality for float arrays (sofab::bitsEqual).
Fixed-capacity, heap-free byte blob of up to N bytes.
bool empty() const noexcept
True if the blob is empty.
void set_len(std::size_t n) noexcept
Decode hook: set the logical length (clamped to N).
std::size_t size_type
Size type (mirrors std::vector).
std::size_t size() const noexcept
Number of bytes currently stored.
void clear() noexcept
Reset to an empty blob.
static constexpr std::size_t capacity() noexcept
Maximum number of bytes (the template parameter N).
std::uint8_t value_type
Element type (mirrors std::vector).
const std::uint8_t * end() const noexcept
Const iterator past the last byte.
bool operator!=(const FixedBytes &o) const noexcept
Negated operator==.
bool operator==(const FixedBytes &o) const noexcept
Content equality (same logical length and bytes).
const std::uint8_t * begin() const noexcept
Const iterator to the first byte.
FixedBytes & operator=(std::initializer_list< std::uint8_t > init) noexcept
Replace the contents from a brace-enclosed list (clamped to N; extra bytes are dropped).
const std::uint8_t & operator[](std::size_t i) const noexcept
Access the byte at i (no bounds checking).
void push_back(std::uint8_t b) noexcept
Append one byte (no-op once at capacity N).
static constexpr std::size_t max_size() noexcept
Alias of capacity.
std::uint8_t * end() noexcept
Iterator past the last byte.
FixedBytes() noexcept=default
Construct an empty blob.
const std::uint8_t * data() const noexcept
Const pointer to the byte buffer.
std::uint8_t & operator[](std::size_t i) noexcept
Access the byte at i (no bounds checking).
FixedBytes & assign(std::initializer_list< std::uint8_t > init) noexcept
Replace the contents from a brace-enclosed list (clamped to N; extra bytes are dropped).
std::uint8_t * begin() noexcept
Iterator to the first byte.
std::uint8_t * data() noexcept
Mutable pointer to the byte buffer (decode target).
Fixed-capacity, heap-free string of up to N characters.
char * end() noexcept
Iterator past the last character.
bool operator!=(std::string_view rhs) const noexcept
Inequality against any string view-like operand.
const char * end() const noexcept
Const iterator past the last character.
FixedString & operator=(const char *s) noexcept
Assign from a NUL-terminated C string (clamped to N, see assign).
static constexpr std::size_t max_size() noexcept
Alias of capacity.
void clear() noexcept
Reset to an empty string.
std::string_view view() const noexcept
Non-owning view over the current characters.
const char * data() const noexcept
Const pointer to the character buffer.
FixedString(const std::string &s) noexcept
Construct from a std::string (the easy on-ramp; truncated to N).
char & operator[](std::size_t i) noexcept
Access the character at i (no bounds checking).
const char * c_str() const noexcept
NUL-terminated view of the contents.
const char * begin() const noexcept
Const iterator to the first character.
char * begin() noexcept
Iterator to the first character.
FixedString & assign(std::string_view sv) noexcept
Replace the contents with sv, clamped to N bytes.
FixedString & operator=(std::string_view sv) noexcept
Assign from a string view (clamped to N, see assign).
std::string str() const
Copy the contents into an owning std::string (allocates).
const char & operator[](std::size_t i) const noexcept
Access the character at i (no bounds checking).
FixedString(std::string_view sv) noexcept
Construct from a string view (clamped to N, see assign).
bool empty() const noexcept
True if the string is empty.
static constexpr std::size_t capacity() noexcept
Maximum number of characters (the template parameter N).
char * data() noexcept
Mutable pointer to the character buffer (decode target).
std::size_t length() const noexcept
Alias of size.
std::size_t size() const noexcept
Number of characters currently stored.
char value_type
Character type (mirrors std::string).
bool operator==(std::string_view rhs) const noexcept
Equality against any string view-like operand.
std::size_t size_type
Size type (mirrors std::string).
void set_len(std::size_t n) noexcept
Decode hook: set the logical length and (re)place the trailing NUL.
FixedString() noexcept=default
Construct an empty string.
FixedString & operator=(const std::string &s) noexcept
Assign from a std::string (clamped to N, see assign).
Three-valued outcome of a feed call (spec §7).
bool invalid() const noexcept
bool operator==(Error e) const noexcept
bool incomplete() const noexcept
bool operator!=(Error e) const noexcept
bool invalidArgument() const noexcept
Error code() const noexcept
DecodeStatus status() const noexcept
bool complete() const noexcept
bool limitExceeded() const noexcept
size_t skipped() const noexcept
Base of the input streams: decodes fields from fed bytes.
bool readIntElements(std::span< Elem > sp, ElemBound b={}) noexcept
Decode the current integer-array payload: count_ varint elements, the first sp.size() of them into sp...
void discountSkipped(const uint8_t *from) noexcept
Discount a skipped field's bytes from the live span (§6.2.1).
Wire pendType_
That field's header, kept apart from the live type_ / fixLen_ / count_.
size_t maxBufferedField_
The receiver's byte budget for one top-level field (Limits::max_buffered_field), as this decode was t...
bool capCannotFire(size_t n) const noexcept
Hoisted form of exceedsBuffer for a whole window of n bytes: true when no field of it can cross the b...
size_t skipped() const noexcept
Number of fields skipped this stream because their wire tag contradicted the type the callback asked ...
size_t spanned() const noexcept
The bytes of the current top-level field seen so far, across every chunk it spans (#26,...
bool capInert_
Can the field-span cap provably not fire anywhere in the window being parsed (§6.2....
bool readPayload(D &value, bool validateUtf8) noexcept
Deliver the current fixlen payload into the destination the caller handed over (§6....
size_t available() const noexcept
Bytes of this field readable right now, in the chunk being parsed.
uint8_t carry_[CARRY_CAP]
The prefix of one cut item, carried to the next feed.
void invalidate() noexcept
Mark the running decode INVALID from inside a deliver callback.
static FieldCb wrapCb(Cb &cb) noexcept
Wrap a level's callback as a FieldCb.
static constexpr bool schemaBoundsHeader(Wire w) noexcept
Does this wire type's header state a size the schema can bound?
size_t pendDone_
Progress through the pending field: payload bytes already written into the caller's destination,...
int suspendDepth_
Depth at which the parse is suspended, or -1 when nothing is.
Fix fixType_
Sub-type of the current fixlen field.
bool error_
Sticky "this feed was refused" flag, and the only one the parse loops test.
Result latchTerminal() noexcept
Latch the refusal this feed produced, in §6.3's order of tiers.
size_t parseWindow(const uint8_t *p, size_t n) noexcept
Parse one window of bytes, resuming whatever the last one left open, and report how much of it was co...
std::function< void(sofab::id, size_t, size_t)> topCallback_
Delivers each top-level field.
bool acceptsBlobGated(long bound, long dynCap) noexcept
The body both blob accepts share.
bool reenterLevel(FieldCb cb, Entry entry) noexcept
Take the Entry::Descend or Entry::Resume path.
int seqDepth_
Current nested-sequence depth during dispatch (§4.9 MAX_DEPTH).
bool readStringCapped(S &value, long dynCap, Sizer sizer={}) noexcept
Read the current field as a schema-**unbounded** string under the receiver's max_dyn_string_len (§6....
bool deliverPending(FieldCb cb, bool declined) noexcept
Re-deliver the half-delivered field at this level.
const uint8_t * p_
Read cursor.
bool acceptsString(long bound) noexcept
The §7.3 and §7.1 decisions readString makes, taken before a destination exists.
void skipPayload() noexcept
Step over the payload of the current field, resumably.
size_t fixLen_
Payload length (fixlen) or element size (fixlen array), in bytes.
const uint8_t * spanBase_
Where that field's span continues in the window being parsed (#26).
bool parseFieldMeta() noexcept
Parse the word(s) between a field header and its payload — the fixlen word (§4.6),...
void suspendAtBoundary() noexcept
Claim the suspension for this level at a field boundary — nothing half-delivered, only a header cut i...
Wire wire() const noexcept
Wire type of the field currently being delivered.
long elemDyn_
Configured max_dyn_array_count: LimitExceeded (§6.2.1).
IStreamImpl & operator=(const IStreamImpl &)=delete
bool read(T &value) noexcept
Read the current field's value, dispatching on value's type.
size_t announcedCount() const noexcept
The element count the current array field's header announces.
void stash(const uint8_t *p, size_t n) noexcept
Hold the ≤ CARRY_CAP bytes of a cut item until the next feed.
size_t carryLen_
Live bytes of carry_.
size_t progress() const noexcept
How much of the current field earlier chunks already delivered — payload bytes written,...
void restorePending() noexcept
Put the suspended field's header back before continuing it.
sofab::id pathId_[MAX_DEPTH+1]
Id of the sequence field entered at each open level (§4.9).
bool descendResume(FieldCb cb) noexcept
Re-descend one recorded level of pathId_ towards suspendDepth_.
void rejectElementIndex(sofab::id bad) noexcept
Refuse a wrapper-array element whose index is at or past a bound, in the category §6....
void skipSequence() noexcept
Walk a sub-sequence nobody asked for, delivering nothing.
bool resumed() const noexcept
true when this delivery re-enters a sequence an earlier feed left open, rather than announcing a new ...
bool acceptsStringCapped(long dynCap) noexcept
acceptsString for a schema-unbounded element, under the receiver's max_dyn_string_len (§6....
bool pend_
A field at suspendDepth_ is half-delivered.
size_t spanCarry_
Bytes of the current top-level field consumed in earlier chunks (#26).
long elemDest_
The destination container's own capacity: InvalidArgument (§6.6.3).
bool readStringGated(S &value, long bound, long dynCap, Sizer sizer) noexcept
The body both string reads share, so the two cannot answer differently.
bool readBlob(B &value, long bound, Sizer sizer={}) noexcept
Read the current field as a blob, or skip it (§7.3).
Result feed(const uint8_t *buffer, size_t buflen) noexcept
Feed bytes into the decoder, delivering every complete top-level field.
Wire type_
Wire type of the field being delivered.
bool consumed_
Set once the callback has read the current field's value.
void dispatchLevel(Cb &&cb, bool stopAtEnd) noexcept
Entry
How a level is being entered (see levelEntry).
@ Descend
The suspended level is deeper: replay one more id.
@ Resume
This level is it: continue its half-delivered field.
@ Fresh
Nothing open here: parse the next field.
bool acceptsStringGated(long bound, long dynCap) noexcept
The body both string accepts share.
bool exceedsBufferAtHeader() noexcept
Would this field cross maxBufferedField_, judged from its header alone (#26)?
bool readArrayCapped(T &dst, long dynCap, ElemBound elem={}, Sizer sizer={}) noexcept
Read a schema-**unbounded** count-prefixed array under the receiver's max_dyn_array_count (§6....
Field
What beginField found at this level's next field.
@ Stop
The level is finished, suspended or refused.
@ SkipElem
§7.3 says it is not this array's element: skip, do not deliver.
void parseTopLevel() noexcept
Deliver every complete top-level field in the current window, leaving p_ at the first byte not consum...
bool tagMatches(Wire wantWire, Fix wantFix) noexcept
bool parseFieldTag() noexcept
Parse a field header word into fieldId_ and type_ (§4.3).
bool limitExceeded_
Category: a receiver-side limit was crossed (§6.2.1).
static bool skipVarint(const uint8_t *&p, const uint8_t *end, bool *overflow=nullptr) noexcept
Advance the cursor past one varint without decoding it (bounds-checked).
Fix fixType() const noexcept
Fixlen sub-type of the field currently being delivered.
void suspendHere(sofab::id fieldId, bool declined) noexcept
Record that this level's current field is the suspension point.
bool parseFieldHeader() noexcept
Parse one top-level field header plus the metadata that precedes its payload, into the current-field ...
void rejectUnbounded() noexcept
Refuse the current field because the call stated no bound for it at all (§6.3's InvalidArgument).
static bool getVarint(const uint8_t *&p, const uint8_t *end, uint64_t &out, bool *overflow=nullptr) noexcept
Read one base-128 varint, advancing the cursor (bounds-checked).
bool replay_
Re-descending pathId_ to reach suspendDepth_.
static bool arrayFixlenWordValid(uint64_t word) noexcept
Validate a ArrayFixlen element word (§4.8, §6.2).
void rejectDestination() noexcept
Refuse the current field because the caller's destination is too short for it (§6....
bool spanSkip_
Is the parse currently inside a skipped sequence subtree (§6.2.1, #129)?
size_t spanSkipped_
Bytes of the current top-level field spent on SKIPPED subtrees (§6.2.1, #129 one level down).
size_t pendCount_
That field's header, kept apart from the live type_ / fixLen_ / count_.
bool readString(S &value, long bound, Sizer sizer={}) noexcept
Read the current field as a string, or skip it (§7.3).
size_t announcedSize() const noexcept
The payload length the current field's header announces — a string/blob byte count,...
bool acceptsBlobCapped(long dynCap) noexcept
acceptsString for a schema-unbounded element, under the receiver's max_dyn_string_len (§6....
bool readBlobCapped(B &value, long dynCap, Sizer sizer={}) noexcept
Read the current field as a schema-**unbounded** blob under the receiver's max_dyn_blob_len (§6....
const uint8_t * end_
One past the last readable byte.
virtual void reset() noexcept
Drop every byte of decoder state, so the next feed starts a brand-new message.
IStreamImpl(const IStreamImpl &)=delete
bool argError_
Category: a well-formed value did not fit the destination the caller handed over (§6....
bool pendSkip_
...and it was declined, so skipPayload resumes it rather than the handler.
bool readArrayGated(T &dst, long schemaCount, long dynCap, ElemBound elem, Sizer sizer) noexcept
The body both array reads share.
size_t spannedLive() const noexcept
spanned less what this field spent on skipped subtrees — the number the field-span cap is measured ag...
bool exceedsBuffer(size_t consumed, uint64_t need) const noexcept
Would buffering this field cross maxBufferedField_?
static bool getVarintWindowed(const uint8_t *&p, uint64_t &out, bool *overflow) noexcept
Read one varint, given that a full varint window is in the buffer.
bool finishField(const uint8_t *fieldStart, const uint8_t *payload, sofab::id fieldId) noexcept
Settle a field the callback has been offered: skip it if the callback did not want it,...
bool readPayloadPiece(D &value, bool validateUtf8, size_t avail) noexcept
The chunk-straddling half of readPayload — deliver the piece that has arrived and remember how far th...
bool incomplete_
The field being delivered needs more bytes (§7 INCOMPLETE, not malformed).
Entry levelEntry() noexcept
Decide how this level is being entered, and clear the replay state once the suspended level is reache...
bool readBlobGated(B &value, long bound, long dynCap, Sizer sizer) noexcept
The body both blob reads share.
bool acceptsBlob(long bound) noexcept
The §7.3 and §7.1 decisions readString makes, taken before a destination exists.
uint32_t utf8State_
Incremental UTF-8 DFA state for the string payload in progress (§6.4.4).
bool readArray(T &dst, long schemaCount, ElemBound elem={}, Sizer sizer={}) noexcept
Read a count-prefixed native array, applying every receiver-side decision at the one word that decide...
size_t skipped_
§7.3 type-mismatch skips seen so far (skipped).
static bool fixlenWordValid(uint64_t word) noexcept
Validate a single Fixlen field's length-and-subtype word (§4.6, §6.2).
Fix pendFix_
That field's header, kept apart from the live type_ / fixLen_ / count_.
void closeLevel(bool stopAtEnd) noexcept
The bytes ran out with this sequence still open — INCOMPLETE, not malformed (§7).
bool pathSkip_[MAX_DEPTH+1]
That level was entered by skipPayload, not by a handler.
int elemFix_
§7.3 fixlen subtype for that element type (a Fix as int); -1 = the element type has none.
IStreamImpl(Limits limits) noexcept
Construct with the receiver's Limits; a derived class installs topCallback_.
sofab::id fieldId_
Id of the field being delivered.
static bool skipVarintWindowed(const uint8_t *&p, bool *overflow) noexcept
getVarintWindowed without building the value — see skipVarint.
static constexpr size_t CARRY_CAP
Widest prefix of a wire item that can outlive a chunk boundary, derived from this format's own consta...
Error terminal_
The stream's latched terminal verdict, or Error::None while the stream is still usable (§5....
size_t read(void *dst, size_t maxlen) noexcept
Read the current blob field into a caller buffer.
void exceedLimit() noexcept
Report a receiver-side decode-limit violation from inside a deliver callback.
long elemSchema_
Schema count N: an id at or past it is InvalidMessage (§7.1).
size_t pendLen_
That field's header, kept apart from the live type_ / fixLen_ / count_.
bool tagMatches(Wire wantWire) noexcept
The §7.3 seam: does the delivered field's wire tag match the one the caller's read declares?
bool roomFor(D &value, size_t need) noexcept
Is there room for need bytes in the destination the caller handed over (§6.6.3)?
Field beginField(bool stopAtEnd) noexcept
Parse the next field's header and metadata at a nested level, and apply every rule that is decided be...
static constexpr uint64_t CAP_NEED_MAX
Upper bound of any header-declared need (§6.2 ceilings).
int elemWire_
§7.3 wire type its elements must carry (a Wire as int); -1 = the collector decides the bound itself.
sofab::id pendId_
That field's header, kept apart from the live type_ / fixLen_ / count_.
static F loadFloat(const uint8_t *p) noexcept
Load a little-endian float or double from raw bytes.
IStreamImpl(IStreamImpl &&) noexcept=default
size_t count_
Element count of the current array field.
long elemBound_
The tightest armed element-index bound of the wrapper sequence being read (§5.1); -1 = none.
bool tagMatches(Wire wantWire, Fix wantFix, Fix wantFix2) noexcept
bool consumed() const noexcept
Input stream that delivers each top-level field to a user callback.
IStreamInline(fieldCallback callback, Limits limits) noexcept
Construct with the per-field callback and the receiver's decode limits.
std::function< void(sofab::id, size_t, size_t)> fieldCallback
Callback type invoked per top-level field as (fieldId, size, count).
Decoder that decodes into a message instance the CALLER owns.
IStreamInto(MessageType &message, Limits limits) noexcept
Bind message and route each top-level field into it.
Base class for user-defined messages that can deserialise themselves.
virtual void deserialize(IStreamImpl &istream, sofab::id id, size_t size, size_t count) noexcept=0
Consume one of this message's fields from istream.
virtual ~IStreamMessage()=default
Holds a message and routes decoded top-level fields into it.
IStreamObject(Limits limits) noexcept
Construct and route each top-level field into the wrapped message.
MessageType & operator*() noexcept
MessageType & operator->() noexcept
void reset() noexcept override
Reset the decoder and the wrapped message, ready for the next message.
const MessageType & operator->() const noexcept
const MessageType & operator*() const noexcept
Fixed-capacity, heap-free sequence of up to N elements of type T.
void push_back(T &&v) noexcept
Append v by move; dropped once at capacity N (see above).
InlineVector & operator=(std::initializer_list< T > init) noexcept
Replace the contents from a brace-enclosed list (clamped to N; extra elements are dropped).
static constexpr std::size_t capacity() noexcept
Maximum number of elements (the template parameter N).
std::size_t size_type
Size type (mirrors std::vector).
void push_back(const T &v) noexcept
Append a copy of v; once at capacity N, v is dropped.
T & operator[](std::size_t i) noexcept
Access the element at i (no bounds checking).
const T * begin() const noexcept
Const iterator to the first element.
bool empty() const noexcept
True if the sequence is empty.
T value_type
Element type (mirrors std::vector).
T * begin() noexcept
Iterator to the first element.
const T & back() const noexcept
Const reference to the last element.
void reserve(std::size_t) noexcept
No-op (inline storage never reallocates); present for API parity.
bool operator==(const InlineVector &o) const noexcept
Content equality (same logical length and elements).
void resize(std::size_t n) noexcept
Set the logical length to n, value-initializing what changes.
InlineVector() noexcept=default
Construct an empty sequence.
T & back() noexcept
Reference to the last element.
static constexpr std::size_t max_size() noexcept
Alias of capacity.
void clear() noexcept
Reset to an empty sequence (logical length only).
const T * data() const noexcept
Const pointer to the underlying storage.
const T & operator[](std::size_t i) const noexcept
Access the element at i (no bounds checking).
bool operator!=(const InlineVector &o) const noexcept
Negated operator==.
const T * end() const noexcept
Const iterator past the last element.
T & emplace_back() noexcept
Append a default-constructed element and return a reference to it.
T * end() noexcept
Iterator past the last element.
T * data() noexcept
Mutable pointer to the underlying storage.
std::size_t size() const noexcept
Number of elements currently stored.
InlineVector & assign(std::initializer_list< T > init) noexcept
Replace the contents from a brace-enclosed list (clamped to N; extra elements are dropped).
The held-back sequence run: ids of the innermost open sequences whose header has not been written yet...
void clear() noexcept
Forget the whole run (it has just been written out).
sofab::id operator[](size_t i) const noexcept
void pop() noexcept
Drop the innermost held-back id — its sequence got no content.
bool empty() const noexcept
size_t size() const noexcept
bool push(sofab::id v) noexcept
Hold back one more id (the new innermost open sequence).
Chainable result of a write operation.
Result sequenceEndKeep() noexcept
Chain a frame-keeping close (OStreamImpl::sequenceEndKeep).
Result write(sofab::id fieldId, const T &value) noexcept
Chain another field write onto the same stream.
Result writeIf(sofab::id fieldId, const T &value, bool condition) noexcept
Chain a field write that only happens when condition holds.
bool operator==(Error e) const noexcept
Result sequenceEnd() noexcept
Chain the closing of the current nested sub-message.
Result sequenceBeginLazy(sofab::id fieldId) noexcept
Chain the opening of a nested sub-message that is framed only if it turns out to have content (OStrea...
bool operator!=(Error e) const noexcept
Result writeLazy(sofab::id fieldId, const T &value) noexcept
Chain a nested-message field write that is omitted when the message is all-default (OStreamImpl::writ...
Error code() const noexcept
Base of the output streams: encodes values into a caller-provided buffer.
OStreamImpl() noexcept=default
Construct an unattached stream; a derived class must call initBuffer.
Result write(sofab::id fieldId, const void *value, int32_t size) noexcept
Write a raw byte blob field.
Error commitPending() noexcept
Write out the held-back sequence headers, outermost first.
Error error() const noexcept
The code behind ok, latched first-failure-wins.
Result sequenceEnd() noexcept
Close the most recently opened sub-message, letting it vanish if it received no content.
Result writeIf(sofab::id fieldId, const T &value, bool condition) noexcept
Write a field only when condition holds.
Error writeIntArray(sofab::id fieldId, std::span< const E > elems) noexcept
Write an array of integers as a count-prefixed run of varints.
bool installed_
Set by initBuffer, cleared right before a flush callback runs.
Error latch(Error e) noexcept
Record a failure in the sticky verdict and hand it straight back.
Result rejectArgument() noexcept
Refuse the value being encoded: latch Error::InvalidArgument.
Result write(sofab::id fieldId, const T &value) noexcept
Write a field, dispatching on the value's type.
flushCallback flushCallback_
Invoked when the buffer fills; may be empty.
static constexpr uint64_t fixlenWord(uint64_t len, Fix ft) noexcept
Compose a fixlen word: the payload length (or element size) in the high bits, the subtype in the low ...
const uint8_t * data() const noexcept
OStreamImpl(OStreamImpl &&) noexcept=default
Error pushByte(uint8_t b) noexcept
Append a single byte, flushing first if the buffer is full.
Error pushBytes(const uint8_t *data, size_t len) noexcept
Append a run of bytes.
size_t flush() noexcept
Hand any buffered bytes to the flush callback and rewind the cursor.
size_t bytesUsed() const noexcept
uint8_t * buffer_
Start of the active buffer.
OStreamImpl & operator=(const OStreamImpl &)=delete
Error putVarint(uint64_t v) noexcept
Encode a value as a varint and append it to the buffer.
Error writeFloatArray(sofab::id fieldId, std::span< const F > elems) noexcept
Write an array of floats or doubles as a count-prefixed fixlen array.
size_t seqDepth_
Number of currently-open nested sequences (§4.9 MAX_DEPTH).
Result sequenceEndKeep() noexcept
Close the most recently opened sub-message, keeping its frame even when it received no content.
size_t offset_
Start offset of the current installation (§5.1).
bool ok() const noexcept
Whether every write on this stream has succeeded.
static size_t encodeVarint(uint8_t *out, uint64_t v) noexcept
Encode an unsigned value as a base-128 varint.
static size_t encodeVarintPadded(uint8_t *out, uint64_t v) noexcept
Encode a varint into a destination with a full varint window.
static constexpr uint64_t headerWord(sofab::id fieldId, Wire w) noexcept
Compose a field header word: the id in the high bits, the wire type in the low three (§4....
uint8_t * end_
One past the end of the buffer.
Error putSequenceEnd() noexcept
Write the sequence-end marker (§4.9) — id 0, wire type 7.
OStreamImpl(const OStreamImpl &)=delete
Error beforeContent() noexcept
Commit any held-back sequence run before writing content.
Error writeFixlen(sofab::id fieldId, Fix ft, const uint8_t *data, size_t len) noexcept
Write a length-prefixed field (string, blob or other fixlen payload).
Error writeScalar(sofab::id fieldId, Wire type, uint64_t value) noexcept
Write a scalar field: header varint plus one value varint, in a single bulk write.
Result sequenceBeginLazy(sofab::id fieldId) noexcept
Open a nested sub-message whose header is held back until the sub-message turns out to have content.
uint8_t * cursor_
Current write position.
std::function< void(std::span< const uint8_t >)> flushCallback
Callback invoked with a span of finished bytes whenever the buffer flushes.
Result writeLazy(sofab::id fieldId, const T &value) noexcept
Write a nested message field, omitting it when it is all-default.
Error failure_
Sticky first failure of this stream (see ok, error).
void initBuffer(uint8_t *buffer, size_t buflen, size_t offset) noexcept
Point the stream at a buffer and position the write cursor.
Error writeFloatScalar(sofab::id fieldId, F value) noexcept
Write a single float or double as a little-endian fixlen field.
Output stream whose buffer is stored inline (the buffer costs no heap allocation).
OStreamInline() noexcept
Construct with no flush callback; overflow returns Error::BufferFull.
OStreamInline(flushCallback callback) noexcept
Construct with a flush callback.
Base class for user-defined messages that can serialise themselves.
virtual OStreamImpl::Result serialize(OStreamImpl &ostream) const noexcept=0
Write this message's fields into ostream.
Bundles a message with an inline output buffer sized for it.
OStreamObject() noexcept=default
Construct with no flush callback.
MessageType * operator->() noexcept
Reach the wrapped message, so its fields are obj->field.
OStreamImpl::Result serialize() noexcept
Serialise the wrapped message into the inline buffer and flush.
const MessageType * operator->() const noexcept
Reach the wrapped message, so its fields are obj->field.
Output stream over a buffer the caller already owns.
OStreamView(uint8_t *buffer, size_t buflen, size_t offset=0) noexcept
Construct over caller storage.
OStreamView(flushCallback callback, uint8_t *buffer, size_t buflen, size_t offset=0) noexcept
Construct over caller storage with a flush callback.
void setBuffer(uint8_t *buffer, size_t buflen, size_t offset=0) noexcept
Install a different caller buffer, mid-stream.
Output stream over a caller-supplied buffer whose lifetime is shared.
OStream() noexcept=default
Construct without a buffer; one must be set via setBuffer.
std::shared_ptr< uint8_t[]> getBuffer() noexcept
OStream(flushCallback callback, std::shared_ptr< uint8_t[]> buffer, size_t buflen, size_t offset=0) noexcept
Construct over a caller-supplied buffer with a flush callback.
std::shared_ptr< uint8_t[]> bufferOwner_
Caller storage, kept alive.
void setBuffer(std::shared_ptr< uint8_t[]> buffer, size_t buflen, size_t offset=0) noexcept
Install a buffer, mid-stream if need be (§5.1's buffer-set).
Constrains a serialisable message: derives from sofab::OStreamMessage and exposes a static constexpr ...
Give dst room for want, if it is a destination the caller has to size.
std::size_t utf8Prefix(std::string_view sv, std::size_t n) noexcept
Length of the longest prefix of sv that is at most n bytes and does not end inside a UTF-8 character;...
size_t arrayReach(const IStreamImpl &is) noexcept
Elements of the announced array the bytes in hand could still carry, clamped to the count itself.
constexpr uint32_t utf8Advance(uint32_t state, const uint8_t *d, size_t len) noexcept
Step the UTF-8 DFA over len bytes and return the state.
void storeLittleBits(uint8_t *out, U bits) noexcept
Store the object representation of a 4- or 8-byte value as little-endian bytes.
constexpr uint64_t gather7(uint64_t w) noexcept
Inverse of spread7: pack eight bytes' low 7 bits into one value.
constexpr uint32_t UTF8_REJECT
constexpr F bitsFloat(U bits) noexcept
Reconstruct a floating-point value from its raw bits.
constexpr uint8_t utf8Dfa[]
Validate that [data, data+len) is well-formed UTF-8.
bool seqIndexAdmitted(IStreamImpl &is, sofab::id id, long cap, long dynCap, long destCap) noexcept
Admit or refuse a wrapper-array element index, in §6.3's categories, before the container it indexes ...
Wire
Wire type stored in the low 3 bits of every field header.
@ ArrayUnsigned
Count-prefixed array of unsigned varints.
@ Fixlen
Length-prefixed payload (float, string or blob).
@ Signed
Signed integer, zig-zag encoded as a varint.
@ ArraySigned
Count-prefixed array of zig-zag varints.
@ Unsigned
Unsigned integer encoded as a varint.
@ ArrayFixlen
Count-prefixed array of fixed-size elements.
@ SequenceStart
Opens a nested sub-message.
@ SequenceEnd
Closes the most recently opened sub-message.
constexpr int64_t zigzagDecode(uint64_t u) noexcept
Inverse of zigzagEncode.
constexpr bool utf8Valid(const char *data, size_t len) noexcept
constexpr void destSetLen(D &d, size_t n) noexcept
Publish the decoded length in a destination that already had the room — the one container operation t...
constexpr size_t destRoom(const D &d) noexcept
Room a decode destination already holds — bytes for a payload, elements for an array (CORELIB_PLAN §6...
constexpr bool namesSeqContainer() noexcept
Whether a MessageSeq template argument names the destination container rather than the element type.
bool arrayTagMatches(const IStreamImpl &is) noexcept
Does the delivered tag match the array kind Elem declares (§7.3)?
typename WireInt< E >::type WireInt_t
Alias for WireInt.
void fitDest(D &dst, size_t want) noexcept
constexpr uint32_t UTF8_ACCEPT
The DFA's ACCEPT and REJECT states (see utf8Dfa).
constexpr long destCapacity() noexcept
The element ceiling a decode destination T publishes, or -1 when it publishes none.
constexpr uint64_t spread7(uint64_t v) noexcept
Spread the low 56 bits of v into eight 7-bit groups, one per byte.
void storeLittle64(uint8_t *out, uint64_t w) noexcept
Store a 64-bit word as eight little-endian bytes.
uint64_t loadLittle64(const uint8_t *in) noexcept
Load eight little-endian bytes as a 64-bit word (see storeLittle64).
constexpr size_t VARINT_MAX_BYTES
Widest base-128 varint: ceil(64/7) == 10 bytes (§4.1).
constexpr uint64_t zigzagEncode(int64_t v) noexcept
Map a signed integer to an unsigned one with the zig-zag scheme.
Fix
Sub-type of a length-prefixed (Fixlen) payload, stored in the low 3 bits of its length word.
@ Fp32
32-bit IEEE-754 float.
@ Fp64
64-bit IEEE-754 double.
@ Blob
Opaque byte string.
constexpr auto floatBits(F v) noexcept
Reinterpret a float/double as the unsigned integer holding its bits.
U loadLittleBits(const uint8_t *in) noexcept
Inverse of storeLittleBits.
DecodeStatus
Three-valued decode outcome of a sofab::IStreamImpl::feed call (spec §7).
@ LimitExceeded
A configured receiver-side limit (§6.2.1) was exceeded on a schema-**unbounded** field.
@ InvalidArgument
The value broke neither the schema bound nor a receiver cap, but does not fit the destination this ca...
@ Incomplete
Consumed bytes end inside a field or with an open sequence.
@ Invalid
Bytes are malformed regardless of what follows.
@ Complete
Consumed bytes end exactly at a field boundary — a valid message.
constexpr int API_VERSION
Version of the SofaBuffers public API implemented by this header.
constexpr size_t MIN_OUTPUT_BUFFER
Smallest output buffer this port accepts for streaming (§5.1).
bool readArray(IStreamImpl &is, T &dst, long schemaCount, ElemBound elem={}) noexcept
Read the current count-prefixed array into a destination this call sizes — the generated layer's IStr...
constexpr uint32_t FIXLEN_MAX
Largest fixlen payload byte-length (INT32_MAX).
constexpr bool always_false_v
Always-false trait used to trigger static_assert in the otherwise-unreachable branch of an if constex...
uint32_t id
Field identifier on the wire.
bool read(IStreamImpl &is, T &dst) noexcept
IStreamImpl::read with the destination sized first — the generated layer's untyped read.
bool readString(IStreamImpl &is, S &dst, long maxlen) noexcept
Read the current field as a string into a destination this call sizes — the generated layer's IStream...
constexpr int MAX_DEPTH
Maximum nested-sequence depth (§4.9).
bool readBlobCapped(IStreamImpl &is, B &dst, long dynCap) noexcept
The blob counterpart of sofab::readStringCapped.
constexpr uint32_t ID_MAX
Largest valid field id (INT32_MAX).
constexpr uint32_t ARRAY_MAX
Largest array element count (INT32_MAX).
bool readBlob(IStreamImpl &is, B &dst, long maxlen) noexcept
The blob counterpart of sofab::readString.
constexpr bool utf8_valid(std::string_view bytes) noexcept
Public UTF-8 validity primitive (spec CORELIB_PLAN §6.4).
Error
Status codes returned by the encode/decode API; None signals success.
@ BufferFull
Encode-only: the encoder ran out of room.
@ LimitExceeded
Decode-only: a receiver-configured cap (§6.2.1) was exceeded on a field the schema leaves unbounded —...
@ InvalidArgument
An argument was out of range (e.g.
@ Incomplete
Decode-only: the fed bytes end inside a field — a partial varint (§4.1), a fixlen/array payload short...
@ None
Operation succeeded (decode: COMPLETE, §7).
@ InvalidMessage
The input bytes are malformed (decode: INVALID, §7).
bool readStringCapped(IStreamImpl &is, S &dst, long dynCap) noexcept
The schema-unbounded sofab::readString: sizes dst only once the §6.2.1 receiver cap has admitted the ...
bool readArrayCapped(IStreamImpl &is, T &dst, long dynCap, ElemBound elem={}) noexcept
The schema-unbounded sofab::readArray: sizes dst only once the §6.2.1 receiver cap has admitted the c...
The blob counterpart of StringSeq; see it for the placement and bound rules.
long elemDynCap
The §6.2.1 receiver cap on one ELEMENT's length, or -1 when the caller supplied none.
BlobSeq(C &o, long capacity, long elemMax, long indexCap, long elemLenCap) noexcept
long dynCap
The configured receiver cap on the element index (max_dyn_array_count, §6.2.1); negative means none.
void prepare() noexcept
§7.4: the sequence IS the array's value, so a repeated field id replaces it whole.
void deserialize(IStreamImpl &is, sofab::id id, size_t size, size_t) noexcept override
Consume one of this message's fields from istream.
The value range a declared integer type admits (MESSAGE_SPEC §7.1).
int64_t lo
Smallest admissible value, inclusive.
int64_t hi
Largest admissible value, inclusive.
constexpr ElemBound() noexcept=default
bool armed
false: no bound — the decode is unchanged.
static constexpr ElemBound of() noexcept
The bound a declared element type E implies.
Decode fields at the current nesting level, firing cb for each.
void operator()(sofab::id id, size_t size, size_t count) const noexcept
void(* fn)(void *, sofab::id, size_t, size_t)
The one stream-scoped receiver cap: how many bytes a single top-level field may span.
size_t max_buffered_field
Cap on how many bytes a single top-level field may span, in bytes.
constexpr Limits(size_t maxBufferedField) noexcept
State the cap.
Collects a struct/union or nested-array wrapper sequence into the container it is handed.
void prepare() noexcept
§7.4 replace-whole, and absent ⇒ never called:
typename Container::value_type Elem
Element type — an IStreamMessage, or a container for a nested-array row.
std::conditional_t< detail::namesSeqContainer< A >(), A, std::vector< A > > Container
Destination container: A itself, or std::vector<A> for the element spelling.
void deserialize(IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override
Consume one of this message's fields from istream.
A message that both encodes and decodes: exactly OStreamMessage + IStreamMessage.
Collects a wrapper sequence whose elements are rows the stream cannot read on its own — a row that is...
long cap
Schema count N, or -1; an id at or past N is INVALID (§5.1/§7.1).
void prepare() noexcept
§7.4 replace-whole, and absent ⇒ never called:
Reader readRow
The row read (Reader).
long dynCap
The configured receiver cap on the element index (max_dyn_array_count, §6.2.1); negative means none.
RowSeq(C &o, long capacity, long indexCap, Reader reader={}) noexcept
C Container
Destination container.
typename C::value_type Elem
Row type: the container's element.
void deserialize(IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override
Consume one of this message's fields from istream.
Collects the elements of a string wrapper-sequence array.
StringSeq(C &o, long capacity, long elemMax, long indexCap, long elemLenCap) noexcept
long dynCap
The configured receiver cap on the element index (max_dyn_array_count, §6.2.1); negative means none.
long elemDynCap
The §6.2.1 receiver cap on one ELEMENT's length, or -1 when the caller supplied none.
void prepare() noexcept
§7.4: the sequence IS the array's value, so a repeated field id replaces it whole.
void deserialize(IStreamImpl &is, sofab::id id, size_t size, size_t) noexcept override
Consume one of this message's fields from istream.
fitDest as the sizer a typed read runs between its checks and its delivery, so the free reads below s...
void operator()(D &dst, size_t want) const noexcept
The "size nothing" sizer: what a typed read does with the caller's destination between its checks and...
constexpr void operator()(D &, size_t) const noexcept
std::underlying_type_t< E > type
The integer type an element travels as on the wire.