vec.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. // NOTE ^^^^^^^ This derivation should be carefully reviewed when this struct is changed.
  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: usize,
  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: usize,
  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: usize) -> 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. // 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 = unsafe { Pointer::new(*Pointer::from(block) as *mut T) };
  55. self.len = old.len;
  56. unsafe {
  57. ptr::copy_nonoverlapping(*old.ptr, *self.ptr, old.len);
  58. }
  59. Block::from(old)
  60. }
  61. /// Get the capacity of this vector.
  62. #[inline]
  63. pub fn capacity(&self) -> usize {
  64. self.cap
  65. }
  66. /// Push an element to the end of this vector.
  67. ///
  68. /// On success, return `Ok(())`. On failure (not enough capacity), return `Err(())`.
  69. #[inline]
  70. #[allow(cast_possible_wrap)]
  71. pub fn push(&mut self, elem: T) -> Result<(), ()> {
  72. if self.len == self.cap {
  73. Err(())
  74. } else {
  75. // Place the element in the end of the vector.
  76. unsafe {
  77. // By the invariants of this type (the size is bounded by the address space), this
  78. // conversion isn't overflowing.
  79. ptr::write((*self.ptr).offset(self.len as isize), elem);
  80. }
  81. // Increment the length.
  82. self.len += 1;
  83. Ok(())
  84. }
  85. }
  86. /// Pop an element from the vector.
  87. ///
  88. /// If the vector is empty, `None` is returned.
  89. #[inline]
  90. pub fn pop(&mut self) -> Option<T> {
  91. if self.len == 0 {
  92. None
  93. } else {
  94. unsafe {
  95. // Decrement the length.
  96. self.len -= 1;
  97. // We use `ptr::read` since the element is unaccessible due to the decrease in the
  98. // length.
  99. Some(ptr::read(self.get_unchecked(self.len)))
  100. }
  101. }
  102. }
  103. /// Truncate this vector.
  104. ///
  105. /// This is O(1).
  106. ///
  107. /// # Panics
  108. ///
  109. /// Panics on out-of-bound.
  110. pub fn truncate(&mut self, len: usize) {
  111. // Bound check.
  112. assert!(len <= self.len, "Out of bound.");
  113. self.len = len;
  114. }
  115. }
  116. // TODO: Remove this in favour of `derive` when rust-lang/rust#35263 is fixed.
  117. impl<T: Leak> Default for Vec<T> {
  118. fn default() -> Vec<T> {
  119. Vec {
  120. ptr: Pointer::empty(),
  121. cap: 0,
  122. len: 0,
  123. }
  124. }
  125. }
  126. /// Cast this vector to the respective block.
  127. impl<T: Leak> From<Vec<T>> for Block {
  128. fn from(from: Vec<T>) -> Block {
  129. unsafe { Block::from_raw_parts(from.ptr.cast(), from.cap * mem::size_of::<T>()) }
  130. }
  131. }
  132. impl<T: Leak> ops::Deref for Vec<T> {
  133. type Target = [T];
  134. #[inline]
  135. fn deref(&self) -> &[T] {
  136. unsafe {
  137. slice::from_raw_parts(*self.ptr as *const T, self.len)
  138. }
  139. }
  140. }
  141. impl<T: Leak> ops::DerefMut for Vec<T> {
  142. #[inline]
  143. fn deref_mut(&mut self) -> &mut [T] {
  144. unsafe {
  145. slice::from_raw_parts_mut(*self.ptr as *mut T, self.len)
  146. }
  147. }
  148. }
  149. #[cfg(test)]
  150. mod test {
  151. use prelude::*;
  152. #[test]
  153. fn test_vec() {
  154. let mut buffer = [b'a'; 32];
  155. let mut vec = unsafe {
  156. Vec::from_raw_parts(
  157. Block::from_raw_parts(Pointer::new(&mut buffer[0] as *mut u8), 32),
  158. 16
  159. )
  160. };
  161. assert_eq!(&*vec, b"aaaaaaaaaaaaaaaa");
  162. vec.push(b'b').unwrap();
  163. assert_eq!(&*vec, b"aaaaaaaaaaaaaaaab");
  164. vec.push(b'c').unwrap();
  165. assert_eq!(&*vec, b"aaaaaaaaaaaaaaaabc");
  166. vec[0] = b'.';
  167. assert_eq!(&*vec, b".aaaaaaaaaaaaaaabc");
  168. unsafe {
  169. assert_eq!(vec.refill(
  170. Block::from_raw_parts(Pointer::new(&mut buffer[0] as *mut u8), 32)).size(),
  171. 32
  172. );
  173. }
  174. assert_eq!(&*vec, b".aaaaaaaaaaaaaaabc");
  175. for _ in 0..14 {
  176. vec.push(b'_').unwrap();
  177. }
  178. assert_eq!(vec.pop().unwrap(), b'_');
  179. vec.push(b'@').unwrap();
  180. vec.push(b'!').unwrap_err();
  181. assert_eq!(&*vec, b".aaaaaaaaaaaaaaabc_____________@");
  182. assert_eq!(vec.capacity(), 32);
  183. for _ in 0..32 { vec.pop().unwrap(); }
  184. assert!(vec.pop().is_none());
  185. assert!(vec.pop().is_none());
  186. assert!(vec.pop().is_none());
  187. assert!(vec.pop().is_none());
  188. }
  189. }