# "If this field is zero then this other field must also be zero" annotations e.g. to create niches

**URL:** <https://internals.rust-lang.org/t/if-this-field-is-zero-then-this-other-field-must-also-be-zero-annotations-e-g-to-create-niches/24795>\
**Category:** Uncategorized\
**Created:** [November 8, 2026, 4:15pm UTC](https://internals.rust-lang.org/t/if-this-field-is-zero-then-this-other-field-must-also-be-zero-annotations-e-g-to-create-niches/24795 "2026-11-08T16:15:25Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![zackw](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/zackw/32/2071_2.png) [@zackw](https://internals.rust-lang.org/u/zackw)\
**Post date:** [November 8, 2026, 4:15pm UTC](https://internals.rust-lang.org/t/if-this-field-is-zero-then-this-other-field-must-also-be-zero-annotations-e-g-to-create-niches/24795/1 "2026-11-08T16:15:25Z")

</div>

[Make NonZero usable as Const param](https://internals.rust-lang.org/t/make-nonzero-usable-as-const-param/24793) is about something else but it got me thinking, what if we had a way to tell the compiler that if one field of a struct is zero then another field must also be zero? Or more generally, invariant relationships among fields?

```rust
#[invariant(val.is_null() == (len == 0))]
struct RawFatPointer<T> {
    val: *const T,
    len: usize,
}

```

(#[...] notation used just to illustrate, the syntax isn't the important part)

Now `RawFatPointer` has 2^sizeof(\*const T) niches, and I'm sure there's plenty of other interesting things the compiler could do with this information.

**EDIT:** Come to think of it, this is exactly the same concept as a multi-column CHECK constraint in SQL, isn't it? Only the SQL design goal is trapping data integrity errors as early as possible, rather than creating optimization opportunities (though I'm sure SQL query planners _do_ use CHECK constraints for optimization)

---

<div class="post-metadata">

**Author:** ![kpreid](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kpreid/32/8484_2.png) [@kpreid](https://internals.rust-lang.org/u/kpreid)\
**Post date:** [November 8, 2026, 4:42pm UTC](https://internals.rust-lang.org/t/if-this-field-is-zero-then-this-other-field-must-also-be-zero-annotations-e-g-to-create-niches/24795/2 "2026-11-08T16:42:19Z")

</div>

I think the most important question here is: how is this invariant enforced? Does writing an unacceptable value to the field panic? Is it `unsafe` to write to the field?

---

<div class="post-metadata">

**Author:** ![SkiFire13](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/skifire13/32/7579_2.png) [@SkiFire13](https://internals.rust-lang.org/u/SkiFire13)\
**Post date:** [November 8, 2026, 5:05pm UTC](https://internals.rust-lang.org/t/if-this-field-is-zero-then-this-other-field-must-also-be-zero-annotations-e-g-to-create-niches/24795/3 "2026-11-08T17:05:38Z")

</div>

It's not exactly a generic solution, but you can get those niches for `RawFatPointer` using the following type:

```rust
enum RawFatPointer<T> {
    Null,
    NonNull {
        val: core::ptr::NonNull<T>,
        len: core::num::NonZero<usize>,
    }
}

```

Edit: apparently the compiler cannot optimize this properly to use all niches, but in theory it should give it that information.

---

<div class="post-metadata">

**Author:** ![zackw](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/zackw/32/2071_2.png) [@zackw](https://internals.rust-lang.org/u/zackw)\
**Post date:** [November 8, 2026, 5:06pm UTC](https://internals.rust-lang.org/t/if-this-field-is-zero-then-this-other-field-must-also-be-zero-annotations-e-g-to-create-niches/24795/4 "2026-11-08T17:06:43Z")

</div>

I was thinking "it's unsafe to write to the field, except in cases where the compiler can prove that the write cannot possibly break the invariant", kinda like how `NonNull` works today. The challenge is of course pinning down how powerful we document the compiler's proofs to be.

I feel like "the compiler automatically inserts a `dbg_assert!` before each assignment" would _also_ be useful, but I'd want that to be an opt-in mode. You need to _know_ when you're electing to have assignments possibly panic.

---

<div class="post-metadata">

**Author:** ![Evian-Zhang](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/evian-zhang/32/12170_2.png) [@Evian-Zhang](https://internals.rust-lang.org/u/Evian-Zhang)\
**Post date:** [November 9, 2026, 11:49am UTC](https://internals.rust-lang.org/t/if-this-field-is-zero-then-this-other-field-must-also-be-zero-annotations-e-g-to-create-niches/24795/5 "2026-11-09T11:49:12Z")

</div>

This is much like the unsafe field proposal, except that that proposal does not mention how the compiler could be aware of the invariant.

Like the example given in the [design meeting notes](https://hackmd.io/@jswrenn/Bkp8l4BtJg?stext=4166%3A226%3A0%3A1794224930%3AK8XRcQ):

```rust
struct CacheArcCount<T> {
    // SAFETY: This `Arc`'s `ref_count` must equal the
    // value of the `ref_count` field.
    unsafe arc: Arc<T>,
    // SAFETY: See [`CacheArcCount::arc`].
    unsafe ref_count: usize,
}

```

---

<div class="post-metadata">

**Author:** ![zackw](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/zackw/32/2071_2.png) [@zackw](https://internals.rust-lang.org/u/zackw)\
**Post date:** [November 9, 2026, 2:25pm UTC](https://internals.rust-lang.org/t/if-this-field-is-zero-then-this-other-field-must-also-be-zero-annotations-e-g-to-create-niches/24795/6 "2026-11-09T14:25:50Z")

</div>

I thought some more about how to represent _checked_ updates and came up with this:

```rust
trait HasCheckedInvariants {
    fn try_update(&mut self, FnOnce(&mut Self) -> ())
        -> Result<(), InvariantBrokenError>;
}

```

The `try_update` callback gets a mutable reference to a _copy_ of the object, and can do whatever it wants to its fields. On exit, the invariants are all checked. If all are good, the changes are copied back to the original object and `try_update` returns `Ok`, otherwise the changes are discarded and it returns `Err`.

This could probably be prototyped in a library with some derive macros.

(Unsolved problem: what do you do if the object is too big to copy twice for each update, or has uncopyable fields?)

---

<div class="post-metadata">

**Author:** ![jdahlstrom](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jdahlstrom/32/3351_2.png) [@jdahlstrom](https://internals.rust-lang.org/u/jdahlstrom)\
**Post date:** [November 9, 2026, 3:10pm UTC](https://internals.rust-lang.org/t/if-this-field-is-zero-then-this-other-field-must-also-be-zero-annotations-e-g-to-create-niches/24795/7 "2026-11-09T15:10:54Z")

</div>

There’s also an ongoing design effort to add contract programming to Rust, including invariant annotations, but I don’t know what its status is.

> **Aside: C++26 Contracts**
>
> In an unprecedented turn of events, the C++26 DIS (Draft International Standard, the final draft that was to become the C++26 IS modulo editorial fixes) was just rejected by the ISO National Bodies in a vote that was supposed to be largely a formality. The reason, according to the opponents, is the Contracts feature which hasn’t exactly lacked in the controversy department over its many years of design effort. Luckily Rust is in many ways a better fit for contracts, design-wise.
