1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
use std::{cell, mem, ops, ptr};

const SEGMENT_CAPACITY_LOG_2: usize = 5;
const SEGMENT_CAPACITY: usize = 1 << SEGMENT_CAPACITY_LOG_2;
const SEGMENT_CAPACITY_MASK: usize = SEGMENT_CAPACITY - 1;

struct Segment<T> {
  len: usize,
  elements: Option<Box<[T; SEGMENT_CAPACITY]>>,
}

impl<T> Segment<T> {
  unsafe fn new() -> Segment<T> {
    Segment {
      len: 0,
      elements: Some(Box::new(mem::uninitialized())),
    }
  }

  fn is_full(&self) -> bool {
    self.len >= SEGMENT_CAPACITY
  }

  /// Retrieves a reference to a slot within the segment, that may be unintialized memory.
  ///
  /// # Safety
  ///
  /// The returned reference points to initialized memory if and only if the given `index` is
  /// smaller than `self.len`.
  unsafe fn get_slot(&self, index: usize) -> &T {
    if let Some(ref elements) = self.elements {
      &elements[index]
    } else {
      panic!()
    }
  }

  /// Retrieves a mutable reference to a slot within the segment, that may be unintialized memory.
  ///
  /// # Safety
  ///
  /// The returned reference points to initialized memory if and only if the given `index` is
  /// smaller than `self.len`.
  unsafe fn get_slot_mut(&mut self, index: usize) -> &mut T {
    if let Some(ref mut elements) = self.elements {
      &mut elements[index]
    } else {
      panic!()
    }
  }
}

impl<T> Drop for Segment<T> {
  fn drop(&mut self) {
    unsafe {
      if let Some(mut elements) = mem::replace(&mut self.elements, None) {
        for i in 0..self.len {
          ptr::drop_in_place(&mut elements[i]);
        }

        mem::forget(elements);
      }
    }
  }
}

impl<T> ops::Index<usize> for Segment<T> {
  type Output = T;

  fn index(&self, index: usize) -> &<Self as ops::Index<usize>>::Output {
    if self.len <= index {
      panic!("index out of bounds")
    }

    unsafe { self.get_slot(index) }
  }
}

impl<T> std::ops::IndexMut<usize> for Segment<T> {
  fn index_mut(&mut self, index: usize) -> &mut <Self as ops::Index<usize>>::Output {
    if self.len <= index {
      panic!("index out of bounds")
    }

    unsafe { self.get_slot_mut(index) }
  }
}

/// A collection onto which new values can be appended, while still keeping references to previous
/// values valid.
///
/// # Example
///
/// This is useful as a buffer on the side of another data structure that is built incrementally.
/// For example, let's imagine we want to parse a JSON-like data format that contains only arrays
/// and strings.
///
/// The advantage of having slices and `str`s instead of `Vec`s and `String`s is that you'd then be
/// to directly pattern match against values of this type.
///
/// ```
/// use cursed_collections::AppendOnlyVec;
///
/// enum MyData<'buffers> {
///   Array(&'buffers [MyData<'buffers>]),
///   String(&'buffers str),
/// }
///
/// fn main() {
///   let string_buf = AppendOnlyVec::<String>::new();
///   let array_buf = AppendOnlyVec::<Vec<MyData>>::new();
///
///   let my_key = MyData::String(string_buf.push("name".into()));
///   let my_name = MyData::String(string_buf.push("Simon".into()));
///   let my_array = MyData::Array(array_buf.push(vec![my_key, my_name]));
///
///   match my_array {
///     MyData::Array(&[MyData::String("name"), MyData::String(name)]) => {
///       println!("Hello, {}", name)
///     }
///     _ => println!("Hello!"),
///   }
/// }
/// ```
pub struct AppendOnlyVec<T> {
  segments: cell::UnsafeCell<Vec<cell::UnsafeCell<Segment<T>>>>,
}

impl<T> AppendOnlyVec<T> {
  /// Creates an empty `AppendOnlyVec`.
  pub fn new() -> AppendOnlyVec<T> {
    AppendOnlyVec {
      segments: cell::UnsafeCell::new(vec![]),
    }
  }

