Skip to content

Commit ceb33e9

Browse files
authored
Rollup merge of #149061 - jdonszelmann:fixed-size-encoding-assert, r=oli-obk
debug-assert FixedSizeEncoding invariant Something like this? It asserts during encoding that for that type, decoding 0 would give the default. Preferably, I'd either somehow statically/in const assert it once, instead of every time, but I see no easy way to do so. It'd require us to iterate all types that implement the trait or something. Let me know what you think No types currently violate this invariant. r? `@oli-obk`
2 parents 5d24303 + d1bcf2e commit ceb33e9

File tree

1 file changed

+10
-1
lines changed
  • compiler/rustc_metadata/src/rmeta

1 file changed

+10
-1
lines changed

compiler/rustc_metadata/src/rmeta/table.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,10 @@ impl IsDefault for UnusedGenericParams {
5555

5656
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
5757
/// Used mainly for Lazy positions and lengths.
58-
/// Unchecked invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
58+
///
59+
/// Invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
5960
/// but this has no impact on safety.
61+
/// In debug builds, this invariant is checked in `[TableBuilder::set]`
6062
pub(super) trait FixedSizeEncoding: IsDefault {
6163
/// This should be `[u8; BYTE_LEN]`;
6264
/// Cannot use an associated `const BYTE_LEN: usize` instead due to const eval limitations.
@@ -432,6 +434,13 @@ impl<I: Idx, const N: usize, T: FixedSizeEncoding<ByteArray = [u8; N]>> TableBui
432434
/// arises in the future then a new method (e.g. `clear` or `reset`) will need to be introduced
433435
/// for doing that explicitly.
434436
pub(crate) fn set(&mut self, i: I, value: T) {
437+
#[cfg(debug_assertions)]
438+
{
439+
debug_assert!(
440+
T::from_bytes(&[0; N]).is_default(),
441+
"expected all-zeroes to decode to the default value, as per the invariant of FixedSizeEncoding"
442+
);
443+
}
435444
if !value.is_default() {
436445
// FIXME(eddyb) investigate more compact encodings for sparse tables.
437446
// On the PR @michaelwoerister mentioned:

0 commit comments

Comments
 (0)