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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
//! The purpose of "persist-o-vec" is to:
//!
//! - prevent reallocation
//! - re-use freed slots fast
//! - only iter over used slots
//!
//! As such, you must allocate what you need before use up to the maximum determined
//! by the chosen indexer feature. In future there will be an option to increase
//! the capacity if required.
//!
//! ## features available
//!
//! The features available are for the size of the indexing type used internally. This
//! dictates how much extra storage is used for `Vec<T>`. The default is a `u16` which
//! means a possible 2 bytes * 2 per `T`. The maximum entries per Vec for each type are:
//!
//! - `u8` = 256
//! - `u16` = 65026
//! - `u32` = 4228250626
//! - `u64` = 17878103347812890625
//!
//! **WIP!**

use std::cmp::Ordering;
use std::mem::size_of;

#[cfg(feature = "capacity_u8_len")]
type INDEXER = u8;
#[cfg(feature = "capacity_u16_len")]
type INDEXER = u16;
#[cfg(feature = "capacity_u32_len")]
type INDEXER = u32;
#[cfg(feature = "capacity_u64_len")]
type INDEXER = u64;

/// Iteration will not always be in order
#[derive(Clone, Default)]
pub struct Persist<T> {
    entries: Vec<Option<T>>,
    /// contains the indexes to `None` slots
    free: Vec<INDEXER>,
    /// contains the indexes to used slots
    used: Vec<INDEXER>,
}

impl<T> Persist<T> {
    /// Allocate with capacity.
    ///
    /// This is the only way to create a new persistent vec.
    ///
    /// # Panics
    ///
    /// Will panic if the selected capacity is larger than the ability for
    /// `Persist` to internally index in to
    #[inline]
    pub fn with_capacity(capacity: usize) -> Persist<T> {
        let limit = (255 as INDEXER).pow(size_of::<INDEXER>() as u32) as usize;
        if capacity > limit {
            panic!("Selected capacity is larger than ability to index");
        }

        Persist {
            entries: (0..capacity).map(|_| None).collect(),
            free: (0..capacity as INDEXER).rev().collect(),
            used: Vec::with_capacity(capacity),
        }
    }

    /// Allocate with capacity and fill with values produced by a closure
    ///
    /// This is a secondary way to create a new persistent vec and is a good way
    /// to do so if you know the storage needs to be filled.
    ///
    /// # Panics
    ///
    /// Will panic if the selected capacity is larger than the ability for
    /// `Persist` to internally index in to
    #[inline]
    pub fn with_capacity_filled_by<F>(capacity: usize, func: F) -> Persist<T>
    where
        F: Fn() -> T,
    {
        let limit = (255 as INDEXER).pow(size_of::<INDEXER>() as u32) as usize;
        if capacity > limit {
            panic!("Selected capacity is larger than ability to index");
        }

        Persist {
            entries: (0..capacity).map(|_| Some(func())).collect(),
            free: Vec::with_capacity(capacity),
            used: (0..capacity as INDEXER).collect(),
        }
    }

    /// Allocate with capacity and fill with values copied from slice
    ///
    /// # Panics
    ///
    /// Will panic if the selected capacity is larger than the ability for
    /// `Persist` to internally index in to
    #[inline]
    pub fn with_capacity_from(capacity: usize, slice: &[T]) -> Persist<T>
    where
        T: Clone,
    {
        let limit = (255 as INDEXER).pow(size_of::<INDEXER>() as u32) as usize;
        if capacity > limit {
            panic!("Selected capacity is larger than ability to index");
        }

        Persist {
            entries: (0..capacity).map(|i| Some(slice[i].clone())).collect(),
            free: (slice.len() as INDEXER..capacity as INDEXER)
                .rev()
                .collect(),
            used: (0..slice.len() as INDEXER).collect(),
        }
    }

    /// Reserve extra capacity. This may move the allocations and invalidate any
    /// pointers that are held to stored data.
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        let limit = (255 as INDEXER).pow(size_of::<INDEXER>() as u32) as usize;
        if self.entries.len() + additional > limit {
            panic!("Additional capacity is larger than ability to index");
        }

