standard_lib/collections/contiguous/vector/vector.rs
1use std::borrow::{Borrow, BorrowMut};
2use std::cmp;
3use std::fmt::{self, Debug, Display, Formatter};
4use std::hash::{Hash, Hasher};
5use std::iter::TrustedLen;
6use std::mem::{self, MaybeUninit};
7use std::ops::{Deref, DerefMut};
8use std::ptr::{self, NonNull};
9use std::slice;
10
11use crate::collections::contiguous::Array;
12use crate::util::error::IndexOutOfBounds;
13use crate::util::result::ResultExtension;
14
15const MIN_CAP: usize = 2;
16const MAX_CAP: usize = isize::MAX as usize;
17
18const GROWTH_FACTOR: usize = 2;
19
20// TODO: Add try methods.
21
22/// A variable size contiguous collection, based on [`Array<T>`].
23///
24/// # Time Complexity
25/// For this analysis of time complexity, variables are defined as follows:
26/// - `n`: The number of items in the Vector.
27/// - `i`: The index of the item in question.
28/// - `m`: The number of items in the second Vector.
29///
30/// | Method | Complexity |
31/// |-|-|
32/// | `get` | `O(1)` |
33/// | `len` | `O(1)` |
34/// | `push` | `O(1)`*, `O(n)` |
35/// | `push_unchecked` | `O(1)` |
36/// | `pop` | `O(1)` |
37/// | `insert` | `O(n-i)` |
38/// | `remove` | `O(n-i)` |
39/// | `replace` | `O(1)` |
40/// | `reserve` | `O(n)`**, `O(1)` |
41/// | `shrink_to_fit` | `O(n)` |
42/// | `adjust_cap` | `O(n)` |
43/// | `append` | `O(n+m)` |
44/// | `contains` | `O(n)` |
45///
46/// \* If the Vector doesn't have enough capacity for the new element, `push` will take `O(n)`.
47///
48/// \** If the Vector has enough capacity for the additional items already, `reserve` is `O(1)`.
49pub struct Vector<T> {
50 pub(crate) arr: Array<MaybeUninit<T>>,
51 pub(crate) len: usize,
52}
53
54impl<T> Vector<T> {
55 /// Creates a new Vector with length and capacity 0. Memory will be allocated when the capacity
56 /// changes.
57 ///
58 /// # Examples
59 /// ```
60 /// # use standard_lib::collections::contiguous::Vector;
61 /// let vec: Vector<u8> = Vector::new();
62 /// assert_eq!(vec.len(), 0);
63 /// assert_eq!(vec.cap(), 0);
64 /// ```
65 pub fn new() -> Vector<T> {
66 Vector {
67 arr: Array::new(),
68 len: 0,
69 }
70 }
71
72 /// Creates a new Vector with capacity exactly equal to the provided value, allowing values to
73 /// be added without reallocation.
74 ///
75 /// # Panics
76 /// Panics if memory layout size exceeds [`isize::MAX`].
77 ///
78 /// # Examples
79 /// ```
80 /// # use standard_lib::collections::contiguous::Vector;
81 /// let mut vec: Vector<u8> = Vector::with_cap(5);
82 /// assert_eq!(vec.cap(), 5);
83 /// vec.extend([1_u8, 2, 3, 4, 5]);
84 /// assert_eq!(vec.cap(), 5);
85 /// ```
86 pub fn with_cap(cap: usize) -> Vector<T> {
87 Vector {
88 arr: Array::new_uninit(cap),
89 len: 0,
90 }
91 }
92
93 /// Returns the length of the Vector.
94 ///
95 /// # Examples
96 /// ```
97 /// # use standard_lib::collections::contiguous::Vector;
98 /// let vec = Vector::from_iter_sized(1_u8..=3);
99 /// assert_eq!(vec.len(), 3);
100 /// ```
101 pub const fn len(&self) -> usize {
102 self.len
103 }
104
105 /// Returns true if the Vector contains no elements.
106 ///
107 /// # Examples
108 /// ```
109 /// # use standard_lib::collections::contiguous::Vector;
110 /// let mut vec: Vector<u8> = Vector::new();
111 /// assert!(vec.is_empty());
112 /// vec.push(1);
113 /// assert!(!vec.is_empty())
114 /// ```
115 pub const fn is_empty(&self) -> bool {
116 self.len == 0
117 }
118
119 /// Returns the current capacity of the Vector. Unlike [`Vec`], the capacity is guaranteed to be
120 /// exactly the value provided to any of the various capacity manipulation functions.
121 ///
122 /// # Examples
123 /// ```
124 /// # use standard_lib::collections::contiguous::Vector;
125 /// let vec: Vector<u8> = Vector::with_cap(5);
126 /// assert_eq!(vec.cap(), 5);
127 /// ```
128 pub const fn cap(&self) -> usize {
129 self.arr.size()
130 }
131
132 /// Push the provided value onto the end of the Vector, increasing the capacity if required.
133 ///
134 /// # Panics
135 /// Panics if the memory layout of the Vector would have a size that exceeds [`isize::MAX`].
136 ///
137 /// # Examples
138 /// ```
139 /// # use standard_lib::collections::contiguous::Vector;
140 /// let mut vec = Vector::<u8>::new();
141 /// for i in 0..=5 {
142 /// vec.push(i);
143 /// }
144 /// assert_eq!(&*vec, &[0, 1, 2, 3, 4, 5]);
145 /// ```
146 pub fn push(&mut self, value: T) {
147 if self.len == self.cap() {
148 self.grow();
149 }
150 // SAFETY: The capacity has just been adjusted to support the addition of the new item.
151 unsafe { self.push_unchecked(value) }
152 }
153
154 /// Push the provided value onto the end of the Vector, assuming that there is enough capacity
155 /// to do so.
156 ///
157 /// # Safety
158 /// It is up to the caller to ensure that the Vector has enough capacity to add the provided
159 /// value, using methods like [`reserve`](Vector::reserve), [`adjust_cap`](Vector::adjust_cap)
160 /// or [`with_cap`](Vector::with_cap) to do so. Using this method on a Vector without enough
161 /// capacity is undefined behavior.
162 ///
163 /// # Examples
164 /// ```
165 /// # use standard_lib::collections::contiguous::{Array, Vector};
166 /// let arr = Array::from_iter_sized(1_u8..=3);
167 /// let mut vec = Vector::with_cap(arr.size());
168 /// for i in arr.into_iter() {
169 /// // SAFETY: We know that vec has enough capacity to store all elements in arr.
170 /// unsafe { vec.push_unchecked(i); }
171 /// }
172 /// assert_eq!(&*vec, &[1, 2, 3]);
173 /// ```
174 pub const unsafe fn push_unchecked(&mut self, value: T) {
175 // SAFETY: It is up to the caller to ensure that the Vector has enough capacity for this
176 // push, leading to the pointer read being in bounds of the object.
177 unsafe { self.arr.ptr.add(self.len).write(MaybeUninit::new(value)); }
178 self.len += 1;
179 }
180
181 /// Pops the last value off the end of the Vector, returning an owned value if the Vector has
182 /// length greater than 0.
183 ///
184 /// # Examples
185 /// ```
186 /// # use standard_lib::collections::contiguous::Vector;
187 /// let mut vec = Vector::from_iter_sized(0..5);
188 /// for i in (0..vec.len()).rev() {
189 /// assert_eq!(vec.pop(), Some(i));
190 /// }
191 /// assert_eq!(vec.pop(), None);
192 /// ```
193 pub const fn pop(&mut self) -> Option<T> {
194 if self.len == 0 {
195 None
196 } else {
197 // Decrement len before getting.
198 self.len -= 1;
199
200 // SAFETY: len has just been decremented and is within the capacity of the Vector.
201 // size_of::<T>() * self.len can't overflow isize::MAX, and all values < len are
202 // initialized.
203 // We are making a bitwise copy of the value on the heap and then forgetting that the
204 // version on the heap exists, which is as close as we can get to actually moving the
205 // value off of the heap.
206 let value = unsafe {
207 self.arr.ptr.add(self.len).read().assume_init()
208 };
209 Some(value)
210 }
211 }
212
213 /// Inserts the provided value at the given index, growing and moving items as necessary.
214 ///
215 /// # Panics
216 /// Panics if the provided index is out of bounds.
217 ///
218 /// # Examples
219 /// ```
220 /// # use standard_lib::collections::contiguous::Vector;
221 /// let mut vec = Vector::from_iter_sized(0..3);
222 /// vec.insert(1, 100);
223 /// vec.insert(1, 200);
224 /// vec.insert(3, 300);
225 /// assert_eq!(&*vec, &[0, 200, 100, 300, 1, 2]);
226 /// ```
227 pub fn insert(&mut self, index: usize, value: T) {
228 self.check_index(index);
229
230 if self.len == self.cap() {
231 self.grow()
232 }
233
234 let mut prev = MaybeUninit::new(value);
235 for i in index..=self.len {
236 prev = mem::replace(&mut self.arr[i], prev);
237 }
238
239 self.len += 1;
240 }
241
242 /// Removes the element at the provided index, moving all following values to fill in the gap.
243 ///
244 /// # Panics
245 /// Panics if the provided index is out of bounds.
246 ///
247 /// # Examples
248 /// ```
249 /// # use standard_lib::collections::contiguous::Vector;
250 /// let mut vec: Vector<_> = "Hello world!".chars().collect();
251 /// assert_eq!(vec.remove(1), 'e');
252 /// assert_eq!(vec.remove(4), ' ');
253 /// assert_eq!(vec, "Hlloworld!".chars().collect());
254 /// ```
255 pub fn remove(&mut self, index: usize) -> T {
256 self.check_index(index);
257
258 let mut next = MaybeUninit::uninit();
259 // Iterate backwards to index.
260 for i in (index..self.len).rev() {
261 next = mem::replace(&mut self.arr[i], next);
262 }
263
264 self.len -= 1;
265 // SAFETY: next contains the value which was previously located at index, which we've
266 // already checked to be less than len and therefore initialized.
267 unsafe { next.assume_init() }
268 }
269
270 /// Replaces the element at the provided index with `new_value`, returning the old value.
271 ///
272 /// # Panics
273 /// Panics if the provided index is out of bounds.
274 pub fn replace(&mut self, index: usize, new_value: T) -> T {
275 self.check_index(index);
276
277 // SAFETY: index is < len and all values < len are initialized.
278 unsafe {
279 mem::replace(
280 &mut self.arr[index],
281 MaybeUninit::new(new_value)
282 ).assume_init()
283 }
284 }
285
286 /// Ensures that the Vector has capacity to hold an additional `extra` elements. After invoking
287 /// this method, the capacity will be >= len + extra.
288 ///
289 /// # Panics
290 /// Panics if the memory layout of the Vector would have a size that exceeds [`isize::MAX`].
291 pub fn reserve(&mut self, extra: usize) {
292 let new_cap = self.len.strict_add(extra);
293
294 if new_cap < self.cap() { return; }
295
296 self.realloc_with_cap(new_cap);
297 }
298
299 /// Shrinks the Vector so that its capacity is equal to its length.
300 ///
301 /// # Panics
302 /// Panics if the memory layout of the Vector would have a size that exceeds [`isize::MAX`].
303 pub fn shrink_to_fit(&mut self) {
304 self.realloc_with_cap(self.len);
305 }
306
307 /// Adjusts the capacity of the Vector to `new_cap`, dropping elements if required.
308 ///
309 /// # Panics
310 /// Panics if the memory layout of the Vector would have a size that exceeds [`isize::MAX`].
311 pub fn adjust_cap(&mut self, new_cap: usize) {
312 if new_cap < self.cap() {
313 // Drop the values that are about to be deallocated.
314 for i in new_cap..self.cap() {
315 // SAFETY: The pointer is nonnull, as well as properly aligned, initialized and
316 // ready to drop. count > isize::MAX is already guarded against and all possible
317 // values are within the allocated range of the Array.
318 unsafe {
319 ptr::drop_in_place(
320 self.arr.ptr.add(i).as_ptr()
321 );
322 }
323 self.len -= 1;
324 }
325 }
326
327 self.realloc_with_cap(new_cap);
328 }
329
330 /// Appends all elements from `other` to self.
331 ///
332 /// # Panics
333 /// Panics if the memory layout of the Vector would have a size that exceeds [`isize::MAX`].
334 pub fn append(&mut self, other: Vector<T>) {
335 let initial_len = self.len;
336 self.reserve(other.len);
337
338 // SAFETY: self is valid from initial_len to initial_len + other.len and other is valid from
339 // 0 to other.len. Both are properly aligned and don't overlap.
340 unsafe {
341 // Reduce iteration by copying one slice into the other.
342 ptr::copy_nonoverlapping(
343 self.arr.ptr.add(initial_len).as_ptr().cast_const(),
344 other.arr.ptr.as_ptr(),
345 other.len,
346 );
347 }
348
349 self.len += other.len;
350
351 // Forget about other because we have copied all values.
352 mem::forget(other);
353 }
354
355 pub const fn into_parts(self) -> (NonNull<MaybeUninit<T>>, usize, usize) {
356 let ret = (self.arr.ptr, self.len, self.arr.size);
357 mem::forget(self);
358 ret
359 }
360
361 pub const unsafe fn from_parts(
362 ptr: NonNull<MaybeUninit<T>>,
363 len: usize,
364 cap: usize,
365 ) -> Vector<T> {
366 Vector {
367 arr: unsafe { Array::from_parts(ptr, cap) },
368 len,
369 }
370 }
371
372 /// Creates an Vector from a type which implements [`IntoIterator`] and creates an
373 /// [`ExactSizeIterator`].
374 ///
375 /// # Panics
376 /// Panics if memory layout size exceeds [`isize::MAX`].
377 pub fn from_iter_sized<I>(value: I) -> Self
378 where
379 I: Iterator<Item = T> + ExactSizeIterator + TrustedLen,
380 {
381 let iter = value.into_iter();
382 let mut vec = Vector::with_cap(iter.len());
383
384 for item in iter {
385 // SAFETY: vec has been created with the right capacity.
386 unsafe { vec.push_unchecked(item); }
387 }
388
389 vec
390 }
391
392 /// Reallocates the internal Array with the provided capacity.
393 ///
394 /// # Panics
395 /// Panics if the memory layout of the Vector would have a size that exceeds [`isize::MAX`].
396 pub(crate) fn realloc_with_cap(&mut self, new_cap: usize) {
397 self.arr.realloc(new_cap);
398 }
399
400 /// Grows the internal Array to allow for the insertion of additional elements. After calling
401 /// this, the Vector can take at least one more element.
402 ///
403 /// # Panics
404 /// Panics if the memory layout of the Vector would have a size that exceeds [`isize::MAX`].
405 pub(crate) fn grow(&mut self) {
406 // SAFETY: old_cap < isize::MAX, so old_cap * 2 can't overflow. Can still exceed isize::MAX.
407 let mut new_cap = cmp::max(self.cap() * GROWTH_FACTOR, MIN_CAP);
408
409 // If we would grow past maximum capacity, instead use the maximum if it represents growth.
410 if (new_cap * size_of::<T>() > MAX_CAP) && (MAX_CAP > self.cap() * size_of::<T>()) {
411 new_cap = MAX_CAP;
412 }
413
414 self.realloc_with_cap(new_cap);
415 }
416
417 /// Checks that the provided index is within the bounds of self.
418 ///
419 /// # Panics
420 /// Panics if the provided index is out of bounds.
421 pub(crate) fn check_index(&self, index: usize) {
422 if index >= self.len {
423 Err(IndexOutOfBounds {
424 index,
425 len: self.len
426 }).throw()
427 }
428 }
429}
430
431impl<T> Extend<T> for Vector<T> {
432 fn extend<A: IntoIterator<Item = T>>(&mut self, iter: A) {
433 for item in iter {
434 self.push(item);
435 }
436 }
437
438 fn extend_one(&mut self, item: T) {
439 self.push(item);
440 }
441
442 fn extend_reserve(&mut self, additional: usize) {
443 self.reserve(additional);
444 }
445
446 unsafe fn extend_one_unchecked(&mut self, item: T)
447 where
448 Self: Sized,
449 {
450 // SAFETY: extend_reserve is implemented correctly, so all other safety requirements are the
451 // responsibility of the caller.
452 unsafe { self.push_unchecked(item); }
453 }
454}
455
456// impl<T, I> From<I> for Vector<T>
457// where
458// I: Iterator<Item = T> + ExactSizeIterator + TrustedLen,
459// {
460// fn from(value: I) -> Self {
461// let iter = value.into_iter();
462// let mut vec = Vector::with_cap(iter.len());
463
464// for item in iter {
465// // SAFETY: vec has been created with the right capacity.
466// unsafe { vec.push_unchecked(item); }
467// }
468
469// vec
470// }
471// }
472
473impl<T> FromIterator<T> for Vector<T> {
474 fn from_iter<I: IntoIterator<Item = T>>(value: I) -> Self {
475 let iter = value.into_iter();
476 let mut vec = Vector::with_cap(iter.size_hint().0);
477
478 for item in iter {
479 vec.push(item);
480 }
481
482 vec
483 }
484}
485
486impl<T> Default for Vector<T> {
487 fn default() -> Self {
488 Self::new()
489 }
490}
491
492impl<T> Drop for Vector<T> {
493 fn drop(&mut self) {
494 // Call drop on all initialized values in place.
495 for i in 0..self.len {
496 // SAFETY: All values less than len are initialized and safe to drop.
497 unsafe { self.arr.ptr.add(i).as_mut().assume_init_drop(); }
498 }
499
500 // Implicitly drop self.arr, containing only MaybeUninit values without a no-op drop.
501 // Doing so also deallocates the owned memory.
502 }
503}
504
505impl<T> Deref for Vector<T> {
506 type Target = [T];
507
508 fn deref(&self) -> &Self::Target {
509 // SAFETY: Vector is valid as a slice for len values, which are all initialized. The pointer
510 // is nonnull, properly aligned and the range entirely contained within this Vector.
511 // The borrow checker enforces that self isn't mutated due to this function taking a &self.
512 // The total size is < isize::MAX as the result of being a valid Vector.
513 unsafe {
514 slice::from_raw_parts(
515 // Reinterpret *mut MaybeUninit<T> as *mut T for all values < len.
516 self.arr.ptr.as_ptr().cast(),
517 self.len,
518 )
519 }
520 }
521}
522
523impl<T> DerefMut for Vector<T> {
524 fn deref_mut(&mut self) -> &mut Self::Target {
525 // SAFETY: Vector is valid as a slice for len values, which are all initialized. The pointer
526 // is nonnull, properly aligned and the range entirely contained within this Vector.
527 // The borrow checker enforces that self isn't accessed due to this function taking a &self.
528 // The total size is < isize::MAX as the result of being a valid Vector.
529 unsafe {
530 slice::from_raw_parts_mut(
531 // Reinterpret *mut MaybeUninit<T> as *mut T for all values < len.
532 self.arr.ptr.as_ptr().cast(),
533 self.len,
534 )
535 }
536 }
537}
538
539impl<T> AsRef<[T]> for Vector<T> {
540 fn as_ref(&self) -> &[T] {
541 self.deref()
542 }
543}
544
545impl<T> AsMut<[T]> for Vector<T> {
546 fn as_mut(&mut self) -> &mut [T] {
547 self.deref_mut()
548 }
549}
550
551impl<T> Borrow<[T]> for Vector<T> {
552 fn borrow(&self) -> &[T] {
553 self.as_ref()
554 }
555}
556
557impl<T> BorrowMut<[T]> for Vector<T> {
558 fn borrow_mut(&mut self) -> &mut [T] {
559 self.as_mut()
560 }
561}
562
563// SAFETY: Vectors, when used safely rely on unique pointers and are therefore safe for Send when T:
564// Send.
565unsafe impl<T: Send> Send for Vector<T> {}
566// SAFETY: Vector's safe API obeys all rules of the borrow checker, so no interior mutability
567// occurs. This means that Vector<T> can safely implement Sync when T: Sync.
568unsafe impl<T: Sync> Sync for Vector<T> {}
569
570impl<T: Clone> Clone for Vector<T> {
571 fn clone(&self) -> Self {
572 let mut vec = Self::with_cap(self.cap());
573
574 for value in self.iter() {
575 vec.push(value.clone());
576 }
577
578 vec
579 }
580}
581
582impl<T> From<Vector<T>> for Array<T> {
583 fn from(mut value: Vector<T>) -> Self {
584 // Dealloc all uninit values > len.
585 value.shrink_to_fit();
586
587 // SAFETY: A Vector contains len initialized values with the same layout and alignment as an
588 // Array.
589 let arr = unsafe { mem::transmute_copy(&value.arr) };
590 mem::forget(value);
591 arr
592 }
593}
594
595impl<T> From<Array<T>> for Vector<T> {
596 fn from(value: Array<T>) -> Self {
597 let len = value.size();
598 Vector {
599 arr: value.forget_init(),
600 len,
601 }
602 }
603}
604
605impl<T> From<Vector<T>> for Vec<T> {
606 fn from(value: Vector<T>) -> Self {
607 let (ptr, len, cap) = value.into_parts();
608 unsafe { Vec::from_parts(ptr.cast(), len, cap) }
609 }
610}
611
612impl<T> From<Vec<T>> for Vector<T> {
613 fn from(value: Vec<T>) -> Self {
614 let (ptr, len, cap) = value.into_parts();
615 unsafe { Vector::from_parts(ptr.cast(), len, cap) }
616 }
617}
618
619impl From<String> for Vector<u8> {
620 fn from(value: String) -> Self {
621 Vec::from(value).into()
622 }
623}
624
625impl TryFrom<Vector<u8>> for String {
626 type Error = <String as TryFrom<Vec<u8>>>::Error;
627
628 fn try_from(value: Vector<u8>) -> Result<Self, Self::Error> {
629 Vec::from(value).try_into()
630 }
631}
632
633impl<T: PartialEq> PartialEq for Vector<T> {
634 fn eq(&self, other: &Self) -> bool {
635 **self == **other
636 }
637}
638
639impl<T: Eq> Eq for Vector<T> {}
640
641impl<T: Hash> Hash for Vector<T> {
642 fn hash<H: Hasher>(&self, state: &mut H) {
643 (**self).hash(state);
644 }
645}
646
647impl<T: Debug> Debug for Vector<T> {
648 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
649 f.debug_struct("Vector")
650 .field_with("contents", |f| f.debug_list().entries(self.iter()).finish())
651 .field("len", &self.len)
652 .field("cap", &self.cap())
653 .finish()
654 }
655}
656
657impl<T: Debug> Display for Vector<T> {
658 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
659 write!(f, "!")?;
660 f.debug_list().entries(self.iter()).finish()
661 }
662}