Skip to content

Leave parent unchanged if opening a submessage fails - #170

Open
kkaefer wants to merge 1 commit into
kk/known-size-submessagefrom
kk/open-submessage-failure
Open

kkaefer wants to merge 1 commit into
kk/known-size-submessagefrom
kk/open-submessage-failure

Conversation

@kkaefer

@kkaefer kkaefer commented Nov 18, 2026

Copy link
Copy Markdown
Member

If the buffer can't grow while the header of a submessage is written (e.g. a full fixed_size_buffer_adaptor), open_submessage() threw after having already written part of the field key and length. Since the submessage writer was never constructed, there was nothing to roll back, and the parent was left with a stray partial field.

This PR contains the following changes:

  • open_submessage() now removes the partially written header before rethrowing, so the parent is unchanged and can still be used.
  • The tutorial now mentions that the destructor of a submessage writer always commits, even if an exception is leaving its scope, and shows how to catch the exception and call rollback() instead. With Support rolling back submessages with known size #169, this also works for submessages opened with a known size.

I also looked into rolling back submessages automatically in the destructor if an exception is leaving its scope. However, this requires calling std::uncaught_exceptions() in every submessage destructor, which made the microbenchmark ~65% slower with GCC 13/libstdc++ on Linux (55 ms → 91 ms, ~12 ns per submessage) and ~17% slower with Apple clang/libc++. Since most users discard the entire buffer when encoding fails anyway, they'd pay this cost without any benefit. Additionally, it can't distinguish an exception leaving the scope of the writer from a writer used in a destructor during stack unwinding. Therefore, I think a documentation "fix" is the better alternative.

If the buffer can't grow while the header of a submessage is written
(e.g. a full fixed_size_buffer_adaptor), open_submessage() threw after
having already written part of the field key and length. The parent
then contained a stray partial field.

open_submessage() now removes the partially written header before
rethrowing, so the parent is unchanged and can still be used.

Also document in the tutorial that the destructor of a submessage
writer always commits, and how to roll back a submessage when an
exception is thrown while writing it.
@kkaefer
kkaefer requested a review from a team as a code owner November 18, 2026 13:17
@kkaefer
kkaefer requested a review from joto November 18, 2026 13:18
@kkaefer
kkaefer added this pull request to stack #171 November 18, 2026 13:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant