Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 82 additions & 19 deletions include/sofab/sofab.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -743,13 +743,37 @@ namespace sofab
* what a schema means.
*/

namespace detail
{
/*!
* @brief Length of the longest prefix of @p sv that is at most @p n bytes
* and does not end inside a UTF-8 character; @p sv is longer
* than @p n.
*
* The over-long half of @ref FixedString's assignment-time clamp, one
* copy for every capacity: the cut moves back while the first byte left
* out is a continuation byte (10xxxxxx), so a valid UTF-8 @p sv keeps a
* valid UTF-8 prefix. The common case -- the value fits -- stays inline
* in @ref FixedString::assign, where a literal's length folds away.
*/
inline std::size_t utf8Prefix(std::string_view sv, std::size_t n) noexcept
{
while (n > 0 && (static_cast<unsigned char>(sv[n]) & 0xC0u) == 0x80u)
{
--n;
}
return n;
}
} // namespace detail

/*!
* @brief Fixed-capacity, heap-free string of up to @p N characters.
*
* A drop-in, embedded-friendly stand-in for @c std::string on both the encode
* and decode paths. The characters live in an inline @c std::array, so an
* instance allocates nothing, never throws (overflow clamps to @p N), and
* compiles cleanly under @c -fno-exceptions / @c -fno-rtti. The buffer never
* instance allocates nothing, never throws (an over-long value is clamped to
* @p N bytes at a UTF-8 character boundary, see @ref assign), and compiles
* cleanly under @c -fno-exceptions / @c -fno-rtti. The buffer never
* moves, so an instance stays a valid decode destination across every
* @ref IStreamImpl::feed chunk.
*
Expand Down Expand Up @@ -787,7 +811,7 @@ namespace sofab
FixedString() noexcept = default;

/*!
* @brief Construct from a NUL-terminated C string (truncated to @p N).
* @brief Construct from a NUL-terminated C string (clamped to @p N, see @ref assign).
* @param s Source string, or @c nullptr for an empty string.
*/
FixedString(const char *s) noexcept
Expand All @@ -796,7 +820,7 @@ namespace sofab
}

/*!
* @brief Construct from a string view (truncated to @p N).
* @brief Construct from a string view (clamped to @p N, see @ref assign).
* @param sv Source characters (may contain embedded NULs).
*/
FixedString(std::string_view sv) noexcept
Expand All @@ -813,35 +837,43 @@ namespace sofab
assign(std::string_view{s});
}

/*! @brief Assign from a NUL-terminated C string (truncated to @p N). */
/*! @brief Assign from a NUL-terminated C string (clamped to @p N, see @ref assign). */
FixedString &operator=(const char *s) noexcept
{
assign(s ? std::string_view{s} : std::string_view{});
return *this;
}

/*! @brief Assign from a string view (truncated to @p N). */
/*! @brief Assign from a string view (clamped to @p N, see @ref assign). */
FixedString &operator=(std::string_view sv) noexcept
{
assign(sv);
return *this;
}

/*! @brief Assign from a @c std::string (truncated to @p N). */
/*! @brief Assign from a @c std::string (clamped to @p N, see @ref assign). */
FixedString &operator=(const std::string &s) noexcept
{
assign(std::string_view{s});
return *this;
}

/*!
* @brief Replace the contents with @p sv, truncated to @p N characters.
* @brief Replace the contents with @p sv, clamped to @p N bytes.
*
* The assignment-time clamp is a documented contract of the static
* storage (the generator's `allow_dynamic: false`): a value longer than
* @p N is cut, not refused, before any encoder sees it. The cut never
* lands inside a UTF-8 character -- it moves back to the start of the
* character that would not fit whole, so the kept prefix is valid UTF-8
* whenever @p sv is.
*
* @param sv Source characters (may contain embedded NULs).
* @return Reference to @c *this.
*/
FixedString &assign(std::string_view sv) noexcept
{
len_ = sv.size() > N ? N : sv.size();
len_ = sv.size() <= N ? sv.size() : detail::utf8Prefix(sv, N);
for (std::size_t i = 0; i < len_; ++i)
{
buf_[i] = sv[i];
Expand Down Expand Up @@ -985,7 +1017,7 @@ namespace sofab
FixedBytes() noexcept = default;

/*!
* @brief Construct from a brace-enclosed list of bytes (truncated to @p N).
* @brief Construct from a brace-enclosed list of bytes (clamped to @p N; extra bytes are dropped).
*
* Providing this constructor makes @c FixedBytes a non-aggregate, so a
* brace-init such as @c b = {1, 2, 3} routes through here and sets
Expand All @@ -999,13 +1031,13 @@ namespace sofab
assign(init);
}

/*! @brief Replace the contents from a brace-enclosed list (truncated to @p N). */
/*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra bytes are dropped). */
FixedBytes &operator=(std::initializer_list<std::uint8_t> init) noexcept
{
return assign(init);
}

/*! @brief Replace the contents from a brace-enclosed list (truncated to @p N). */
/*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra bytes are dropped). */
FixedBytes &assign(std::initializer_list<std::uint8_t> init) noexcept
{
len_ = 0;
Expand Down Expand Up @@ -1138,7 +1170,7 @@ namespace sofab
InlineVector() noexcept = default;

/*!
* @brief Construct from a brace-enclosed list of elements (truncated to @p N).
* @brief Construct from a brace-enclosed list of elements (clamped to @p N; extra elements are dropped).
*
* The presence of this constructor makes @c InlineVector a non-aggregate:
* @c v = {a, b, c} routes here and sets @ref size, instead of aggregate
Expand All @@ -1151,13 +1183,13 @@ namespace sofab
assign(init);
}

/*! @brief Replace the contents from a brace-enclosed list (truncated to @p N). */
/*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra elements are dropped). */
InlineVector &operator=(std::initializer_list<T> init) noexcept
{
return assign(init);
}

/*! @brief Replace the contents from a brace-enclosed list (truncated to @p N). */
/*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra elements are dropped). */
InlineVector &assign(std::initializer_list<T> init) noexcept
{
len_ = 0;
Expand Down Expand Up @@ -1239,10 +1271,17 @@ namespace sofab
return buf_[i];
}

/*! @brief Append a copy of @p v (no-op growth once at capacity @p N). */
void push_back(const T &v) noexcept { emplace_back() = v; }
/*! @brief Append @p v by move (no-op growth once at capacity @p N). */
void push_back(T &&v) noexcept { emplace_back() = static_cast<T &&>(v); }
/*!
* @brief Append a copy of @p v; once at capacity @p N, @p v is dropped.
*
* The assignment-time clamp of the static storage: elements past @p N
* are left out and the ones already held are kept, so a filled container
* holds the first @p N values it was given. (@ref emplace_back, the
* decode-side binder, reuses the last slot instead.)
*/
void push_back(const T &v) noexcept { if (len_ < N) buf_[len_++] = v; }
/*! @brief Append @p v by move; dropped once at capacity @p N (see above). */
void push_back(T &&v) noexcept { if (len_ < N) buf_[len_++] = static_cast<T &&>(v); }

/*! @brief Reference to the last element. */
T &back() noexcept { return buf_[len_ - 1]; }
Expand Down Expand Up @@ -2159,6 +2198,30 @@ namespace sofab
*/
[[nodiscard]] Error error() const noexcept { return failure_; }

/**
* @brief Refuse the value being encoded: latch @ref Error::InvalidArgument.
*
* The hook a generated `serialize()` calls when a field's value is past
* a bound only the schema knows -- a string or blob longer than its
* `maxlen`, an array with more elements than its `count`. The corelib
* holds no schema bound; it records the refusal, so that @ref ok and
* @ref error report it exactly like its own §6.2 / §6.4 refusals and no
* byte of the message is returned as a success (§5.1). Writes nothing
* itself. The encode-side counterpart of IStreamImpl::invalidate.
*
* Cold and out of line: the refusal is the rare path, and keeping it
* out of a generated serialize() keeps that function small enough for
* GCC to go on inlining the writes into it (measured: the bench
* schema's encode is 11546 Ir/op with this, 12423 with the hook
* inlined at its 18 call sites, 11904 before any guard existed).
*
* @return A Result carrying @ref Error::InvalidArgument.
*/
[[gnu::cold, gnu::noinline]] Result rejectArgument() noexcept
{
return Result{*this, latch(Error::InvalidArgument)};
}

/**
* @brief Write a field, dispatching on the value's type.
*
Expand Down
111 changes: 111 additions & 0 deletions test/test_roundtrip.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8822,6 +8822,116 @@ static void rowSeqCollector()
}
}

/* --- the encode-side bound refusal and the static storage's clamp ----------
*
* generator#656. A value past a bound only the schema knows (a string's
* `maxlen`, an array's `count`) is refused at encode by the generated code,
* which calls OStreamImpl::rejectArgument: the corelib holds no bound, it only
* latches InvalidArgument so the verdict reports it and nothing more is
* written. The static storage (FixedString / FixedBytes / InlineVector) clamps
* at ASSIGNMENT instead, by contract: the first N bytes or elements are kept,
* the rest is dropped, and a string is never cut inside a UTF-8 character. --- */

/* A message whose serialize() refuses its value the way generated code does. */
struct RefusingMsg : sofab::Message
{
std::string s;
sofab::OStreamImpl::Result serialize(sofab::OStreamImpl &os) const noexcept override
{
(void)os.write(0, uint64_t{1});
if (s.size() > 4) { return os.rejectArgument(); }
return os.write(1, std::string_view{s});
}
void deserialize(sofab::IStreamImpl &, sofab::id, size_t, size_t) noexcept override {}
};

static void encodeBoundRefusalAndAssignmentClamp()
{
/* rejectArgument: the Result and the stream verdict both say InvalidArgument,
* and a condemned stream writes nothing more. */
{
sofab::OStreamInline<64> os;
(void)os.write(sofab::id(1), uint64_t{1});
const size_t before = os.bytesUsed();
auto r = os.rejectArgument();
CHECK(!r.ok() && r == sofab::Error::InvalidArgument && r.code() == sofab::Error::InvalidArgument,
"rejectArgument: the Result carries InvalidArgument");
CHECK(!os.ok() && os.error() == sofab::Error::InvalidArgument,
"rejectArgument: the stream verdict latches InvalidArgument");
CHECK(os.bytesUsed() == before, "rejectArgument: the refusal itself writes nothing");
(void)os.write(sofab::id(2), uint64_t{2});
CHECK(!os.ok() && os.error() == sofab::Error::InvalidArgument,
"rejectArgument: a later healthy write does not clear the verdict");
}
/* First failure wins: a refusal after an overflow keeps BufferFull. */
{
sofab::OStreamInline<2> os;
(void)os.write(sofab::id(1), std::string_view("too long for two bytes"));
CHECK(os.error() == sofab::Error::BufferFull, "rejectArgument control: the overflow latched first");
auto r = os.rejectArgument();
CHECK(r == sofab::Error::InvalidArgument && os.error() == sofab::Error::BufferFull,
"rejectArgument: the first latched failure is kept");
}
/* Through a message: the refused message encodes to nothing as a success,
* the one at its bound encodes. */
{
RefusingMsg m;
m.s = "abcde";
sofab::OStreamInline<64> os;
auto r = m.serialize(os);
CHECK(!r.ok() && !os.ok() && os.error() == sofab::Error::InvalidArgument,
"rejectArgument: a refusing serialize() fails the whole encode");
m.s = "abcd";
sofab::OStreamInline<64> ok;
const bool done = m.serialize(ok).ok();
CHECK(done && ok.ok() &&
toHex(std::span<const uint8_t>(ok.data(), ok.bytesUsed())) == "0001" "0a2261626364",
"rejectArgument control: a value at its bound encodes");
}

/* FixedString: clamp to N bytes, at a character boundary. */
{
sofab::FixedString<4> a{"xxxxx"};
CHECK(a.view() == "xxxx", "FixedString clamp: ASCII is cut at N bytes");
sofab::FixedString<4> b{"xxx\xC3\xA9"}; /* xxx + U+00E9 */
CHECK(b.view() == "xxx" && b.size() == 3 && b.c_str()[3] == '\0',
"FixedString clamp: a 2-byte character that would straddle N is left out whole");
sofab::FixedString<4> c{std::string("\xC3\xA9\xC3\xA9\xC3\xA9")};
CHECK(c.view() == "\xC3\xA9\xC3\xA9", "FixedString clamp: whole characters up to N are kept");
sofab::FixedString<4> d;
d = std::string_view("a\xF0\x9F\x98\x80"); /* a + U+1F600 */
CHECK(d.view() == "a", "FixedString clamp: a 4-byte character is left out whole");
sofab::FixedString<5> e{"a\xF0\x9F\x98\x80"};
CHECK(e.size() == 5, "FixedString clamp control: a value at N bytes is kept whole");
sofab::FixedString<3> f{"\xF0\x9F\x98\x80"};
CHECK(f.empty() && f.c_str()[0] == '\0', "FixedString clamp: nothing fits, nothing is kept");
sofab::FixedString<2> g{"a\xE2\x82\xAC"}; /* a + U+20AC, 3 bytes */
CHECK(g.view() == "a", "FixedString clamp: a 3-byte character is left out whole");
sofab::FixedString<4> h;
h = std::string("ab");
h = "\xC3\xA9xyz";
CHECK(h.view() == "\xC3\xA9xy", "FixedString clamp: a boundary right at N keeps the cut there");
}
/* InlineVector / FixedBytes: the first N are kept, the rest dropped. */
{
sofab::InlineVector<uint32_t, 3> v;
for (uint32_t x : {1u, 2u, 3u, 4u, 5u}) v.push_back(x);
CHECK(v.size() == 3 && v[0] == 1 && v[1] == 2 && v[2] == 3,
"InlineVector clamp: push_back past N drops the value, the held ones stay");
sofab::InlineVector<sofab::FixedString<4>, 3> t;
for (const char *x : {"a", "b", "c", "d"}) t.push_back(sofab::FixedString<4>{x});
const sofab::FixedString<4> keep{"zz"};
t.push_back(keep);
CHECK(t.size() == 3 && t[2].view() == "c",
"InlineVector clamp: push_back (move and copy) past N keeps the last held element");
sofab::InlineVector<uint16_t, 2> w{7, 8, 9};
CHECK(w.size() == 2 && w[1] == 8, "InlineVector clamp: an over-long list keeps its first N");
sofab::FixedBytes<4> b{1, 2, 3, 4, 5};
for (int i = 0; i < 3; ++i) b.push_back(9);
CHECK(b.size() == 4 && b.data()[3] == 4, "FixedBytes clamp: bytes past N are dropped");
}
}

int main()
{
encodeVectors();
Expand Down Expand Up @@ -8866,6 +8976,7 @@ int main()
skippedSubtreeSuspendsBound();
truncatedNestedFieldIsNotDeclined();
heapFreeStorage();
encodeBoundRefusalAndAssignmentClamp();
allocationMeasurement();
destinationReuse();
varintWidthSweep();
Expand Down
Loading