forked from LukasKalbertodt/stable-vec
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1751 lines (1638 loc) · 59.2 KB
/
lib.rs
File metadata and controls
1751 lines (1638 loc) · 59.2 KB
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A `Vec<T>`-like collection which guarantees stable indices and features
//! O(1) deletion of elements.
//!
//! You can find nearly all the relevant documentation on the type
//! [`StableVecFacade`]. This is the main type which is configurable over the
//! core implementation. To use a pre-configured stable vector, use
//! [`StableVec`].
//!
//! This crate uses `#![no_std]` but requires the `alloc` crate.
//!
//!
//! # Why?
//!
//! The standard `Vec<T>` always stores all elements contiguously. While this
//! has many advantages (most notable: cache friendliness), it has the
//! disadvantage that you can't simply remove an element from the middle; at
//! least not without shifting all elements after it to the left. And this has
//! two major drawbacks:
//!
//! 1. It has a linear O(n) time complexity
//! 2. It invalidates all indices of the shifted elements
//!
//! Invalidating an index means that a given index `i` who referred to an
//! element `a` before, now refers to another element `b`. On the contrary, a
//! *stable* index means, that the index always refers to the same element.
//!
//! Stable indices are needed in quite a few situations. One example are graph
//! data structures (or complex data structures in general). Instead of
//! allocating heap memory for every node and edge, all nodes and all edges are
//! stored in a vector (each). But how does the programmer unambiguously refer
//! to one specific node? A pointer is not possible due to the reallocation
//! strategy of most dynamically growing arrays (the pointer itself is not
//! *stable*). Thus, often the index is used.
//!
//! But in order to use the index, it has to be stable. This is one example,
//! where this data structure comes into play.
//!
//!
//! # How?
//!
//! We can trade O(1) deletions and stable indices for a higher memory
//! consumption.
//!
//! When `StableVec::remove()` is called, the element is just marked as
//! "deleted" (and the actual element is dropped), but other than that, nothing
//! happens. This has the very obvious disadvantage that deleted objects (so
//! called empty slots) just waste space. This is also the most important thing
//! to understand:
//!
//! The memory requirement of this data structure is `O(|inserted elements|)`;
//! instead of `O(|inserted elements| - |removed elements|)`. The latter is the
//! memory requirement of normal `Vec<T>`. Thus, if deletions are far more
//! numerous than insertions in your situation, then this data structure is
//! probably not fitting your needs.
//!
//!
//! # Why not?
//!
//! As mentioned above, this data structure is rather simple and has many
//! disadvantages on its own. Here are some reason not to use it:
//!
//! - You don't need stable indices or O(1) removal
//! - Your deletions significantly outnumber your insertions
//! - You want to choose your keys/indices
//! - Lookup times do not matter so much to you
//!
//! Especially in the last two cases, you could consider using a `HashMap` with
//! integer keys, best paired with a fast hash function for small keys.
//!
//! If you not only want stable indices, but stable pointers, you might want
//! to use something similar to a linked list. Although: think carefully about
//! your problem before using a linked list.
//!
//!
//! # Use of `unsafe` in this crate
//!
//! Unfortunately, implementing the features of this crate in a fast manner
//! requires `unsafe`. This was measured in micro-benchmarks (included in this
//! repository) and on a larger project using this crate. Thus, the use of
//! `unsafe` is measurement-guided and not just because it was assumed `unsafe`
//! makes things faster.
//!
//! This crate takes great care to ensure that all instances of `unsafe` are
//! actually safe. All methods on the (low level) `Core` trait have extensive
//! documentation of preconditions, invariants and postconditions. Comments in
//! functions usually describe why `unsafe` is safe. This crate contains a
//! fairly large number of unit tests and some tests with randomized input.
//! These tests are executed with `miri` to try to catch UB caused by invalid
//! `unsafe` code.
//!
//! That said, of course it cannot be guaranteed this crate is perfectly safe.
//! If you think you found an instance of incorrect usage of `unsafe` or any
//! UB, don't hesitate to open an issue immediately. Also, if you find `unsafe`
//! code that is not necessary and you can show that removing it does not
//! decrease execution speed, please also open an issue or PR!
//!
#![deny(missing_debug_implementations)]
#![deny(broken_intra_doc_links)]
// ----- Deal with `no_std` stuff --------------------------------------------
#![no_std]
// Import the real `std` for tests.
#[cfg(test)]
#[macro_use]
extern crate std;
// When compiling in a normal way, we use this compatibility layer that
// reexports symbols from `core` and `alloc` under the name `std`. This is just
// convenience so that all other imports in this crate can just use `std`.
#[cfg(not(test))]
extern crate no_std_compat as std;
// ---------------------------------------------------------------------------
use std::{
prelude::v1::*,
cmp,
fmt,
iter::FromIterator,
mem,
ops::{Index, IndexMut},
};
use crate::{
core::{Core, DefaultCore, OwningCore, OptionCore, BitVecCore},
iter::{Indices, Iter, IterMut, IntoIter, Values, ValuesMut},
};
#[cfg(test)]
mod tests;
pub mod core;
pub mod iter;
/// A stable vector with the default core implementation.
pub type StableVec<T> = StableVecFacade<T, DefaultCore<T>>;
/// A stable vector which stores the "deleted information" inline. This is very
/// close to `Vec<Option<T>>`.
///
/// This is particularly useful if `T` benefits from "null optimization", i.e.
/// if `size_of::<T>() == size_of::<Option<T>>()`.
pub type InlineStableVec<T> = StableVecFacade<T, OptionCore<T>>;
/// A stable vector which stores the "deleted information" externally in a bit
/// vector.
pub type ExternStableVec<T> = StableVecFacade<T, BitVecCore<T>>;
/// A `Vec<T>`-like collection which guarantees stable indices and features
/// O(1) deletion of elements.
///
///
/// # Terminology and overview of a stable vector
///
/// A stable vector has slots. Each slot can either be filled or empty. There
/// are three numbers describing a stable vector (each of those functions runs
/// in O(1)):
///
/// - [`capacity()`][StableVecFacade::capacity]: the total number of slots
/// (filled and empty).
/// - [`num_elements()`][StableVecFacade::num_elements]: the number of filled
/// slots.
/// - [`next_push_index()`][StableVecFacade::next_push_index]: the index of the
/// first slot (i.e. with the smallest index) that was never filled. This is
/// the index that is returned by [`push`][StableVecFacade::push]. This
/// implies that all filled slots have indices smaller than
/// `next_push_index()`.
///
/// Here is an example visualization (with `num_elements = 4`).
///
/// ```text
/// 0 1 2 3 4 5 6 7 8 9 10
/// ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
/// │ a │ - │ b │ c │ - │ - │ d │ - │ - │ - │
/// └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
/// ↑ ↑
/// next_push_index capacity
/// ```
///
/// Unlike `Vec<T>`, `StableVecFacade` allows access to all slots with indices
/// between 0 and `capacity()`. In particular, it is allowed to call
/// [`insert`][StableVecFacade::insert] with all indices smaller than
/// `capacity()`.
///
///
/// # The Core implementation `C`
///
/// You might have noticed the type parameter `C`. There are actually multiple
/// ways how to implement the abstact data structure described above. One might
/// basically use a `Vec<Option<T>>`. But there are other ways, too.
///
/// Most of the time, you can simply use the alias [`StableVec`] which uses the
/// [`DefaultCore`]. This is fine for almost all cases. That's why all
/// documentation examples use that type instead of the generic
/// `StableVecFacade`.
///
///
/// # Implemented traits
///
/// This type implements a couple of traits. Some of those implementations
/// require further explanation:
///
/// - `Clone`: the cloned instance is exactly the same as the original,
/// including empty slots.
/// - `Extend`, `FromIterator`, `From<AsRef<[T]>>`: these impls work as if all
/// of the source elements are just `push`ed onto the stable vector in order.
/// - `PartialEq<Self>`/`Eq`: empty slots, capacity, `next_push_index` and the
/// indices of elements are all checked. In other words: all observable
/// properties of the stable vectors need to be the same for them to be
/// "equal".
/// - `PartialEq<[B]>`/`PartialEq<Vec<B>>`: capacity, `next_push_index`, empty
/// slots and indices are ignored for the comparison. It is equivalent to
/// `sv.iter().eq(vec)`.
///
/// # Overview of important methods
///
/// (*there are more methods than mentioned in this overview*)
///
/// **Creating a stable vector**
///
/// - [`new`][StableVecFacade::new]
/// - [`with_capacity`][StableVecFacade::with_capacity]
/// - [`FromIterator::from_iter`](#impl-FromIterator<T>)
///
/// **Adding and removing elements**
///
/// - [`push`][StableVecFacade::push]
/// - [`insert`][StableVecFacade::insert]
/// - [`remove`][StableVecFacade::remove]
///
/// **Accessing elements**
///
/// - [`get`][StableVecFacade::get] and [`get_mut`][StableVecFacade::get_mut]
/// (returns `Option<&T>` and `Option<&mut T>`)
/// - [the `[]` index operator](#impl-Index<usize>) (returns `&T` or `&mut T`)
/// - [`remove`][StableVecFacade::remove] (returns `Option<T>`)
///
/// **Stable vector specifics**
///
/// - [`has_element_at`][StableVecFacade::has_element_at]
/// - [`next_push_index`][StableVecFacade::next_push_index]
/// - [`is_compact`][StableVecFacade::is_compact]
///
#[derive(Clone)]
pub struct StableVecFacade<T, C: Core<T>> {
core: OwningCore<T, C>,
num_elements: usize,
}
impl<T, C: Core<T>> StableVecFacade<T, C> {
/// Constructs a new, empty stable vector.
///
/// The stable-vector will not allocate until elements are pushed onto it.
pub fn new() -> Self {
Self {
core: OwningCore::new(C::new()),
num_elements: 0,
}
}
/// Constructs a new, empty stable vector with the specified capacity.
///
/// The stable-vector will be able to hold exactly `capacity` elements
/// without reallocating. If `capacity` is 0, the stable-vector will not
/// allocate any memory. See [`reserve`][StableVecFacade::reserve] for more
/// information.
pub fn with_capacity(capacity: usize) -> Self {
let mut out = Self::new();
out.reserve_exact(capacity);
out
}
/// Inserts the new element `elem` at index `self.next_push_index` and
/// returns said index.
///
/// The inserted element will always be accessible via the returned index.
///
/// This method has an amortized runtime complexity of O(1), just like
/// `Vec::push`.
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::new();
/// let star_idx = sv.push('★');
/// let heart_idx = sv.push('♥');
///
/// assert_eq!(sv.get(heart_idx), Some(&'♥'));
///
/// // After removing the star we can still use the heart's index to access
/// // the element!
/// sv.remove(star_idx);
/// assert_eq!(sv.get(heart_idx), Some(&'♥'));
/// ```
pub fn push(&mut self, elem: T) -> usize {
let index = self.core.len();
self.reserve(1);
unsafe {
// Due to `reserve`, the core holds at least one empty slot, so we
// know that `index` is smaller than the capacity. We also know
// that at `index` there is no element (the definition of `len`
// guarantees this).
self.core.set_len(index + 1);
self.core.insert_at(index, elem);
}
self.num_elements += 1;
index
}
/// Inserts the given value at the given index.
///
/// If the slot at `index` is empty, the `elem` is inserted at that
/// position and `None` is returned. If there is an existing element `x` at
/// that position, that element is replaced by `elem` and `Some(x)` is
/// returned. The `next_push_index` is adjusted accordingly if `index >=
/// next_push_index()`.
///
///
/// # Panics
///
/// Panics if the index is `>= self.capacity()`.
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::new();
/// let star_idx = sv.push('★');
/// let heart_idx = sv.push('♥');
///
/// // Inserting into an empty slot (element was deleted).
/// sv.remove(star_idx);
/// assert_eq!(sv.num_elements(), 1);
/// assert_eq!(sv.insert(star_idx, 'x'), None);
/// assert_eq!(sv.num_elements(), 2);
/// assert_eq!(sv[star_idx], 'x');
///
/// // We can also reserve memory (create new empty slots) and insert into
/// // such a new slot. Note that that `next_push_index` gets adjusted.
/// sv.reserve_for(5);
/// assert_eq!(sv.insert(5, 'y'), None);
/// assert_eq!(sv.num_elements(), 3);
/// assert_eq!(sv.next_push_index(), 6);
/// assert_eq!(sv[5], 'y');
///
/// // Inserting into a filled slot replaces the value and returns the old
/// // value.
/// assert_eq!(sv.insert(heart_idx, 'z'), Some('♥'));
/// assert_eq!(sv[heart_idx], 'z');
/// ```
pub fn insert(&mut self, index: usize, mut elem: T) -> Option<T> {
// If the index is out of bounds, we cannot insert the new element.
if index >= self.core.cap() {
panic!(
"`index ({}) >= capacity ({})` in `StableVecFacade::insert`",
index,
self.core.cap(),
);
}
if self.has_element_at(index) {
unsafe {
// We just checked there is an element at that position, so
// this is fine.
mem::swap(self.core.get_unchecked_mut(index), &mut elem);
}
Some(elem)
} else {
if index >= self.core.len() {
// Due to the bounds check above, we know that `index + 1` is ≤
// `capacity`.
unsafe {
self.core.set_len(index + 1);
}
}
unsafe {
// `insert_at` requires that `index < cap` and
// `!has_element_at(index)`. Both of these conditions are met
// by the two explicit checks above.
self.core.insert_at(index, elem);
}
self.num_elements += 1;
None
}
}
/// Removes and returns the element at position `index`. If the slot at
/// `index` is empty, nothing is changed and `None` is returned.
///
/// This simply marks the slot at `index` as empty. The elements after the
/// given index are **not** shifted to the left. Thus, the time complexity
/// of this method is O(1).
///
/// # Panic
///
/// Panics if `index >= self.capacity()`.
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::new();
/// let star_idx = sv.push('★');
/// let heart_idx = sv.push('♥');
///
/// assert_eq!(sv.remove(star_idx), Some('★'));
/// assert_eq!(sv.remove(star_idx), None); // the star was already removed
///
/// // We can use the heart's index here. It has not been invalidated by
/// // the removal of the star.
/// assert_eq!(sv.remove(heart_idx), Some('♥'));
/// assert_eq!(sv.remove(heart_idx), None); // the heart was already removed
/// ```
pub fn remove(&mut self, index: usize) -> Option<T> {
// If the index is out of bounds, we cannot insert the new element.
if index >= self.core.cap() {
panic!(
"`index ({}) >= capacity ({})` in `StableVecFacade::remove`",
index,
self.core.cap(),
);
}
if self.has_element_at(index) {
// We checked with `Self::has_element_at` that the conditions for
// `remove_at` are met.
let elem = unsafe {
self.core.remove_at(index)
};
self.num_elements -= 1;
Some(elem)
} else {
None
}
}
/// Removes all elements from this collection.
///
/// After calling this, `num_elements()` will return 0. All indices are
/// invalidated. However, no memory is deallocated, so the capacity stays
/// as it was before. `self.next_push_index` is 0 after calling this method.
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&['a', 'b']);
///
/// sv.clear();
/// assert_eq!(sv.num_elements(), 0);
/// assert!(sv.capacity() >= 2);
/// ```
pub fn clear(&mut self) {
self.core.clear();
self.num_elements = 0;
}
/// Returns a reference to the element at the given index, or `None` if
/// there exists no element at that index.
///
/// If you are calling `unwrap()` on the result of this method anyway,
/// rather use the index operator instead: `stable_vec[index]`.
pub fn get(&self, index: usize) -> Option<&T> {
if self.has_element_at(index) {
// We might call this, because we checked both conditions via
// `Self::has_element_at`.
let elem = unsafe {
self.core.get_unchecked(index)
};
Some(elem)
} else {
None
}
}
/// Returns a mutable reference to the element at the given index, or
/// `None` if there exists no element at that index.
///
/// If you are calling `unwrap()` on the result of this method anyway,
/// rather use the index operator instead: `stable_vec[index]`.
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
if self.has_element_at(index) {
// We might call this, because we checked both conditions via
// `Self::has_element_at`.
let elem = unsafe {
self.core.get_unchecked_mut(index)
};
Some(elem)
} else {
None
}
}
/// Returns a reference to the element at the given index without checking
/// the index.
///
/// # Security
///
/// When calling this method `self.has_element_at(index)` has to be `true`,
/// otherwise this method's behavior is undefined! This requirement implies
/// the requirement `index < self.next_push_index()`.
pub unsafe fn get_unchecked(&self, index: usize) -> &T {
self.core.get_unchecked(index)
}
/// Returns a mutable reference to the element at the given index without
/// checking the index.
///
/// # Security
///
/// When calling this method `self.has_element_at(index)` has to be `true`,
/// otherwise this method's behavior is undefined! This requirement implies
/// the requirement `index < self.next_push_index()`.
pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
self.core.get_unchecked_mut(index)
}
/// Returns `true` if there exists an element at the given index (i.e. the
/// slot at `index` is *not* empty), `false` otherwise.
///
/// An element is said to exist if the index is not out of bounds and the
/// slot at the given index is not empty. In particular, this method can
/// also be called with indices larger than the current capacity (although,
/// `false` is always returned in those cases).
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::new();
/// assert!(!sv.has_element_at(3)); // no: index out of bounds
///
/// let heart_idx = sv.push('♥');
/// assert!(sv.has_element_at(heart_idx)); // yes
///
/// sv.remove(heart_idx);
/// assert!(!sv.has_element_at(heart_idx)); // no: was removed
/// ```
pub fn has_element_at(&self, index: usize) -> bool {
if index >= self.core.cap() {
false
} else {
unsafe {
// The index is smaller than the capacity, as checked aboved,
// so we can call this without a problem.
self.core.has_element_at(index)
}
}
}
/// Returns the number of existing elements in this collection.
///
/// As long as no element is ever removed, `num_elements()` equals
/// `next_push_index()`. Once an element has been removed, `num_elements()`
/// will always be less than `next_push_index()` (assuming
/// `[reordering_]make_compact()` is not called).
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::new();
/// assert_eq!(sv.num_elements(), 0);
///
/// let heart_idx = sv.push('♥');
/// assert_eq!(sv.num_elements(), 1);
///
/// sv.remove(heart_idx);
/// assert_eq!(sv.num_elements(), 0);
/// ```
pub fn num_elements(&self) -> usize {
self.num_elements
}
/// Returns the index that would be returned by calling
/// [`push()`][StableVecFacade::push]. All filled slots have indices below
/// `next_push_index()`.
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&['a', 'b', 'c']);
///
/// let next_push_index = sv.next_push_index();
/// let index_of_d = sv.push('d');
///
/// assert_eq!(next_push_index, index_of_d);
/// ```
pub fn next_push_index(&self) -> usize {
self.core.len()
}
/// Returns the number of slots in this stable vector.
pub fn capacity(&self) -> usize {
self.core.cap()
}
/// Returns `true` if this collection doesn't contain any existing
/// elements.
///
/// This means that `is_empty()` returns true iff no elements were inserted
/// *or* all inserted elements were removed again.
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::new();
/// assert!(sv.is_empty());
///
/// let heart_idx = sv.push('♥');
/// assert!(!sv.is_empty());
///
/// sv.remove(heart_idx);
/// assert!(sv.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.num_elements == 0
}
/// Returns `true` if all existing elements are stored contiguously from
/// the beginning (in other words: there are no empty slots with indices
/// below `self.next_push_index()`).
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&[0, 1, 2, 3, 4]);
/// assert!(sv.is_compact());
///
/// sv.remove(1);
/// assert!(!sv.is_compact());
/// ```
pub fn is_compact(&self) -> bool {
self.num_elements == self.core.len()
}
/// Returns an iterator over indices and immutable references to the stable
/// vector's elements. Elements are yielded in order of their increasing
/// indices.
///
/// Note that you can also obtain this iterator via the `IntoIterator` impl
/// of `&StableVecFacade`.
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&[10, 11, 12, 13, 14]);
/// sv.remove(1);
///
/// let mut it = sv.iter().filter(|&(_, &n)| n <= 13);
/// assert_eq!(it.next(), Some((0, &10)));
/// assert_eq!(it.next(), Some((2, &12)));
/// assert_eq!(it.next(), Some((3, &13)));
/// assert_eq!(it.next(), None);
/// ```
pub fn iter(&self) -> Iter<'_, T, C> {
Iter::new(self)
}
/// Returns an iterator over indices and mutable references to the stable
/// vector's elements. Elements are yielded in order of their increasing
/// indices.
///
/// Note that you can also obtain this iterator via the `IntoIterator` impl
/// of `&mut StableVecFacade`.
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&[10, 11, 12, 13, 14]);
/// sv.remove(1);
///
/// for (idx, elem) in &mut sv {
/// if idx % 2 == 0 {
/// *elem *= 2;
/// }
/// }
///
/// assert_eq!(sv, vec![20, 24, 13, 28]);
/// ```
pub fn iter_mut(&mut self) -> IterMut<'_, T, C> {
IterMut::new(self)
}
/// Returns an iterator over immutable references to the existing elements
/// of this stable vector. Elements are yielded in order of their
/// increasing indices.
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&[0, 1, 2, 3, 4]);
/// sv.remove(1);
///
/// let mut it = sv.values().filter(|&&n| n <= 3);
/// assert_eq!(it.next(), Some(&0));
/// assert_eq!(it.next(), Some(&2));
/// assert_eq!(it.next(), Some(&3));
/// assert_eq!(it.next(), None);
/// ```
pub fn values(&self) -> Values<'_, T, C> {
Values::new(self)
}
/// Returns an iterator over mutable references to the existing elements
/// of this stable vector. Elements are yielded in order of their
/// increasing indices.
///
/// Through this iterator, the elements within the stable vector can be
/// mutated.
///
/// # Examples
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&[1.0, 2.0, 3.0]);
///
/// for e in sv.values_mut() {
/// *e *= 2.0;
/// }
///
/// assert_eq!(sv, &[2.0, 4.0, 6.0] as &[_]);
/// ```
pub fn values_mut(&mut self) -> ValuesMut<'_, T, C> {
ValuesMut::new(self)
}
/// Returns an iterator over all indices of filled slots of this stable
/// vector. Indices are yielded in increasing order.
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&['a', 'b', 'c', 'd']);
/// sv.remove(1);
///
/// let mut it = sv.indices();
/// assert_eq!(it.next(), Some(0));
/// assert_eq!(it.next(), Some(2));
/// assert_eq!(it.next(), Some(3));
/// assert_eq!(it.next(), None);
/// ```
///
/// Simply using the `for`-loop:
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&['a', 'b', 'c', 'd']);
///
/// for index in sv.indices() {
/// println!("index: {}", index);
/// }
/// ```
pub fn indices(&self) -> Indices<'_, T, C> {
Indices::new(self)
}
/// Reserves memory for at least `additional` more elements to be inserted
/// at indices `>= self.next_push_index()`.
///
/// This method might allocate more than `additional` to avoid frequent
/// reallocations. Does nothing if the current capacity is already
/// sufficient. After calling this method, `self.capacity()` is ≥
/// `self.next_push_index() + additional`.
///
/// Unlike `Vec::reserve`, the additional reserved memory is not completely
/// unaccessible. Instead, additional empty slots are added to this stable
/// vector. These can be used just like any other empty slot; in
/// particular, you can insert into it.
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::new();
/// let star_idx = sv.push('★');
///
/// // After we inserted one element, the next element would sit at index
/// // 1, as expected.
/// assert_eq!(sv.next_push_index(), 1);
///
/// sv.reserve(2); // insert two empty slots
///
/// // `reserve` doesn't change any of this
/// assert_eq!(sv.num_elements(), 1);
/// assert_eq!(sv.next_push_index(), 1);
///
/// // We can now insert an element at index 2.
/// sv.insert(2, 'x');
/// assert_eq!(sv[2], 'x');
///
/// // These values get adjusted accordingly.
/// assert_eq!(sv.num_elements(), 2);
/// assert_eq!(sv.next_push_index(), 3);
/// ```
pub fn reserve(&mut self, additional: usize) {
#[inline(never)]
#[cold]
fn capacity_overflow() -> ! {
panic!("capacity overflow in `stable_vec::StableVecFacade::reserve` (attempt \
to allocate more than `isize::MAX` elements");
}
//: new_cap = len + additional ∧ additional >= 0
//: => new_cap >= len
let new_cap = match self.core.len().checked_add(additional) {
None => capacity_overflow(),
Some(new_cap) => new_cap,
};
if self.core.cap() < new_cap {
// We at least double our capacity. Otherwise repeated `push`es are
// O(n²).
//
// This multiplication can't overflow, because we know the capacity
// is `<= isize::MAX`.
//
//: new_cap = max(new_cap_before, 2 * cap)
//: ∧ cap >= len
//: ∧ new_cap_before >= len
//: => new_cap >= len
let new_cap = cmp::max(new_cap, 2 * self.core.cap());
if new_cap > isize::max_value() as usize {
capacity_overflow();
}
//: new_cap >= len ∧ new_cap <= isize::MAX
//
// These both properties are exactly the preconditions of
// `realloc`, so we can safely call that method.
unsafe {
self.core.realloc(new_cap);
}
}
}
/// Reserve enough memory so that there is a slot at `index`. Does nothing
/// if `index < self.capacity()`.
///
/// This method might allocate more memory than requested to avoid frequent
/// allocations. After calling this method, `self.capacity() >= index + 1`.
///
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::new();
/// let star_idx = sv.push('★');
///
/// // Allocate enough memory so that we have a slot at index 5.
/// sv.reserve_for(5);
/// assert!(sv.capacity() >= 6);
///
/// // We can now insert an element at index 5.
/// sv.insert(5, 'x');
/// assert_eq!(sv[5], 'x');
///
/// // This won't do anything as the slot with index 3 already exists.
/// let capacity_before = sv.capacity();
/// sv.reserve_for(3);
/// assert_eq!(sv.capacity(), capacity_before);
/// ```
pub fn reserve_for(&mut self, index: usize) {
if index >= self.capacity() {
// Won't underflow as `index >= capacity >= next_push_index`.
self.reserve(1 + index - self.next_push_index());
}
}
/// Like [`reserve`][StableVecFacade::reserve], but tries to allocate
/// memory for exactly `additional` more elements.
///
/// The underlying allocator might allocate more memory than requested,
/// meaning that you cannot rely on the capacity of this stable vector
/// having an exact value after calling this method.
pub fn reserve_exact(&mut self, additional: usize) {
#[inline(never)]
#[cold]
fn capacity_overflow() -> ! {
panic!("capacity overflow in `stable_vec::StableVecFacade::reserve_exact` (attempt \
to allocate more than `isize::MAX` elements");
}
//: new_cap = len + additional ∧ additional >= 0
//: => new_cap >= len
let new_cap = match self.core.len().checked_add(additional) {
None => capacity_overflow(),
Some(new_cap) => new_cap,
};
if self.core.cap() < new_cap {
if new_cap > isize::max_value() as usize {
capacity_overflow();
}
//: new_cap >= len ∧ new_cap <= isize::MAX
//
// These both properties are exactly the preconditions of
// `realloc`, so we can safely call that method.
unsafe {
self.core.realloc(new_cap);
}
}
}
/// Removes and returns the first element from this collection, or `None`
/// if it's empty.
///
/// This method uses exactly the same deletion strategy as
/// [`remove()`][StableVecFacade::remove].
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&[1, 2, 3]);
/// assert_eq!(sv.remove_first(), Some(1));
/// assert_eq!(sv, vec![2, 3]);
/// ```
///
/// # Note
///
/// This method needs to find the index of the first valid element. Finding
/// it has a worst case time complexity of O(n). If you already know the
/// index, use [`remove()`][StableVecFacade::remove] instead.
pub fn remove_first(&mut self) -> Option<T> {
self.find_first_index().and_then(|index| self.remove(index))
}
/// Removes and returns the last element from this collection, or `None` if
/// it's empty.
///
/// This method uses exactly the same deletion strategy as
/// [`remove()`][StableVecFacade::remove].
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&[1, 2, 3]);
/// assert_eq!(sv.remove_last(), Some(3));
/// assert_eq!(sv, vec![1, 2]);
/// ```
///
/// # Note
///
/// This method needs to find the index of the last valid element. Finding
/// it has a worst case time complexity of O(n). If you already know the
/// index, use [`remove()`][StableVecFacade::remove] instead.
pub fn remove_last(&mut self) -> Option<T> {
self.find_last_index().and_then(|index| self.remove(index))
}
/// Finds the first element and returns a reference to it, or `None` if
/// the stable vector is empty.
///
/// This method has a worst case time complexity of O(n).
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&[1, 2]);
/// sv.remove(0);
/// assert_eq!(sv.find_first(), Some(&2));
/// ```
pub fn find_first(&self) -> Option<&T> {
self.find_first_index().map(|index| unsafe { self.core.get_unchecked(index) })
}
/// Finds the first element and returns a mutable reference to it, or
/// `None` if the stable vector is empty.
///
/// This method has a worst case time complexity of O(n).
///
/// # Example
///
/// ```
/// # use stable_vec::StableVec;
/// let mut sv = StableVec::from(&[1, 2]);
/// {