Is `AsMut<[T]>` stable across repeated calls?

Has anyone seen a real AsMut<[T]> implementation where repeated calls to as_mut() return slices with different addresses or lengths, even when no other &mut self method is called between them?

In other words, I expect this property:

As long as no other &mut self method on the object is called between calls,
as_mut() always returns a slice with the same address and length.

I've looked at https://doc.rust-lang.org/std/convert/trait.AsMut.html and haven't found such a statement.

Here is an example of code that:

  • relies on this contract, and
  • fails with a valid but surprising AsMut implementation.
//! Minimal example: code that is generic over `AsMut<[u8]>` silently
//! assumes that `as_mut()` is a pure view of the object's state.

use std::panic::{catch_unwind, AssertUnwindSafe};

/// Fills a buffer with the letter `x`, one byte at a time.
/// The constructor remembers the length, and `pos` is the next free index.
struct Filler<B: AsMut<[u8]>> {
    buf: B,
    pos: usize,
    len: usize,
}

impl<B: AsMut<[u8]>> Filler<B> {
    fn new(mut buf: B) -> Self {
        let len = buf.as_mut().len();
        Self { buf, pos: 0, len }
    }

    fn is_full(&self) -> bool {
        self.pos == self.len
    }

    fn put_x(&mut self) {
        // A second `as_mut()` call: the stored `pos` and `len` are applied
        // to whatever slice it returns now.
        self.buf.as_mut()[self.pos] = b'x';
        self.pos += 1;
    }

    /// Fill the whole buffer with `x` and give it back.
    fn fill(mut self) -> B {
        while !self.is_full() {
            self.put_x();
        }
        self.buf
    }
}

/// Well-behaved: the same as `Vec<u8>`, `[u8; N]`, `Box<[u8]>`, ...
struct Stable([u8; 4]);

impl AsMut<[u8]> for Stable {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Switches between two buffers: `as_mut()` has a side effect.
struct Flip {
    a: [u8; 4],
    b: [u8; 4],
    flip: bool,
}

impl AsMut<[u8]> for Flip {
    fn as_mut(&mut self) -> &mut [u8] {
        self.flip = !self.flip;
        if self.flip {
            &mut self.a
        } else {
            &mut self.b
        }
    }
}

/// Returns a shorter slice after the first call.
struct Shrinking {
    data: [u8; 4],
    calls: usize,
}

impl AsMut<[u8]> for Shrinking {
    fn as_mut(&mut self) -> &mut [u8] {
        self.calls += 1;
        if self.calls == 1 {
            &mut self.data
        } else {
            &mut self.data[..2]
        }
    }
}

fn main() {
    let mut stable = Filler::new(Stable([0; 4])).fill();
    println!("stable:    {:?}", stable.as_mut());

    // No panic, but the bytes are scattered over two buffers.
    let flip = Filler::new(Flip { a: [0; 4], b: [0; 4], flip: false }).fill();
    println!("flip:      a={:?} b={:?}", flip.a, flip.b);

    // Panics: index out of range, `len` is 4 but the slice has 2 bytes.
    let result = catch_unwind(AssertUnwindSafe(|| {
        Filler::new(Shrinking { data: [0; 4], calls: 0 }).fill();
    }));
    println!("shrinking: panicked = {}", result.is_err());
}

Running:

stable:    [120, 120, 120, 120]
flip:      a=[0, 120, 0, 120] b=[120, 0, 120, 0]

thread 'main' (456197) panicked at adversarial_asmut.rs:27:9:
index out of bounds: the len is 2 but the index is 2
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
shrinking: panicked = true

Your example shows that relying on such a property for soundness is clearly incorrect. And you've already determined that the documentation doesn't say it's logically necessary.

So what else are you looking for, exactly?

technically yes:

fn main() {
    let mut value = &mut [String::new()];
    let slice: &[String] = value.as_mut();
    println!("{slice:p}");
    let mut other_array = [String::new()];
    value = &mut other_array;
    let slice: &[String] = value.as_mut();
    // prints a different address even though we didn't call
    // any `&mut` methods other than `as_mut()` itself.
    println!("{slice:p}");
}

Your example shows that relying on such a property for soundness is clearly incorrect. And you've already determined that the documentation doesn't say it's logically necessary.

So what else are you looking for, exactly?

As sole mind, I can't understand what's wrong here: is AsMut under-specified because the expected behavior is so obvious that authors didn't even consider the adversarial behavior, or if I'm wrong about expected behavior.

I need the swarm intelligence to help to decide.

For now, I'm 99% for under-specification case. My sample AsMut implementations are clearly adversarial.

But there is still 1% that I'm overlooking a reasonable AsMut that doesn't fit to the desired contract. This is an open challenge, to find such.

