Skip to content

Support rolling back submessages with known size - #169

Open
kkaefer wants to merge 1 commit into
masterfrom
kk/known-size-submessage
Open

kkaefer wants to merge 1 commit into
masterfrom
kk/known-size-submessage

Conversation

@kkaefer

@kkaefer kkaefer commented Nov 18, 2026

Copy link
Copy Markdown
Member

When a submessage is opened with a known size (e.g. packed_field_fixed32 field{pw, 1, 2}), open_submessage() stored the size_is_known sentinel in m_rollback_pos instead of the actual rollback position. This means that calling rollback() on such a submessage failed an assert in debug builds. In release builds, it called resize(SIZE_MAX) on the buffer, which threw std::length_error and left a partially written field behind. Neither the rollback() docs nor the tutorial mention this limitation.

Additionally, we didn't check that exactly size bytes were written to such a submessage. Writing too few or too many bytes silently produced a broken message, even in debug builds.

This PR contains the following changes to address the issues:

  • m_rollback_pos now always holds the actual rollback position. Submessages with a known size are marked by setting its top bit (known_size_flag). I think we can safely do that because buffer positions never get that large.
  • The length of such a submessage is already written when it's opened, so we don't need the position where its data starts later on. Instead, m_pos now holds the position where the data must end, and close_submessage() asserts that the promised number of bytes was written.
  • New tests for rolling back packed fields and submessages with known size, and for committing them with too few/too many bytes.

Opening a submessage with a known size (e.g. packed_field_fixed32 with
a size argument) stored a sentinel instead of the rollback position, so
rollback() failed an assert in debug builds and threw std::length_error
in release builds, leaving a partially written field in the buffer.

Keep the real rollback position in m_rollback_pos and mark submessages
with a known size with a flag bit instead. For these submessages, m_pos
now holds the position where the data must end, so closing them can
assert that exactly the promised number of bytes was written. The
writer doesn't get any bigger.
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