        let old_cap = self.entries.len();
        let new_cap = self.entries.len() + additional;
        self.entries.reserve_exact(additional);
        for _ in old_cap..new_cap {
            self.entries.push(None)
        }
        for i in old_cap..new_cap {
            self.insert_free_record(i as INDEXER);
        }
    }

    /// Returns the actual used length regardless of capacity
    #[inline]
    pub fn len(&self) -> usize {
        self.used.len()
    }

    #[inline]
    pub fn clear(&mut self) {
        let capacity = self.entries.capacity();
        for entry in self.entries.iter_mut() {
            *entry = None;
        }
        self.free = (0..capacity as INDEXER).rev().collect();
        self.used.clear();
    }

    #[inline]
    pub fn get(&self, index: usize) -> Option<&T> {
        if let Some(value) = self.entries.get(index) {
            return value.as_ref();
        }
        None
    }

    #[inline]
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        if let Some(value) = self.entries.get_mut(index) {
            return value.as_mut();
        }
        None
    }

    /// Check if there is a value at this index
    #[inline]
    pub fn is_index_live(&self, index: usize) -> bool {
        if let Some(value) = self.entries.get(index) {
            if value.is_some() {
                return true;
            }
        }
        false
    }

    // TODO: feature to expand/reallocate if required
    /// Push `T` on to storage.
    ///
    /// A push is not guaranteed to push in any
    /// particular order if the internal storage has empty locations (typical after
    /// many `remove`). For this reason it will return the index pushed to.
    ///
    /// Returns `None` if there are no free slots left
    #[inline]
    pub fn push(&mut self, value: T) -> Option<usize> {
        if let Some(free_idx) = self.free.pop() {
            self.entries[free_idx as usize] = Some(value);
            // keep self.used ordered
            self.insert_used_record(free_idx);
            return Some(free_idx as usize);
        }
        None
    }

    /// Insert `T` at location. Returns existing value in that location or `None`.
    ///
    /// # Panics
    ///
    /// Will panic is the index is out of range
    #[inline]
    pub fn insert(&mut self, index: usize, value: T) -> Option<T> {
        // check if used first
        if self.entries[index].is_none() {
            if let Ok(free_idx) = self.free.binary_search_by(|probe| {
                // swap ordering so order is big-to-little
                if *probe > index as INDEXER {
                    return Ordering::Less;
                } else if *probe < index as INDEXER {
                    return Ordering::Greater;
                }
                Ordering::Equal
            }) {
                let loc = self.free.remove(free_idx);
                self.insert_used_record(loc);
            }
        }
        let mut entry = Some(value);
        std::mem::swap(&mut self.entries[index], &mut entry);
        return entry;
    }

    /// We need to keep the free records in reverse order so we can generally push
    /// items to the first free slot in ordering from 0-n
    fn insert_free_record(&mut self, index: INDEXER) {
        if let Some(idx) = self
            .free
            .binary_search_by(|probe| {
                // swap ordering so order is big-to-little
                if *probe > index {
                    return Ordering::Less;
                }
                Ordering::Greater
            })
            // we should never find the value we need so use what err returns
            .err()
        {
            self.free.insert(idx, index);
        };
    }

    fn insert_used_record(&mut self, index: INDEXER) {
        // we should never find the value we need so use what err returns
        if let Some(idx) = self.used.binary_search(&index).err() {
            self.used.insert(idx, index);
        };
    }

    /// Pop the last value in the `Persist`
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        if let Some(index) = self.used.pop() {
            let value = std::mem::take(&mut self.entries[index as usize]);
            self.insert_free_record(index);
            return value;
        }
        None
    }

    /// Remove the item at this index and return it if it exists. Does not shift
    /// elements after it to the left.
    #[inline]
    pub fn remove(&mut self, index: usize) -> Option<T> {
        if self.entries[index].is_some() {
            if let Ok(pos) = self.used.binary_search(&(index as INDEXER)) {
                let i = self.used.remove(pos);
                self.insert_free_record(i);
            }
        }
        return std::mem::take(&mut self.entries[index]);
    }

    #[inline]
    pub fn iter(&self) -> Iter<T> {
        Iter {
            entries: &self.entries,
            used: &self.used,
            used_index: 0,
        }
    }

    #[inline]
    pub fn iter_mut(&mut self) -> IterMut<T> {
        IterMut {
            entries: &mut self.entries,
            used: &self.used,
            used_index: 0,
        }
    }
}

