RawVec(RawVec)

我们实际上已经达到了一个有趣的情况:我们已经复制了用于指定缓冲区并在Vec和IntoIter中释放其内存的逻辑.现在我们已经实现了它并确定了 实际的(actual) 逻辑复制,现在是执行一些逻辑压缩的好时机.

我们将抽象出(ptr, cap)对并给它们分配,增长和释放的逻辑:

  1. struct RawVec<T> {
  2. ptr: NonNull<T>,
  3. cap: usize,
  4. _marker: PhantomData<T>,
  5. }
  6. unsafe impl<T: Send> Send for RawVec<T> {}
  7. unsafe impl<T: Sync> Sync for RawVec<T> {}
  8. impl<T> RawVec<T> {
  9. fn new() -> Self {
  10. assert!(mem::size_of::<T>() != 0, "TODO: implement ZST support");
  11. RawVec {
  12. ptr: NonNull::dangling(),
  13. cap: 0,
  14. _marker: PhantomData,
  15. }
  16. }
  17. fn grow(&mut self) {
  18. let (new_cap, new_layout) = if self.cap == 0 {
  19. (1, Layout::array::<T>(1).unwrap())
  20. } else {
  21. // This can't overflow because we ensure self.cap <= isize::MAX.
  22. let new_cap = 2 * self.cap;
  23. // Layout::array checks that the number of bytes is <= usize::MAX,
  24. // but this is redundant since old_layout.size() <= isize::MAX,
  25. // so the `unwrap` should never fail.
  26. let new_layout = Layout::array::<T>(new_cap).unwrap();
  27. (new_cap, new_layout)
  28. };
  29. // Ensure that the new allocation doesn't exceed `isize::MAX` bytes.
  30. assert!(new_layout.size() <= isize::MAX as usize, "Allocation too large");
  31. let new_ptr = if self.cap == 0 {
  32. unsafe { alloc::alloc(new_layout) }
  33. } else {
  34. let old_layout = Layout::array::<T>(self.cap).unwrap();
  35. let old_ptr = self.ptr.as_ptr() as *mut u8;
  36. unsafe { alloc::realloc(old_ptr, old_layout, new_layout.size()) }
  37. };
  38. // If allocation fails, `new_ptr` will be null, in which case we abort.
  39. self.ptr = match NonNull::new(new_ptr as *mut T) {
  40. Some(p) => p,
  41. None => alloc::handle_alloc_error(new_layout),
  42. };
  43. self.cap = new_cap;
  44. }
  45. }
  46. impl<T> Drop for RawVec<T> {
  47. fn drop(&mut self) {
  48. if self.cap != 0 {
  49. let layout = Layout::array::<T>(self.cap).unwrap();
  50. unsafe {
  51. alloc::dealloc(self.ptr.as_ptr() as *mut u8, layout);
  52. }
  53. }
  54. }
  55. }

并改变Vec如下:

  1. pub struct Vec<T> {
  2. buf: RawVec<T>,
  3. len: usize,
  4. }
  5. impl<T> Vec<T> {
  6. fn ptr(&self) -> *mut T {
  7. self.buf.ptr.as_ptr()
  8. }
  9. fn cap(&self) -> usize {
  10. self.buf.cap
  11. }
  12. pub fn new() -> Self {
  13. Vec {
  14. buf: RawVec::new(),
  15. len: 0,
  16. }
  17. }
  18. // push/pop/insert/remove largely unchanged:
  19. // * `self.ptr.as_ptr() -> self.ptr()`
  20. // * `self.cap -> self.cap()`
  21. // * `self.grow() -> self.buf.grow()`
  22. }
  23. impl<T> Drop for Vec<T> {
  24. fn drop(&mut self) {
  25. while let Some(_) = self.pop() {}
  26. // deallocation is handled by RawVec
  27. }
  28. }

最后我们可以真正简化IntoIter:

  1. pub struct IntoIter<T> {
  2. _buf: RawVec<T>, // we don't actually care about this. Just need it to live.
  3. start: *const T,
  4. end: *const T,
  5. }
  6. // next and next_back literally unchanged since they never referred to the buf
  7. impl<T> Drop for IntoIter<T> {
  8. fn drop(&mut self) {
  9. // only need to ensure all our elements are read;
  10. // buffer will clean itself up afterwards.
  11. for _ in &mut *self {}
  12. }
  13. }
  14. impl<T> Vec<T> {
  15. pub fn into_iter(self) -> IntoIter<T> {
  16. unsafe {
  17. // need to use ptr::read to unsafely move the buf out since it's
  18. // not Copy, and Vec implements Drop (so we can't destructure it).
  19. let buf = ptr::read(&self.buf);
  20. let len = self.len;
  21. mem::forget(self);
  22. IntoIter {
  23. start: buf.ptr.as_ptr(),
  24. end: buf.ptr..as_ptr().add(len),
  25. _buf: buf,
  26. }
  27. }
  28. }
  29. }

好多了.