|
| 1 | +struct Vec<T> { |
| 2 | + slice: [T] |
| 3 | +} |
| 4 | + |
| 5 | +// A mutable vector type implemented as a wrapper around immutable slices. |
| 6 | +// A separate type is technically not needed but helps differentiate which operations are mutable. |
| 7 | +impl<T> Vec<T> { |
| 8 | + fn new() -> Self { |
| 9 | + Self { slice: [] } |
| 10 | + } |
| 11 | + |
| 12 | + // Create a Vec containing each element from the given slice. |
| 13 | + // Mutations to the resulting Vec will not affect the original slice. |
| 14 | + fn from_slice(slice: [T]) -> Self { |
| 15 | + Self { slice } |
| 16 | + } |
| 17 | + |
| 18 | + /// Get an element from the vector at the given index. |
| 19 | + /// Panics if the given index |
| 20 | + /// points beyond the end of the vector. |
| 21 | + fn get(&mut self, index: Field) -> T { |
| 22 | + self.slice[index] |
| 23 | + } |
| 24 | + |
| 25 | + /// Push a new element to the end of the vector, returning a |
| 26 | + /// new vector with a length one greater than the |
| 27 | + /// original unmodified vector. |
| 28 | + fn push(&mut self, elem: T) { |
| 29 | + self.slice = self.slice.push_back(elem); |
| 30 | + } |
| 31 | + |
| 32 | + /// Pop an element from the end of the given vector, returning |
| 33 | + /// a new vector with a length of one less than the given vector, |
| 34 | + /// as well as the popped element. |
| 35 | + /// Panics if the given vector's length is zero. |
| 36 | + fn pop(&mut self) -> T { |
| 37 | + let (popped_slice, last_elem) = self.slice.pop_back(); |
| 38 | + self.slice = popped_slice; |
| 39 | + last_elem |
| 40 | + } |
| 41 | + |
| 42 | + /// Insert an element at a specified index, shifting all elements |
| 43 | + /// after it to the right |
| 44 | + fn insert(&mut self, index: Field, elem: T) { |
| 45 | + self.slice = self.slice.insert(index, elem); |
| 46 | + } |
| 47 | + |
| 48 | + /// Remove an element at a specified index, shifting all elements |
| 49 | + /// after it to the left, returning the removed element |
| 50 | + fn remove(&mut self, index: Field) -> T { |
| 51 | + let (new_slice, elem) = self.slice.remove(index); |
| 52 | + self.slice = new_slice; |
| 53 | + elem |
| 54 | + } |
| 55 | + |
| 56 | + /// Returns the number of elements in the vector |
| 57 | + fn len(self: Self) -> Field { |
| 58 | + self.slice.len() |
| 59 | + } |
| 60 | +} |
0 commit comments