#[derive(Debug)]
pub struct Iter<'a, T> {
    entries: &'a [Option<T>],
    used: &'a [INDEXER],
    used_index: usize,
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    #[inline]
    fn next(&mut self) -> Option<&'a T> {
        if self.used_index == self.used.len() {
            return None;
        }

        unsafe {
            let index = *self.used.get_unchecked(self.used_index) as usize;
            let value = self.entries.get_unchecked(index).as_ref();
            self.used_index += 1;
            value
        }
    }
}

#[derive(Debug)]
pub struct IterMut<'a, T> {
    entries: &'a mut [Option<T>],
    used: &'a [INDEXER],
    used_index: usize,
}

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;

    #[inline]
    fn next(&mut self) -> Option<&'a mut T> {
        if self.used_index == self.used.len() {
            return None;
        }

        unsafe {
            let index = *self.used.get_unchecked(self.used_index) as usize;

            // Only used indexes are ever accessed
            let value = self.entries.get_unchecked_mut(index) as *mut Option<T>;
            self.used_index += 1;
            // working around the lifetime elision issue here
            (*value).as_mut()
        }
    }
}

/// Total capacity will be set from the length of the slice
impl<T: Clone> From<&[T]> for Persist<T> {
    fn from(s: &[T]) -> Persist<T> {
        let capacity = s.len();
        Persist::with_capacity_from(capacity, s)
    }
}

/// Total capacity will be set from the length of the slice
impl<T: Clone> From<&mut [T]> for Persist<T> {
    fn from(s: &mut [T]) -> Persist<T> {
        let capacity = s.len();
        Persist::with_capacity_from(capacity, s)
    }
}

#[cfg(test)]
mod tests {
    use crate::{Persist, INDEXER};
    use std::mem::size_of;

    #[test]
    fn with_capacity() {
        let p: Persist<u32> = Persist::with_capacity(10);
        assert_eq!(p.entries.capacity(), 10);
    }

    #[test]
    fn return_none_if_push_when_full() {
        let mut p: Persist<u32> = Persist::with_capacity(30);

        for i in 0..30 {
            assert!(p.push(i).is_some());
        }

        assert!(p.push(31).is_none());
    }

    #[test]
    fn get() {
        let mut p: Persist<u32> = Persist::with_capacity(10);

        p.push(13);
        p.push(14);
        p.push(15);

        let two = p.get(1).unwrap();
        assert_eq!(*two, 14);
    }

    #[test]
    fn get_mut() {
        let mut p: Persist<u32> = Persist::with_capacity(10);

        p.push(13);
        p.push(14);
        p.push(15);

        {
            let two = p.get_mut(1).unwrap();
            *two *= 2;
        }
        let two = p.get(1).unwrap();
        assert_eq!(*two, 28);
    }

    #[test]
    fn index_validation() {
        let mut p: Persist<u32> = Persist::with_capacity(10);

        p.push(13);
        p.push(14);

        assert!(p.is_index_live(0));
        assert!(p.is_index_live(1));
        assert!(!p.is_index_live(3));
    }

    #[test]
    fn reserve() {
        let mut p: Persist<u32> = Persist::with_capacity(10);

        p.push(13);
        p.push(14);
        p.push(15);

        assert_eq!(p.free.len(), 7);
        assert_eq!(p.entries.len(), 10);

        p.reserve(10);

        assert_eq!(p.free.len(), 17);
        assert_eq!(p.entries.len(), 20);
    }

    #[test]
    fn clear() {
        let p: Persist<u32> = Persist::with_capacity(10);
        assert_eq!(p.free.len(), 10);
        assert_eq!(p.free[9], 0);
        assert_eq!(p.free[0], 9);
    }

    #[test]
    fn pop() {
        let mut p: Persist<u32> = Persist::with_capacity(10);

        p.push(13);
        p.push(14);
        p.push(15);

        assert_eq!(p.used.len(), 3);
        assert_eq!(p.free.len(), 7);

        p.pop();

        assert_eq!(p.used.len(), 2);
        assert_eq!(p.free.len(), 8);
    }