    value = &mut other_array;
...
  // prints a different address even though we didn't call
  // any `&mut` methods other than `as_mut()` itself.

But we replaced value completely, it's another object.

The only possible use case I can think of for AsMut<[T]> returning stable address would be unsafe code. And since AsMut is not an unsafe trait, general rule that unsafe code shall never rely on safety invariants being upheld by safe code, should be used.

It'll be underspecified because most programs aren't adversarial.

In Rust, we tend not to care about adversarial trait implementation unless we're working with unsafe - in Safe Rust, the worst case that can happen due to an adversarial implementation is a logic bug, and we consider that the fault of the adversarial implementation, not the fault of the consumer.

Unsafe Rust flips that, to an extent; the unsafe superpowers allow you to have "spooky action at a distance", and so any time a trait implementation is relevant to your unsafe code, you need to assume that it's adversarial, but compliant with its safety guarantees if it includes unsafe itself.

In the case of AsMut, there are adversarial implementations that don't require unsafe internally, and so unsafe Rust can't depend on any arbitrary impl AsMut to be friendly - but safe Rust can (logic bug), and you can also depend on specific impl AsMut to be safe (e.g. you can depend on Vec, String and [T; N] implementations of AsMut, but not on arbitrary user-supplied AsMut).

Safety invariants wouldn't be upheld by arbitrary safe code, but, of course, you can mark some “known safe” implementation with the marker trait (either sealed or unsafe) and use these.

This is typical example of how Rust discussions waste everyone's time: usually programming experts who know other languages go ten step from “business case” where step 4 or step 5 is totally illogical and not permitted in Rust (like here: writing unsafe code that relies on some other arbitrary safe code that implements safe trait) and then faces problem at step 10. Then step 10 is presented without any history… this leads to week-long discussions and very often “other language expert” feels so strongly about the fact that step 4 have to be done in the exact way s/he likes (and not in a way compatible with Rust) that the whole discussion becomes pointless.

So… what are you actually trying to do that you need that question answered?

  • Unsafe code can't assume safe traits are implemented correctly, but safe code usually can.
  • The trait doesn't say the returned address is stable, so it may not always be stable
  • There's likely a implementation somewhere that has a genuine reason to change address and length upon repeated calls (e.g. if the value is behind a pointer that's atomically swapped with a different pointer by another thread)

Good catch.

So… what are you actually trying to do that you need that question answered?

I have a code conceptually similar to Filler. The code doesn't pass the code review because the reviewer (who is an AI agent) questions its correctness.

I shut it up by saying I know what I'm doing, but actually it's not the case. The finding is absolutely valid, and considering I'm writing a foundational code I have to address it. I had no idea what to do and hoped the swarm intelligence would help.

Yes. Now I know the answer.

The mentioning of unsafe and addresses looked wrong for me, but they helped to understand what does the code expect actually:

It is equality. All the code wants is that stored indexes and written bytes are still valid between calls.

Here is a sort of proof:

  • At time T1, the object contains the value v1.
  • After AsMut, the value m1 is equivalent to v1. (Should be postulated as an exiom.)
  • At time T2, the object contains the value v2. Because we didn't do mutable operations, v2 is equivalent to v1.
  • After AsMut, the value m2 is equivalent to v2.
  • By transitivity, m1 is equivalent to m2, exactly what the code expects.

I've reduced my need of a contract to two axioms, which don't need a proof. Internal mutability would break the second axiom, but it's a topic for another day.

Well you can add a new trait, maybe call it AsMutStable<T> that has the guarantees you want, AsMut<T> as a supertrait, and no methods,
implement it for applicable std types,
and now make the assumptions you wanted to make in safe code as long as the type implements AsMutStable<T>

Looks more similar to HashSet, if you will ask me.

And the HastSet supports the following invariant in that case; The behavior resulting from either logic error is not specified, but will be encapsulated to the HashMap that observed the logic error and not result in undefined behavior. This could include panics, incorrect results, aborts, memory leaks, and non-termination.

I recommend to consider similar restriction: make sure your code crashes in suitably visible way if given “bad” type, but ensure that there are no undefined behavior.

For my own sanity's sake: when talking about the "sole mind", the "AI reviewer" of yours, as well as the "swarm intelligence" you've alluded to several times now; are you speaking.. ironically?

As for the love of me, I'm having an extremely hard time processing the exact train of thought that might lead someone to so openly (if not brazenly) reduce the whole of the people inhabiting this forum, into some AI-rotten marketing-speak garbage like "swarm intelligence"; before asking for a chunk of their personal time, effort, knowledge, and experience to help you with an "issue" your token auto-completion LLM-wit (do these qualify as "intelligent" now?) pointed out for you.

The AsMut is a trait. A compile-time construct, erased entirely by the time your code ever gets a chance to run. The only method, whose existence the compiler is enforcing via the resolution of the type/trait system itself, is a plain fn as_mut(self: &mut [T]). It doesn't provide any way to guarantee that a given function pointer upholds any given contract: be it stability-wise or not.

Doing so would go against the "zero-cost abstraction" philosophy the language does its best to deliver, for one. No amount of documention-level "statements" per se can guarantee anything of the sort, for two. What is and isn't "obvious" and "adversarial" is as much a matter of personal preference as it is of opinion. I wouldn't be surprised if anyone ever writes something akin to:

use std::convert::{AsMut, AsRef};
use std::time::SystemTime as Time;

pub struct LastMut {
    inner: Vec<Time>,
}

impl LastMut {
    pub fn new() -> Self {
        let inner = Vec::new();
        Self { inner }
    }
    pub fn record(&mut self) {
        self.inner.push(Time::now());
    }
}

impl AsRef<[Time]> for LastMut {
    fn as_ref(&self) -> &[Time] {
        &self.inner
    }
}

impl AsMut<[Time]> for LastMut {
    fn as_mut(&mut self) -> &mut [Time] {
        self.record();
        &mut self.inner
    }
}

Every use-case is different. None gets a definite say on what is and isn't "expected" and/or "under/over-specified". Your "AI reviewer" has neither the "taste" nor any amount of any quality remotely approaching the human kind of "intelligence" to differentiate a bold-albeit-controversial choice you might yet have to make going forward; from a choice that doesn't align nearly as well with the bell-curve distribution of syntax comprising the data set it's been trained on. Both will be "wrong", and both will get "corrected" into the mindless, soulless, and statistically average.

On the side note: have you written enough Rust yourself up to this point, to be able to properly judge your AI reviewer's happy-go-lucky advice, to begin with? Or shall the "swarm intelligence" have to handle that for you as well, once your LLM advisor has given their final seal of approval?

If it helps, I believe @farnz answered your question thoroughly. In short, if you're not relying on this stability in unsafe code, then worrying about it should be unnecessary -- bad trait implementations will give bad behavior, i.e., logic bugs, but will not cause UB. If you think the stability is necessary, please explain why.

To be fair, this is only because the overwhelming majority of the time in other languages the discussion is simply never held at all: UB is an explanation for why a bug happened, not a problem to prevent before it becomes a bug.

Consider the equivalent discussion for an equivalent C++ pure virtual base class: I'm pretty sure the discussion would be essentially just arguing the semantics of what documentation even means, saying you should test your code with all implementations, or just a shrug "nothing is guaranteed"

At least in Rust the expectations are clear enough you can get a straightforward "you're exposing yourself to breaking changes in non-breaking version changes if you are depending on behavior that is not documented to be guaranteed" and a further warning that "for the purpose of unsafe code, safe traits don't guarantee anything other than a lack of UB, you need unsafe traits for that"

the "AI reviewer" ...

A detailed response to the statements around that could start a flame discussion, so let's skip it. If "AI" is uncomfortable, let's call it a "theorem prover" or a "formal verifier".

Meanwhile, I stumbled upon a similar topic with a similar lack of a concrete conclusion: "Are AsRef and Borrow supposed to be deterministic?", Are AsRef and Borrow supposed to be deterministic? - libs - Rust Internals

Thanks everyone for sharing thoughts! It was an interesting exercise to follow them.

And if you're in a "correct code through documentation" environment, Filler's documentation can explain what it requires from B's AsMut<[u8]> implementation, so that if a consumer of Filler provides an adversarial implementation, you can point to the documentation and say "that's your logic bug".

stable_deref_trait - Rust seems related

Be careful.

It may also be reducing us to a swarm of birds, boids, or even protozoa, so it does not necessarily have anything to do with AI.