News for hackers. Stuff that matters.
Re:C++ vs. Rust Build Times by magicalhippo on Friday January 06, 2023 @09:08PM (#34284290)
For those of us less versed in Rust, from what I can gather the reason the provided Vec<Vec<T>> implementation works is that the Vec implementation guarantees[1] no reallocation happens when created with a sufficient capacity, and that the elements live in the heap. This means it's safe for the outer Vec to be reallocated.

That said, the pop implementation seems faulty in that it does not appear to deallocate empty chunks. Does Rust have any non-obvious magic here?

[1]: https://doc.rust-lang.org/std/vec/struct.Vec.html#guarantees

Re:C++ vs. Rust Build Times by orlp on Friday January 06, 2023 @09:41PM (#34284547)
> That said, the pop implementation seems faulty in that it does not appear to deallocate empty chunks. Does Rust have any non-obvious magic here?

No, the only magic here is my utter lack of testing for throwaway HN code :) A corrected implementation would be:

    pub fn pop(&mut self) -> Option<T> {
        let last = self.chunks.last_mut()?;
        let ret = last.pop()?;
        if last.is_empty() {
            self.chunks.pop();
        }
        Some(ret)
    }
This is only correct if we maintain the invariant that we do not keep any empty chunks around, but the rest of the implementation does not violate this.