    #[test]
    fn remove() {
        #[derive(Debug, PartialOrd, PartialEq)]
        struct Heading {
            x: u32,
        }

        let mut p: Persist<Heading> = Persist::with_capacity(50);

        for i in 0..50 {
            p.push(Heading { x: i });
        }
        assert_eq!(p.used.len(), 50);

        let r = p.remove(10);
        assert_eq!(r, Some(Heading { x: 10 }));
        assert!(p.entries[10].is_none());
        assert_eq!(p.used.len(), 49);
        assert_eq!(p.free.len(), 1);

        let r = p.remove(20);
        assert_eq!(r, Some(Heading { x: 20 }));
        assert!(p.entries[20].is_none());
        assert_eq!(p.used.len(), 48);
        assert_eq!(p.free.len(), 2);

        let r = p.remove(30);
        assert_eq!(r, Some(Heading { x: 30 }));
        assert!(p.entries[30].is_none());
        assert_eq!(p.used.len(), 47);
        assert_eq!(p.free.len(), 3);

        let r = p.remove(22);
        assert_eq!(r, Some(Heading { x: 22 }));
        assert!(p.entries[22].is_none());
        assert_eq!(p.used.len(), 46);
        assert_eq!(p.free.len(), 4);
    }

    #[test]
    fn insert() {
        let mut p: Persist<u32> = Persist::with_capacity(10);

        p.push(13);
        p.push(14);
        p.push(15);

        assert_eq!(p.used.len(), 3);
        assert_eq!(p.free.len(), 7);

        let previous = p.insert(0, 16).unwrap();
        assert_eq!(previous, 13);
        assert_eq!(p.get(0), Some(&16));
        assert_eq!(p.free.len(), 7);
        assert_eq!(p.used.len(), 3);

        assert!(p.insert(5, 17).is_none());
        assert_eq!(p.get(5), Some(&17));
        assert_eq!(p.free.len(), 6);
        assert_eq!(p.used.len(), 4);
    }

    #[test]
    fn iter() {
        #[derive(Debug)]
        struct Heading {
            x: usize,
        }

        let mut p: Persist<Heading> = Persist::with_capacity(10);

        p.push(Heading { x: 13 });
        p.push(Heading { x: 14 });
        p.push(Heading { x: 15 });
        assert_eq!(p.used.len(), 3);

        let mut accum = 0;
        for (i, x) in p.iter().enumerate() {
            assert_eq!(x.x, 13 + i);
            accum += x.x;
        }
        assert_eq!(accum, 42);
    }

    #[test]
    fn iter_mut() {
        #[derive(Debug)]
        struct Heading {
            x: u32,
        }

        let mut p: Persist<Heading> = Persist::with_capacity(10);

        p.push(Heading { x: 6 });
        p.push(Heading { x: 6 });
        p.push(Heading { x: 6 });
        assert_eq!(p.used.len(), 3);

        for x in p.iter_mut() {
            x.x += 1;
        }

        for x in p.iter() {
            assert_eq!(x.x, 7);
        }
    }

    #[test]
    fn iter_over_removed() {
        #[derive(Debug, PartialOrd, PartialEq)]
        struct Heading {
            x: u32,
        }

        let mut p: Persist<Heading> = Persist::with_capacity(50);

        for i in 0..50 {
            p.push(Heading { x: i });
        }
        assert_eq!(p.used.len(), 50);

        let r = p.remove(10);
        assert_eq!(r, Some(Heading { x: 10 }));
        assert!(p.entries[10].is_none());

        let r = p.remove(20);
        assert_eq!(r, Some(Heading { x: 20 }));
        assert!(p.entries[20].is_none());

        let r = p.remove(30);
        assert_eq!(r, Some(Heading { x: 30 }));
        assert!(p.entries[30].is_none());

        for head in p.iter() {
            assert_ne!(head.x, 10);
            assert_ne!(head.x, 20);
            assert_ne!(head.x, 30);
        }
    }

    #[cfg(feature = "capacity_u8_len")]
    #[test]
    #[should_panic]
    fn panic_if_cap_gt_u8() {
        let limit = (255 as INDEXER).pow(size_of::<INDEXER>() as u32) as usize;
        let _: Persist<u8> = Persist::with_capacity(limit + 1);
    }

