Skip to content

hardening: mark decode_fixed_vec_le as unsafe#19

Open
MegaRedHand wants to merge 7 commits into
mainfrom
hardening/decode-fixed-vec-le-safety
Open

hardening: mark decode_fixed_vec_le as unsafe#19
MegaRedHand wants to merge 7 commits into
mainfrom
hardening/decode-fixed-vec-le-safety

Conversation

@MegaRedHand

@MegaRedHand MegaRedHand commented Mar 31, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR marks decode_fixed_vec_le as unsafe, documenting the safety and correctness requirements, which were already upheld. It also removes the second parameter, since it could be computed inside the function, and doing so simplifies safety requirements.

The reason the function is unsafe is only because some types have invalid values, which can be represented in the raw byte format, but don't really have a representable value in the type. See "Producing invalid values" in the Rustonomicon

For example, bool can only be true or false, which are 1 and 0, respectively. However, interpreting an arbitrary byte (bool has a size of 1 byte) as a bool could result in interpreting unrepresentable values like 2, `3, etc.

Compute size_of::<T>() inside the function instead of taking it as a
parameter. This makes a size mismatch impossible by construction,
replacing the debug_assert added in the previous commit.
Split into a doc-level safety contract (what callers must uphold)
and a block-level SAFETY comment (why the operations are sound).
The function has a safety contract that the type system cannot enforce
(T must have no padding and be valid for any bit pattern), so callers
should explicitly acknowledge it via an unsafe block.
Split the doc comment into a Safety section (valid-for-any-bit-pattern,
the actual soundness requirement) and a Correctness section (little-endian
layout, enforced by cfg).
Split the doc comment into a Safety section (valid-for-any-bit-pattern,
the actual soundness requirement) and a Correctness section (little-endian
layout, enforced by cfg).
@MegaRedHand MegaRedHand changed the title hardening: add debug_assert and safety comment to decode_fixed_vec_le hardening: mark decode_fixed_vec_le as unsafe Mar 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants