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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490

use std::any::{TypeId, Any};

use crate::anon::Anon;
use crate::iter::{
    AnonIter, 
    AnonIterMut
};

/// An Anonymously typed Vector.
/// 
/// Internally, AnonVec is a Vec<u8>. 
/// When pushing to an AnonVec, `T` is converted to `*const u8`.
/// When getting from an AnonVec, `*const u8` is converted to `T`.
/// 
/// ## Usage
/// 
/// Anon Vec is intended for use in data systems where the type or size of the values
/// stored cannot be known at compile-time.  It is a more lax approach to `Box<dyn Any>`.
/// ```
/// use anon_vec::AnonVec;
/// 
/// let mut anon = AnonVec::new::<i32>();
/// anon.push::<i32>(5);
/// anon.push::<i32>(10);
/// anon.push::<i32>(15);
/// 
/// let x = anon.get_ref::<i32>(1);
/// ```
/// `AnonVec` can also work with `Anon` values. 
/// ```
/// use anon_vec::{AnonVec, Anon};
/// use std::mem::size_of;
/// use std::any::TypeId;
/// 
/// // Create AnonVec using the size and typeid.
/// let mut vec = AnonVec::from_size(size_of::<i32>(), TypeId::of::<i32>());
/// vec.push_anon(Anon::new::<i32>(5));
/// vec.push_anon(Anon::new::<i32>(10));
/// vec.push_anon(Anon::new::<i32>(15));
/// 
/// // move index 1 out and into `anon`.
/// let anon: Anon = vec.remove_get_anon(1);
/// 
/// let x: &i32 = anon.cast_ref::<i32>();
/// ```
pub struct AnonVec {
    /// Vec<T>, represented as Vec<u8>. 
    inner: Vec<u8>,
    /// The `std::mem::size_of` each element.
    size: usize,
    /// The length of the vector, in terms of `inner.len() / size.`
    len: usize,
    /// The TypeId of this AnonVec. 
    typeid: TypeId,
}

impl AnonVec {

    // --- // Constructors // --- //

    /// Creates a new Anonymously Typed Vector in-place.
    /// 
    /// ## Usage
    /// ```
    /// use anon_vec::AnonVec;
    /// 
    /// let mut anon = AnonVec::new::<i32>();
    /// anon.push::<i32>(5);
    /// ```
    pub fn new<T>() -> Self 
    where
        T: Any + 'static,
    {
        Self {
            inner: Vec::new(),
            size: std::mem::size_of::<T>(),
            len: 0,
            typeid: TypeId::of::<T>(),
        }
    }

    /// Creates a new Anonymously Typed Vector using the 
    /// size and TypeId of the value to be stored.
    /// 
    /// ## Usage
    /// ```
    /// use anon_vec::AnonVec;
    /// use std::mem::size_of;
    /// use std::any::TypeId;
    /// 
    /// let mut anon = AnonVec::from_size(size_of::<i32>(), TypeId::of::<i32>());
    /// anon.push::<i32>(5);
    /// ```
    pub fn from_size(size: usize, typeid: TypeId) -> Self {
        Self {
            inner: Vec::new(),
            size,
            len: 0,
            typeid,
        }
    }

    /// Creates an Uninitialized Anonymously Typed Vector
    /// 
    /// MUST be initialized before access by calling init::<T>. 
    /// If you can't call init::<T>, call init_size instead.
    /// 
    /// ## Usage
    /// ```
    /// use anon_vec::AnonVec;
    /// 
    /// let mut vec = AnonVec::uninit();
    /// 
    /// if vec.is_uninit() {
    ///     vec.init::<i32>();
    /// }
    /// 
    /// // do stuff with anon_vec
    /// ```
    pub fn uninit() -> Self {
        Self {
            inner: Vec::new(),
            size: 0,
            len: 0,
            typeid: TypeId::of::<i32>(),
        }
    }

    /// Initializes a previously uninitialized AnonVec.
    /// 
    /// ## Usage
    /// ```
    /// use anon_vec::AnonVec;
    /// 
    /// let mut vec = AnonVec::uninit();
    /// 
    /// if vec.is_uninit() {
    ///     vec.init::<i32>();
    /// }
    /// 
    /// // do stuff with anon_vec
    /// ```
    pub fn init<T>(&mut self) 
    where
        T: Any + 'static,
    {
        self.size = std::mem::size_of::<T>();
        self.typeid = TypeId::of::<T>();
    }

    /// Initializes a previously uninitialized AnonVec.
    /// 
    /// ## Usage
    /// ```
    /// use anon_vec::AnonVec;
    /// use std::mem::size_of;
    /// use std::any::TypeId;
    /// 
    /// let mut vec = AnonVec::uninit();
    /// 
    /// if vec.is_uninit() {
    ///     vec.init_size(size_of::<i32>(), TypeId::of::<i32>());
    /// }
    /// 
    /// // do stuff with anon_vec
    /// ```
    pub fn init_size(&mut self, size: usize, typeid: TypeId) {
        self.size = size;
        self.typeid = typeid;
    }

    // --- // Accessors // --- //

    /// The TypeId associated with this AnonVec.
    pub fn typeid(&self) -> TypeId {
        self.typeid
    }

    /// The size, in bytes, each element of this AnonVec holds.
    pub fn size(&self) -> usize {
        self.size
    }

    /// The number of elements this AnonVec holds. (as T)
    pub fn len(&self) -> usize {
        self.len
    }

    /// Whether or not this AnonVec has a length of 0.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Whether or not the size of this AnonVec is 0.
    pub fn is_uninit(&self) -> bool {
        self.size == 0
    }

    /// Get a reference to the interior value at index as T.
    pub fn get_ref<T>(&self, index: usize) -> &T 
    where
        T: Any + 'static,
    {   
        let ptr = self.inner.as_ptr() as *const T;
        unsafe { &*(ptr.add(index)) }
    } 

    /// Get a mutable reference to the interior value at index as T.
    pub fn get_mut<T>(&mut self, index: usize) -> &mut T
    where
        T: Any + 'static,
    {
        let ptr = self.inner.as_mut_ptr() as *mut T;
        unsafe { &mut *(ptr.add(index)) }
    }

    /// Reserves `additional` number of BYTES. 
    /// If you want to reserve size_of::<T>, use `reserve` instead.
    /// 
    /// Reserves capacity for at least `additional` more elements to be inserted
    /// in the given `Vec<T>`. The collection may reserve more space to
    /// speculatively avoid frequent reallocations. After calling `reserve`,
    /// capacity will be greater than or equal to `self.len() + additional`.
    /// Does nothing if capacity is already sufficient.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut vec = vec![1];
    /// vec.reserve(10);
    /// assert!(vec.capacity() >= 11);
    /// ```
    pub fn reserve_bytes(&mut self, additional: usize) {
        self.inner.reserve(additional);
    }

    /// Reserves capacity for at least `additional` more elements to be inserted
    /// in the given `Vec<T>`. The collection may reserve more space to
    /// speculatively avoid frequent reallocations. After calling `reserve`,
    /// capacity will be greater than or equal to `self.len() + additional`.
    /// Does nothing if capacity is already sufficient.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut vec = vec![1];
    /// vec.reserve(10);
    /// assert!(vec.capacity() >= 11);
    /// ```
    pub fn reserve(&mut self, additional: usize) {
        if !self.is_uninit() {
            self.inner.reserve(additional * self.size);
        }
    }

    // --- // Operators // -- //

    /// Appends an element to the back of this AnonVec.
    pub fn push<T>(&mut self, val: T)
    where
        T: Any + 'static,
    {
        let v = &val as *const T as *const u8;
        for i in 0..self.size {
            unsafe {
                self.inner.push(*(v.add(i)))
            }
        }
        self.len += 1;
    }

    /// Appends an anonymous element to the back of this AnonVec.
    pub fn push_anon(&mut self, anon: Anon) {
        let v = anon.inner();
        for _ in 0..self.size {
            self.inner.extend(v.iter());
        }
        self.len += 1;
    }

    /// Inserts an element at `index`, moving all elements after it to the right.
    pub fn insert<T>(&mut self, val: T, index: usize) {
        let v = &val as *const T as *const u8;
        let index = index * self.size;

        for i in (0..self.size).rev() {
            unsafe {
                self.inner.insert(index, *(v.add(i)))
            }
        }
        self.len += 1;
    }

    /// Inserts an anonymous element at `index`, moving all elements after it to the right.
    pub fn insert_anon(&mut self, anon: Anon, index: usize) {
        let v = anon.inner();
        let index = index * self.size;

        for i in (0..self.size).rev() {
            self.inner.insert(index, v[i])
        }
        self.len += 1;
    }

    /// Removes an element at `index`. 
    pub fn remove(&mut self, index: usize) {
        let index = index * self.size;
        for i in (index..index + self.size).rev() {
            self.inner.remove(i);
        }
        self.len -= 1;
    }

    /// Removes and returns the element at `index`. 
    pub fn remove_get<T>(&mut self, index: usize) -> T
    where
        T: Any + Clone + 'static,
    {
        let ptr = self.inner.as_mut_ptr() as *mut T;
        let out = unsafe { &*(ptr.add(index)) }.clone();

        let index = index * self.size;
        for i in (index..index + self.size).rev() {
            self.inner.remove(i);
        }
        self.len -= 1;
        out
    }

    /// Removes and returns the element at `index` as an anonymous type.
    pub fn remove_get_anon(&mut self, index: usize) -> Anon {
        let ptr = self.inner.as_ptr();
        let out = Anon::from_ptr(ptr, self.size, self.typeid);

        let index = index * self.size;
        for i in (index..index + self.size).rev() {
            self.inner.remove(i);
        }
        self.len -= 1;
        out
    }

    /// Pops off and returns the last element in the Vec.
    pub fn pop<T>(&mut self) -> Option<T> 
    where
        T: Any + Clone + 'static,
    {
        if self.len == 0 {
            None
        } else {
            self.len -= 1;
            Some(self.remove_get::<T>(self.len() - 1))
        }
    }

    /// Pops off and returns the last element in the Vec as an Anon. 
    pub fn pop_anon(&mut self) -> Option<Anon> {
        if self.len == 0 {
            None
        } else {
            self.len -= 1;
            Some(self.remove_get_anon(self.len() - 1))
        }
    }

    /// Remove the last element after copying it into `index`. 
    /// MUCH faster than `remove`, in certain situations. 
    pub fn remove_swap(&mut self, index: usize) {
        if index == self.len - 1 {
            for _ in 0..self.size {
                self.inner.pop();
            }
        } else {
            let index = self.size * index;
            for i in (0..self.size).rev() {
                self.inner[index + i] = self.inner.pop().unwrap()
            }
        }
        self.len -= 1;
    }

    /// Immutably Iterate over this AnonVec as T.
    pub fn iter<T>(&self) -> AnonIter<T> {
        AnonIter {
            data: self.inner.as_ptr() as *const T,
            curr: 0,
            len: self.inner.len(),
        }
    } 

    /// Mutably Iterate over this AnonVec as T. 
    pub fn iter_mut<T>(&mut self) -> AnonIterMut<T> {
        AnonIterMut {
            data: self.inner.as_mut_ptr() as *mut T,
            curr: 0,
            len: self.inner.len(),
        }
    }
}

#[cfg(test)]
mod tests {

    use std::any::TypeId;

    use crate::vec::AnonVec;

    const THING: Thing = Thing { a: 1, b: 2, c: 3 };

    #[repr(C)]
    #[derive(PartialEq, Debug, Clone)]
    struct Thing {
        pub a: i32,
        pub b: i32,
        pub c: i32,
    }

    impl Thing {
        fn sum(&self) -> i32 {
            self.a + self.b + self.c
        }
    }

    #[test]
    fn new() {
        let mut anon = AnonVec::new::<Thing>();

        {
            anon.push::<Thing>(THING);
            anon.push::<Thing>(THING);
            anon.push::<Thing>(THING);
        }

        let t1 = anon.get_ref::<Thing>(0);
        let t2 = anon.get_ref::<Thing>(1);
        let t3 = anon.get_ref::<Thing>(2);

        let v = t1.sum() + t2.sum() + t3.sum();

        assert_eq!(v, 18);
    }

    #[test]
    fn from_size() {
        let mut anon = AnonVec::from_size(std::mem::size_of::<Thing>(), TypeId::of::<Thing>());

        {
            anon.push::<Thing>(THING);
            anon.push::<Thing>(THING);
            anon.push::<Thing>(THING);
        }

        let t1 = anon.get_ref::<Thing>(0);
        let t2 = anon.get_ref::<Thing>(1);
        let t3 = anon.get_ref::<Thing>(2);

        let v = t1.sum() + t2.sum() + t3.sum();

        assert_eq!(v, 18);
    }

    #[test]
    fn uninit_init() {
        let mut anon = AnonVec::uninit();

        {
            anon.init::<Thing>();
            anon.push::<Thing>(THING);
            anon.push::<Thing>(THING);
            anon.push::<Thing>(THING);
        }

        let t1 = anon.get_ref::<Thing>(0);
        let t2 = anon.get_ref::<Thing>(1);
        let t3 = anon.get_ref::<Thing>(2);

        let v = t1.sum() + t2.sum() + t3.sum();

        assert_eq!(v, 18);
    }
}