Skip to content

seal Buf trait and make dst() method unsafe for soundness and safety#8

Merged
cfcosta merged 1 commit intocfcosta:mainfrom
biryukovmaxim:main
Nov 30, 2025
Merged

seal Buf trait and make dst() method unsafe for soundness and safety#8
cfcosta merged 1 commit intocfcosta:mainfrom
biryukovmaxim:main

Conversation

@biryukovmaxim
Copy link
Contributor

Problem

The Buf trait was unsound. It allowed transmuting &mut [u8] to &mut [MaybeUninit<u8>] through a safe interface, which could be exploited to cause undefined behavior.

Solution

This PR makes the trait sound using the sealed trait pattern:

  1. private::Sealed - Empty trait in private module, implemented only for [u8] and [MaybeUninit<u8>]
  2. Buf: private::Sealed - Public trait requires the sealed trait, preventing external implementations
  3. unsafe fn dst() - Method marked unsafe with documented safety requirement: callers must only write initialized bytes
  4. Safety comments - Added at all call sites documenting why the invariant is upheld

Safety Guarantee

The library maintains the invariant that only fully initialized bytes are written through dst():

  • encode_to_buf writes through encode_simd_* and encode_scalar, all of which write initialized bytes
  • decode_to_buf writes through decode_into, which writes initialized bytes

@cfcosta cfcosta merged commit 99c3430 into cfcosta:main Nov 30, 2025
3 checks passed
@cfcosta
Copy link
Owner

cfcosta commented Nov 30, 2025

Sorry about the delay, have been traveling for the past few weeks. I'm back now :D

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.

2 participants