  /// Consumes a `T`, appends it to the end of the vector, and returns a reference to the newly
  /// appended element.
  pub fn push(&self, element: T) -> &T {
    unsafe {
      let last_segment = self.get_segment_with_spare_capacity();

      let len = last_segment.len;
      last_segment.len += 1;

      // A simple assignment is not enough because *element_ref = element would invoke drop on
      // the previous value of *element_ref, which is uninitialized memory.
      let element_ref = last_segment.get_slot_mut(len);
      mem::forget(mem::replace(element_ref, element));
      element_ref
    }
  }

  /// Return the number of elements in the vector.
  pub fn len(&self) -> usize {
    unsafe {
      let segments = self.segments();
      if let Some(last_segment) = segments.last() {
        ((segments.len() - 1) << SEGMENT_CAPACITY_LOG_2) + (&*last_segment.get()).len
      } else {
        0
      }
    }
  }

  unsafe fn get_segment_at(&self, index: usize) -> &Segment<T> {
    let segments = self.segments();
    &*segments[index].get()
  }

  unsafe fn get_segment_with_spare_capacity(&self) -> &mut Segment<T> {
    let segments = self.segments();
    match segments.last_mut() {
      None => self.add_segment(),
      Some(segment) => {
        if (*segment.get()).is_full() {
          self.add_segment()
        } else {
          &mut *segment.get()
        }
      }
    }
  }

  unsafe fn add_segment(&self) -> &mut Segment<T> {
    let segments = self.segments();
    segments.push(cell::UnsafeCell::new(Segment::new()));
    &mut *segments.last_mut().unwrap().get()
  }

  unsafe fn segments(&self) -> &mut Vec<cell::UnsafeCell<Segment<T>>> {
    &mut *self.segments.get()
  }
}

impl<T> Default for AppendOnlyVec<T> {
  fn default() -> Self {
    Self::new()
  }
}

impl<T> ops::Index<usize> for AppendOnlyVec<T> {
  type Output = T;

  fn index(&self, index: usize) -> &Self::Output {
    unsafe {
      let segment = self.get_segment_at(index >> SEGMENT_CAPACITY_LOG_2);
      &segment[index & SEGMENT_CAPACITY_MASK]
    }
  }
}

#[cfg(test)]
mod tests {
  use super::{AppendOnlyVec, SEGMENT_CAPACITY};
  use std::ptr;

  #[test]
  fn it_works() {
    let vec = AppendOnlyVec::<String>::new();
    let s1 = vec.push("hello".into());
    let s2 = vec.push("bye".into());
    assert_eq!(&String::from("hello"), s1);
    assert_eq!(&String::from("bye"), s2);
  }

  #[test]
  fn references_still_valid_after_another_segment_is_created() {
    let vec = AppendOnlyVec::<String>::new();
    let mut references = Vec::<&String>::new();
    for i in 0..(SEGMENT_CAPACITY + 1) {
      references.push(vec.push(format!("{}", i)));
    }

    assert_eq!(&"0", &references[0]);
    assert!(ptr::eq(&vec[0], references[0]));
    assert_eq!(
      format!("{}", SEGMENT_CAPACITY).as_str(),
      references[SEGMENT_CAPACITY].as_str()
    );
  }

  #[test]
  fn index() {
    let vec = AppendOnlyVec::<String>::new();
    vec.push("hello".into());
    vec.push("bye".into());

    assert_eq!(vec[0], "hello");
    assert_eq!(vec[1], "bye");
  }

  #[test]
  #[should_panic]
  fn index_out_of_bounds() {
    let vec = AppendOnlyVec::<String>::new();
    vec.push("hello".into());
    vec.push("bye".into());
    &vec[2];
  }

  #[test]
  fn len_empty() {
    let vec = AppendOnlyVec::<String>::new();
    assert_eq!(0, vec.len())
  }

  #[test]
  fn len_1() {
    let vec = AppendOnlyVec::<String>::new();
    vec.push("hello".into());
    assert_eq!(1, vec.len())
  }

  #[test]
  fn len_multiple_segments() {
    let vec = AppendOnlyVec::<String>::new();
    for i in 0..(SEGMENT_CAPACITY + 1) {
      vec.push(format!("{}", i));
    }
    assert_eq!(33, vec.len())
  }
}