Push and Pop
To do the write we have to be careful not to evaluate the memory we want to writeto. At worst, it’s truly uninitialized memory from the allocator. At best it’s thebits of some old value we popped off. Either way, we can’t just index to the memoryand dereference it, because that will evaluate the memory as a valid instance ofT. Worse, foo[idx] = x
will try to call drop
on the old value of foo[idx]
!
For push
, if the old len (before push was called) is 0, then we want to writeto the 0th index. So we should offset by the old len.
For pop
, if the old len is 1, we want to read out of the 0th index. So weshould offset by the new len.
pub fn pop(&mut self) -> Option<T> {
if self.len == 0 {
self.len -= 1;
Some(ptr::read(self.ptr.offset(self.len as isize)))
}