Handling Zero-Sized Types

It’s time. We’re going to fight the specter that is zero-sized types. Safe Rustnever needs to care about this, but Vec is very intensive on raw pointers andraw allocations, which are exactly the two things that care aboutzero-sized types. We need to be careful of two things:

  • The raw allocator API has undefined behavior if you pass in 0 for anallocation size.
  • raw pointer offsets are no-ops for zero-sized types, which will break ourC-style pointer iterator.

Thankfully we abstracted out pointer-iterators and allocating handling intoRawValIter and RawVec respectively. How mysteriously convenient.

Allocating Zero-Sized Types

So if the allocator API doesn’t support zero-sized allocations, what on earthdo we store as our allocation? Unique::empty() of course! Almost every operationwith a ZST is a no-op since ZSTs have exactly one value, and therefore no state needsto be considered to store or load them. This actually extends to ptr::read andptr::write: they won’t actually look at the pointer at all. As such we never needto change the pointer.

Note however that our previous reliance on running out of memory before overflow isno longer valid with zero-sized types. We must explicitly guard against capacityoverflow for zero-sized types.

Due to our current architecture, all this means is writing 3 guards, one in eachmethod of RawVec.

  1. impl<T> RawVec<T> {
  2. fn new() -> Self {
  3. // !0 is usize::MAX. This branch should be stripped at compile time.
  4. let cap = if mem::size_of::<T>() == 0 { !0 } else { 0 };
  5. // Unique::empty() doubles as "unallocated" and "zero-sized allocation"
  6. RawVec { ptr: Unique::empty(), cap: cap }
  7. }
  8. fn grow(&mut self) {
  9. unsafe {
  10. let elem_size = mem::size_of::<T>();
  11. // since we set the capacity to usize::MAX when elem_size is
  12. // 0, getting to here necessarily means the Vec is overfull.
  13. assert!(elem_size != 0, "capacity overflow");
  14. let align = mem::align_of::<T>();
  15. let (new_cap, ptr) = if self.cap == 0 {
  16. let ptr = heap::allocate(elem_size, align);
  17. (1, ptr)
  18. } else {
  19. let new_cap = 2 * self.cap;
  20. let ptr = heap::reallocate(self.ptr.as_ptr() as *mut _,
  21. self.cap * elem_size,
  22. new_cap * elem_size,
  23. align);
  24. (new_cap, ptr)
  25. };
  26. // If allocate or reallocate fail, we'll get `null` back
  27. if ptr.is_null() { oom() }
  28. self.ptr = Unique::new(ptr as *mut _);
  29. self.cap = new_cap;
  30. }
  31. }
  32. }
  33. impl<T> Drop for RawVec<T> {
  34. fn drop(&mut self) {
  35. let elem_size = mem::size_of::<T>();
  36. // don't free zero-sized allocations, as they were never allocated.
  37. if self.cap != 0 && elem_size != 0 {
  38. let align = mem::align_of::<T>();
  39. let num_bytes = elem_size * self.cap;
  40. unsafe {
  41. heap::deallocate(self.ptr.as_ptr() as *mut _, num_bytes, align);
  42. }
  43. }
  44. }
  45. }

That’s it. We support pushing and popping zero-sized types now. Our iterators(that aren’t provided by slice Deref) are still busted, though.

Iterating Zero-Sized Types

Zero-sized offsets are no-ops. This means that our current design will alwaysinitialize start and end as the same value, and our iterators will yieldnothing. The current solution to this is to cast the pointers to integers,increment, and then cast them back:

  1. impl<T> RawValIter<T> {
  2. unsafe fn new(slice: &[T]) -> Self {
  3. RawValIter {
  4. start: slice.as_ptr(),
  5. end: if mem::size_of::<T>() == 0 {
  6. ((slice.as_ptr() as usize) + slice.len()) as *const _
  7. } else if slice.len() == 0 {
  8. slice.as_ptr()
  9. } else {
  10. slice.as_ptr().offset(slice.len() as isize)
  11. }
  12. }
  13. }
  14. }

Now we have a different bug. Instead of our iterators not running at all, ouriterators now run forever. We need to do the same trick in our iterator impls.Also, our size_hint computation code will divide by 0 for ZSTs. Since we’llbasically be treating the two pointers as if they point to bytes, we’ll justmap size 0 to divide by 1.

  1. impl<T> Iterator for RawValIter<T> {
  2. type Item = T;
  3. fn next(&mut self) -> Option<T> {
  4. if self.start == self.end {
  5. None
  6. } else {
  7. unsafe {
  8. let result = ptr::read(self.start);
  9. self.start = if mem::size_of::<T>() == 0 {
  10. (self.start as usize + 1) as *const _
  11. } else {
  12. self.start.offset(1)
  13. };
  14. Some(result)
  15. }
  16. }
  17. }
  18. fn size_hint(&self) -> (usize, Option<usize>) {
  19. let elem_size = mem::size_of::<T>();
  20. let len = (self.end as usize - self.start as usize)
  21. / if elem_size == 0 { 1 } else { elem_size };
  22. (len, Some(len))
  23. }
  24. }
  25. impl<T> DoubleEndedIterator for RawValIter<T> {
  26. fn next_back(&mut self) -> Option<T> {
  27. if self.start == self.end {
  28. None
  29. } else {
  30. unsafe {
  31. self.end = if mem::size_of::<T>() == 0 {
  32. (self.end as usize - 1) as *const _
  33. } else {
  34. self.end.offset(-1)
  35. };
  36. Some(ptr::read(self.end))
  37. }
  38. }
  39. }
  40. }

And that’s it. Iteration works!