原文链接:https://doc.rust-lang.org/nomicon/vec-zsts.html

最终代码

  1. #![feature(ptr_internals)]
  2. #![feature(allocator_api)]
  3. use std::ptr::{Unique, NonNull, self};
  4. use std::mem;
  5. use std::ops::{Deref, DerefMut};
  6. use std::marker::PhantomData;
  7. use std::alloc::{Alloc, GlobalAlloc, Layout, Global, handle_alloc_error};
  8. struct RawVec<T> {
  9. ptr: Unique<T>,
  10. cap: usize,
  11. }
  12. impl<T> RawVec<T> {
  13. fn new() -> Self {
  14. // !0就是usize::MAX。这段分支代码在编译期就可以计算出结果。
  15. let cap = if mem::size_of::<T>() == 0 { !0 } else { 0 };
  16. // Unique::empty()有着“未分配”和“零尺寸分配”的双重含义
  17. RawVec { ptr: Unique::empty(), cap: cap }
  18. }
  19. fn grow(&mut self) {
  20. unsafe {
  21. let elem_size = mem::size_of::<T>();
  22. // 因为当elem_size为0时我们设置了cap为usize::MAX,
  23. // 这一步成立意味着Vec的容量溢出了
  24. assert!(elem_size != 0, "capacity overflow");
  25. let (new_cap, ptr) = if self.cap == 0 {
  26. let ptr = Global.alloc(Layout::array::<T>(1).unwrap());
  27. (1, ptr)
  28. } else {
  29. let new_cap = 2 * self.cap;
  30. let c: NonNull<T> = self.ptr.into();
  31. let ptr = Global.realloc(c.cast(),
  32. Layout::array::<T>(self.cap).unwrap(),
  33. Layout::array::<T>(new_cap).unwrap().size());
  34. (new_cap, ptr)
  35. };
  36. // 如果分配或再分配失败,oom
  37. if ptr.is_err() {
  38. handle_alloc_error(Layout::from_size_align_unchecked(
  39. new_cap * elem_size,
  40. mem::align_of::<T>(),
  41. ))
  42. }
  43. let ptr = ptr.unwrap();
  44. self.ptr = Unique::new_unchecked(ptr.as_ptr() as *mut _);
  45. self.cap = new_cap;
  46. }
  47. }
  48. }
  49. impl<T> Drop for RawVec<T> {
  50. fn drop(&mut self) {
  51. let elem_size = mem::size_of::<T>();
  52. if self.cap != 0 && elem_size != 0 {
  53. unsafe {
  54. let c: NonNull<T> = self.ptr.into();
  55. Global.dealloc(c.cast(),
  56. Layout::array::<T>(self.cap).unwrap());
  57. }
  58. }
  59. }
  60. }
  61. pub struct Vec<T> {
  62. buf: RawVec<T>,
  63. len: usize,
  64. }
  65. impl<T> Vec<T> {
  66. fn ptr(&self) -> *mut T { self.buf.ptr.as_ptr() }
  67. fn cap(&self) -> usize { self.buf.cap }
  68. pub fn new() -> Self {
  69. Vec { buf: RawVec::new(), len: 0 }
  70. }
  71. pub fn push(&mut self, elem: T) {
  72. if self.len == self.cap() { self.buf.grow(); }
  73. unsafe {
  74. ptr::write(self.ptr().offset(self.len as isize), elem);
  75. }
  76. // 不会溢出,会先OOM
  77. self.len += 1;
  78. }
  79. pub fn pop(&mut self) -> Option<T> {
  80. if self.len == 0 {
  81. None
  82. } else {
  83. self.len -= 1;
  84. unsafe {
  85. Some(ptr::read(self.ptr().offset(self.len as isize)))
  86. }
  87. }
  88. }
  89. pub fn insert(&mut self, index: usize, elem: T) {
  90. assert!(index <= self.len, "index out of bounds");
  91. if self.cap() == self.len { self.buf.grow(); }
  92. unsafe {
  93. if index < self.len {
  94. ptr::copy(self.ptr().offset(index as isize),
  95. self.ptr().offset(index as isize + 1),
  96. self.len - index);
  97. }
  98. ptr::write(self.ptr().offset(index as isize), elem);
  99. self.len += 1;
  100. }
  101. }
  102. pub fn remove(&mut self, index: usize) -> T {
  103. assert!(index < self.len, "index out of bounds");
  104. unsafe {
  105. self.len -= 1;
  106. let result = ptr::read(self.ptr().offset(index as isize));
  107. ptr::copy(self.ptr().offset(index as isize + 1),
  108. self.ptr().offset(index as isize),
  109. self.len - index);
  110. result
  111. }
  112. }
  113. pub fn into_iter(self) -> IntoIter<T> {
  114. unsafe {
  115. let iter = RawValIter::new(&self);
  116. let buf = ptr::read(&self.buf);
  117. mem::forget(self);
  118. IntoIter {
  119. iter: iter,
  120. _buf: buf,
  121. }
  122. }
  123. }
  124. pub fn drain(&mut self) -> Drain<T> {
  125. unsafe {
  126. let iter = RawValIter::new(&self);
  127. // 这一步是为了mem::forget的安全。如果Drain被forget,我们会泄露整个Vec的内容
  128. // 同时,既然我们无论如何都会做这一步,为什么不现在做呢?
  129. self.len = 0;
  130. Drain {
  131. iter: iter,
  132. vec: PhantomData,
  133. }
  134. }
  135. }
  136. }
  137. impl<T> Drop for Vec<T> {
  138. fn drop(&mut self) {
  139. while let Some(_) = self.pop() {}
  140. // 分配由RawVec负责
  141. }
  142. }
  143. impl<T> Deref for Vec<T> {
  144. type Target = [T];
  145. fn deref(&self) -> &[T] {
  146. unsafe {
  147. ::std::slice::from_raw_parts(self.ptr(), self.len)
  148. }
  149. }
  150. }
  151. impl<T> DerefMut for Vec<T> {
  152. fn deref_mut(&mut self) -> &mut [T] {
  153. unsafe {
  154. ::std::slice::from_raw_parts_mut(self.ptr(), self.len)
  155. }
  156. }
  157. }
  158. struct RawValIter<T> {
  159. start: *const T,
  160. end: *const T,
  161. }
  162. impl<T> RawValIter<T> {
  163. unsafe fn new(slice: &[T]) -> Self {
  164. RawValIter {
  165. start: slice.as_ptr(),
  166. end: if mem::size_of::<T>() == 0 {
  167. ((slice.as_ptr() as usize) + slice.len()) as *const _
  168. } else if slice.len() == 0 {
  169. slice.as_ptr()
  170. } else {
  171. slice.as_ptr().offset(slice.len() as isize)
  172. }
  173. }
  174. }
  175. }
  176. impl<T> Iterator for RawValIter<T> {
  177. type Item = T;
  178. fn next(&mut self) -> Option<T> {
  179. if self.start == self.end {
  180. None
  181. } else {
  182. unsafe {
  183. let result = ptr::read(self.start);
  184. self.start = if mem::size_of::<T>() == 0 {
  185. (self.start as usize + 1) as *const _
  186. } else {
  187. self.start.offset(1)
  188. };
  189. Some(result)
  190. }
  191. }
  192. }
  193. fn size_hint(&self) -> (usize, Option<usize>) {
  194. let elem_size = mem::size_of::<T>();
  195. let len = (self.end as usize - self.start as usize)
  196. / if elem_size == 0 { 1 } else { elem_size };
  197. (len, Some(len))
  198. }
  199. }
  200. impl<T> DoubleEndedIterator for RawValIter<T> {
  201. fn next_back(&mut self) -> Option<T> {
  202. if self.start == self.end {
  203. None
  204. } else {
  205. unsafe {
  206. self.end = if mem::size_of::<T>() == 0 {
  207. (self.end as usize - 1) as *const _
  208. } else {
  209. self.end.offset(-1)
  210. };
  211. Some(ptr::read(self.end))
  212. }
  213. }
  214. }
  215. }
  216. pub struct IntoIter<T> {
  217. _buf: RawVec<T>, // 我们并不关心这个,只是需要它们保持分配空间不被销毁
  218. iter: RawValIter<T>,
  219. }
  220. impl<T> Iterator for IntoIter<T> {
  221. type Item = T;
  222. fn next(&mut self) -> Option<T> { self.iter.next() }
  223. fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
  224. }
  225. impl<T> DoubleEndedIterator for IntoIter<T> {
  226. fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
  227. }
  228. impl<T> Drop for IntoIter<T> {
  229. fn drop(&mut self) {
  230. for _ in &mut *self {}
  231. }
  232. }
  233. pub struct Drain<'a, T: 'a> {
  234. vec: PhantomData<&'a mut Vec<T>>,
  235. iter: RawValIter<T>,
  236. }
  237. impl<'a, T> Iterator for Drain<'a, T> {
  238. type Item = T;
  239. fn next(&mut self) -> Option<T> { self.iter.next() }
  240. fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
  241. }
  242. impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
  243. fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
  244. }
  245. impl<'a, T> Drop for Drain<'a, T> {
  246. fn drop(&mut self) {
  247. // pre-drain the iter
  248. for _ in &mut self.iter {}
  249. }
  250. }
  251. # fn main() {
  252. # tests::create_push_pop();
  253. # tests::iter_test();
  254. # tests::test_drain();
  255. # tests::test_zst();
  256. # println!("All tests finished OK");
  257. # }
  258. # mod tests {
  259. # use super::*;
  260. # pub fn create_push_pop() {
  261. # let mut v = Vec::new();
  262. # v.push(1);
  263. # assert_eq!(1, v.len());
  264. # assert_eq!(1, v[0]);
  265. # for i in v.iter_mut() {
  266. # *i += 1;
  267. # }
  268. # v.insert(0, 5);
  269. # let x = v.pop();
  270. # assert_eq!(Some(2), x);
  271. # assert_eq!(1, v.len());
  272. # v.push(10);
  273. # let x = v.remove(0);
  274. # assert_eq!(5, x);
  275. # assert_eq!(1, v.len());
  276. # }
  277. #
  278. # pub fn iter_test() {
  279. # let mut v = Vec::new();
  280. # for i in 0..10 {
  281. # v.push(Box::new(i))
  282. # }
  283. # let mut iter = v.into_iter();
  284. # let first = iter.next().unwrap();
  285. # let last = iter.next_back().unwrap();
  286. # drop(iter);
  287. # assert_eq!(0, *first);
  288. # assert_eq!(9, *last);
  289. # }
  290. #
  291. # pub fn test_drain() {
  292. # let mut v = Vec::new();
  293. # for i in 0..10 {
  294. # v.push(Box::new(i))
  295. # }
  296. # {
  297. # let mut drain = v.drain();
  298. # let first = drain.next().unwrap();
  299. # let last = drain.next_back().unwrap();
  300. # assert_eq!(0, *first);
  301. # assert_eq!(9, *last);
  302. # }
  303. # assert_eq!(0, v.len());
  304. # v.push(Box::new(1));
  305. # assert_eq!(1, *v.pop().unwrap());
  306. # }
  307. #
  308. # pub fn test_zst() {
  309. # let mut v = Vec::new();
  310. # for _i in 0..10 {
  311. # v.push(())
  312. # }
  313. #
  314. # let mut count = 0;
  315. #
  316. # for _ in v.into_iter() {
  317. # count += 1
  318. # }
  319. #
  320. # assert_eq!(10, count);
  321. # }
  322. # }