vec.rs 7.0 KB

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