vec.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. //! Vector primitive.
  2. use prelude::*;
  3. use core::{slice, ops, mem, ptr};
  4. // Derive the length newtype.
  5. usize_newtype!(pub Elements);
  6. /// A low-level vector primitive.
  7. ///
  8. /// This does not perform allocation nor reallaction, thus these have to be done manually.
  9. /// Moreover, no destructors are called, making it possible to leak memory.
  10. pub struct Vec<T: Leak> {
  11. /// A pointer to the start of the buffer.
  12. ptr: Pointer<T>,
  13. /// The capacity of the buffer.
  14. ///
  15. /// This demonstrates the lengths before reallocation is necessary.
  16. cap: Elements,
  17. /// The length of the vector.
  18. ///
  19. /// This is the number of elements from the start, that is initialized, and can be read safely.
  20. len: Elements,
  21. }
  22. impl<T: Leak> Vec<T> {
  23. /// Create a vector from a block.
  24. ///
  25. /// # Safety
  26. ///
  27. /// This is unsafe, since it won't initialize the buffer in any way, possibly breaking type
  28. /// safety, memory safety, and so on. Thus, care must be taken upon usage.
  29. #[inline]
  30. pub unsafe fn from_raw_parts(block: Block, len: Elements) -> Vec<T> {
  31. Vec {
  32. len: len,
  33. cap: block.size() / mem::size_of::<T>(),
  34. ptr: Pointer::from(block).cast(),
  35. }
  36. }
  37. /// Replace the inner buffer with a new one, and return the old.
  38. ///
  39. /// This will memcpy the vectors buffer to the new block, and update the pointer and capacity
  40. /// to match the given block.
  41. ///
  42. /// # Panics
  43. ///
  44. /// This panics if the vector is bigger than the block.
  45. pub fn refill(&mut self, block: Block) -> Block {
  46. log!(INTERNAL, "Refilling vector...");
  47. // Calculate the new capacity.
  48. let new_cap = block.size() / mem::size_of::<T>();
  49. // Make some assertions.
  50. assert!(self.len <= new_cap, "Block not large enough to cover the vector.");
  51. assert!(block.aligned_to(mem::align_of::<T>()), "Block not aligned.");
  52. let old = mem::replace(self, Vec::default());
  53. // Update the fields of `self`.
  54. self.cap = new_cap;
  55. self.ptr = Pointer::from(block).cast();
  56. self.len = old.len;
  57. unsafe {
  58. // LAST AUDIT: 2016-08-21 (Ticki).
  59. // Due to the invariants of `Block`, this copy is safe (the pointer is valid and
  60. // unaliased).
  61. ptr::copy_nonoverlapping(*old.ptr, *self.ptr, old.len);
  62. }
  63. Block::from(old)
  64. }
  65. /// Get the capacity of this vector.
  66. #[inline]
  67. pub fn capacity(&self) -> Elements {
  68. self.cap
  69. }
  70. /// Push an element to the end of this vector.
  71. ///
  72. /// On success, return `Ok(())`. On failure (not enough capacity), return `Err(())`.
  73. #[inline]
  74. #[allow(cast_possible_wrap)]
  75. pub fn push(&mut self, elem: T) -> Result<(), ()> {
  76. if self.len == self.cap {
  77. Err(())
  78. } else {
  79. // Place the element in the end of the vector.
  80. unsafe {
  81. // LAST AUDIT: 2016-08-21 (Ticki).
  82. // By the invariants of this type (the size is bounded by the address space), this
  83. // conversion isn't overflowing.
  84. ptr::write((*self.ptr).offset(self.len as isize), elem);
  85. }
  86. // Increment the length.
  87. self.len += 1;
  88. Ok(())
  89. }
  90. }
  91. /// Pop an element from the vector.
  92. ///
  93. /// If the vector is empty, `None` is returned.
  94. #[inline]
  95. pub fn pop(&mut self) -> Option<T> {
  96. if self.len == 0 {
  97. None
  98. } else {
  99. unsafe {
  100. // LAST AUDIT: 2016-08-21 (Ticki).
  101. // Decrement the length. This won't underflow due to the conditional above.
  102. self.len -= 1;
  103. // We use `ptr::read` since the element is unaccessible due to the decrease in the
  104. // length.
  105. Some(ptr::read(self.get_unchecked(self.len)))
  106. }
  107. }
  108. }
  109. /// Truncate this vector.
  110. ///
  111. /// This is $$O(1)$$.
  112. ///
  113. /// # Panics
  114. ///
  115. /// Panics on out-of-bound.
  116. pub fn truncate(&mut self, len: Elements) {
  117. // Bound check.
  118. assert!(len <= self.len, "Out of bound.");
  119. self.len = len;
  120. }
  121. /// Yield an iterator popping from the vector.
  122. pub fn pop_iter(&mut self) -> PopIter<T> {
  123. PopIter {
  124. vec: self,
  125. }
  126. }
  127. }
  128. /// An iterator popping blocks from the bookkeeper.
  129. pub struct PopIter<'a, T: 'a + Leak> {
  130. vec: &'a mut Vec<T>,
  131. }
  132. impl<'a, T: Leak> Iterator for PopIter<'a, T> {
  133. type Item = T;
  134. #[inline]
  135. fn next(&mut self) -> Option<T> {
  136. self.vec.pop()
  137. }
  138. }
  139. // TODO: Remove this in favour of `derive` when rust-lang/rust#35263 is fixed.
  140. impl<T: Leak> Default for Vec<T> {
  141. fn default() -> Vec<T> {
  142. Vec {
  143. ptr: Pointer::empty(),
  144. cap: 0,
  145. len: 0,
  146. }
  147. }
  148. }
  149. /// Cast this vector to the respective block.
  150. impl<T: Leak> From<Vec<T>> for Block {
  151. fn from(from: Vec<T>) -> Block {
  152. unsafe {
  153. // LAST AUDIT: 2016-08-21 (Ticki).
  154. // The invariants maintains safety.
  155. Block::from_raw_parts(from.ptr.cast(), from.cap * mem::size_of::<T>())
  156. }
  157. }
  158. }
  159. impl<T: Leak> ops::Deref for Vec<T> {
  160. type Target = [T];
  161. #[inline]
  162. fn deref(&self) -> &[T] {
  163. unsafe {
  164. // LAST AUDIT: 2016-08-21 (Ticki).
  165. // The invariants maintains safety.
  166. slice::from_raw_parts(self.ptr, self.len)
  167. }
  168. }
  169. }
  170. impl<T: Leak> ops::DerefMut for Vec<T> {
  171. #[inline]
  172. fn deref_mut(&mut self) -> &mut [T] {
  173. unsafe {
  174. // LAST AUDIT: 2016-08-21 (Ticki).
  175. // The invariants maintains safety.
  176. slice::from_raw_parts_mut(self.ptr, self.len)
  177. }
  178. }
  179. }
  180. #[cfg(test)]
  181. mod test {
  182. use prelude::*;
  183. #[test]
  184. fn vec() {
  185. let mut buffer = [b'a'; 32];
  186. let mut vec = unsafe {
  187. Vec::from_raw_parts(
  188. Block::from_raw_parts(Pointer::new(&mut buffer[0]), 32),
  189. 16
  190. )
  191. };
  192. assert_eq!(&*vec, b"aaaaaaaaaaaaaaaa");
  193. vec.push(b'b').unwrap();
  194. assert_eq!(&*vec, b"aaaaaaaaaaaaaaaab");
  195. vec.push(b'c').unwrap();
  196. assert_eq!(&*vec, b"aaaaaaaaaaaaaaaabc");
  197. vec[0] = b'.';
  198. assert_eq!(&*vec, b".aaaaaaaaaaaaaaabc");
  199. unsafe {
  200. assert_eq!(vec.refill(
  201. Block::from_raw_parts(Pointer::new(&mut buffer[0]), 32)).size(),
  202. 32
  203. );
  204. }
  205. assert_eq!(&*vec, b".aaaaaaaaaaaaaaabc");
  206. for _ in 0..14 {
  207. vec.push(b'_').unwrap();
  208. }
  209. assert_eq!(vec.pop().unwrap(), b'_');
  210. vec.push(b'@').unwrap();
  211. vec.push(b'!').unwrap_err();
  212. assert_eq!(&*vec, b".aaaaaaaaaaaaaaabc_____________@");
  213. assert_eq!(vec.capacity(), 32);
  214. for _ in 0..32 { vec.pop().unwrap(); }
  215. assert!(vec.pop().is_none());
  216. assert!(vec.pop().is_none());
  217. assert!(vec.pop().is_none());
  218. assert!(vec.pop().is_none());
  219. }
  220. }