Deref

Alright! We’ve got a decent minimal stack implemented. We can push, we canpop, and we can clean up after ourselves. However there’s a whole mess offunctionality we’d reasonably want. In particular, we have a proper array, butnone of the slice functionality. That’s actually pretty easy to solve: we canimplement Deref<Target=[T]>. This will magically make our Vec coerce to, andbehave like, a slice in all sorts of conditions.

All we need is slice::from_raw_parts. It will correctly handle empty slicesfor us. Later once we set up zero-sized type support it will also Just Workfor those too.

  1. use std::ops::Deref;
  2. impl<T> Deref for Vec<T> {
  3. type Target = [T];
  4. fn deref(&self) -> &[T] {
  5. unsafe {
  6. ::std::slice::from_raw_parts(self.ptr.as_ptr(), self.len)
  7. }
  8. }
  9. }

And let’s do DerefMut too:

  1. use std::ops::DerefMut;
  2. impl<T> DerefMut for Vec<T> {
  3. fn deref_mut(&mut self) -> &mut [T] {
  4. unsafe {
  5. ::std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len)
  6. }
  7. }
  8. }

Now we have len, first, last, indexing, slicing, sorting, iter,iter_mut, and all other sorts of bells and whistles provided by slice. Sweet!