    #[cfg(feature = "capacity_u16_len")]
    #[test]
    #[should_panic]
    fn panic_if_cap_gt_u16() {
        let limit = (255 as INDEXER).pow(size_of::<INDEXER>() as u32) as usize;
        // actual addressing is 0 to 65025, so bump up by 1
        let _: Persist<u8> = Persist::with_capacity(limit + 1);
    }

    #[cfg(feature = "capacity_u32_len")]
    #[test]
    #[should_panic]
    fn panic_if_cap_gt_u32() {
        let limit = (255 as INDEXER).pow(size_of::<INDEXER>() as u32) as usize;
        let _: Persist<u8> = Persist::with_capacity(limit + 1);
    }

    #[cfg(feature = "capacity_u64_len")]
    #[test]
    #[should_panic]
    fn panic_if_cap_gt_u64() {
        let limit = (255 as INDEXER).pow(size_of::<INDEXER>() as u32) as usize;
        let _: Persist<u8> = Persist::with_capacity(limit + 1);
    }

    #[cfg(feature = "capacity_u16_len")]
    #[test]
    fn populate() {
        const LIMIT: usize = 65025;

        let mut persist = Persist::with_capacity(LIMIT);
        for _ in 0..LIMIT {
            persist.push(10);
        }

        for i in 0..LIMIT {
            persist.remove(i);
        }
    }

    #[test]
    fn pst_remove_and_push() {
        #[cfg(feature = "capacity_u8_len")]
        const LIMIT: usize = 255; //65025;
        #[cfg(any(
            feature = "capacity_u16_len",
            feature = "capacity_u32_len",
            feature = "capacity_u64_len"
        ))]
        const LIMIT: usize = 10_000; //65025;

        struct Velocity(f32);

        let mut persist = Persist::with_capacity(LIMIT);
        assert_eq!(persist.free.len(), LIMIT);

        for _ in 0..LIMIT {
            persist.push(Velocity(1.0));
        }
        assert_eq!(persist.used.len(), LIMIT);

        let mut a = 0.0;
        for _ in 0..100 {
            let b = persist.remove(9).unwrap();
            a += b.0;
            let b = persist.remove(20).unwrap();
            a += b.0;
            let b = persist.remove(77).unwrap();
            a += b.0;
            let b = persist.remove(4).unwrap();
            a += b.0;
            let b = persist.remove(100).unwrap();
            a += b.0;
            let b = persist.remove(200).unwrap();
            a += b.0;
            let b = persist.remove(222).unwrap();
            a += b.0;

            persist.push(Velocity(1.0));
            persist.push(Velocity(1.0));
            persist.push(Velocity(1.0));
            persist.push(Velocity(1.0));
            persist.push(Velocity(1.0));
            persist.push(Velocity(1.0));
            persist.push(Velocity(1.0));
        }
    }

    #[test]
    fn from_slice_reserve() {
        let ar = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        let mut persist = Persist::from(&ar[..]);
        assert_eq!(persist.len(), 10);
        persist.reserve(10);
        assert_eq!(persist.len(), 10);
        assert_eq!(persist.entries.len(), 20);
    }

    #[test]
    #[should_panic]
    fn panic_out_of_bounds() {
        let ar = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        let mut persist = Persist::from(&ar[..]);
        assert_eq!(persist.len(), 10);
        persist.insert(10, 10);
    }

    #[test]
    fn insert_at_end() {
        let mut p: Persist<u32> = Persist::with_capacity(10);

        p.insert(9, 15);

        let x = p.get(9).unwrap();
        assert_eq!(*x, 15);

        let mut accum = 0;
        for (i, v) in p.iter().enumerate() {
            assert_eq!(i, 0);
            assert_eq!(*v, 15);
            accum += 1;
        }
        assert_eq!(accum, 1);

        let mut accum = 0;
        for (i, v) in p.iter_mut().enumerate() {
            assert_eq!(i, 0);
            assert_eq!(*v, 15);
            accum += 1;
        }
        assert_eq!(accum, 1);
    }
}