vec-option 0.3.0

A space optimized version of `Vec<Option<T>>` that stores the discriminant seperately
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
#![cfg_attr(feature = "nightly", feature(specialization, try_trait))]
#![allow(clippy::option_option)]
#![forbid(missing_docs)]

/*!
# vec-option

A space optimized version of `Vec<Option<T>>` that stores the discriminant seperately.

## Feature flags

`nightly` - This turns on a few optimizations (makes `Clone`ing `Copy` elements much cheaper) and extends `try_fold` and `try_for_each` to work with all `Try` types. Finally, this also allows the `iterator.nth_back(n)` methods to be used.

## Pros

* Can have a smaller memory footprint compared to `Vec<Option<T>>` if `Option<T>`'s space optimizations don't take effect
* More cache-friendly if `Option<T>`'s space optimizations don't take effect
* Quickly set the entire collection to contain `None`
* Fast extend with `None`

## Cons

* 2 allocations, instead of a single allocation
* Cannot remove elements from the middle of the vector
* Cannot work on the option's directly

## Example

Just like a normal vector, you can push and pop elements from the end of the vector

```rust
# use vec_option::VecOption;
let mut vec = VecOption::new();

vec.push(10);

assert_eq!(vec, [Some(10)]);

vec.push(20);
vec.push(None);
vec.push(Some(30));

assert_eq!(vec, [Some(10), Some(20), None, Some(30)]);

assert_eq!(vec.pop(), Some(Some(30)));
assert_eq!(vec.pop(), Some(None));
assert_eq!(vec.pop(), Some(Some(20)));
assert_eq!(vec.pop(), Some(Some(10)));
assert_eq!(vec.pop(), None);
assert_eq!(vec, []);
```

You can get elements from the vector

```rust
# use vec_option::VecOption;
let mut vec = VecOption::from(vec![0, 1, 2, 3, 4]);
assert_eq!(vec.len(), 5);
assert_eq!(vec, [Some(0), Some(1), Some(2), Some(3), Some(4)]);
// assert_eq!(vec.get(2), Some(Some(&2)));
// assert_eq!(vec.get_mut(4), Some(Some(&mut 4)));
assert_eq!(vec.get(5), None);
```

You can swap and replace elements

```rust ignore
vec.swap(2, 1);

assert_eq!(vec, [Some(0), Some(2), Some(1), Some(3), Some(4)]);

assert_eq!(vec.replace(3, None), Some(Some(3)));
assert_eq!(vec.replace(1, Some(10)), Some(Some(1)));

assert_eq!(vec, [Some(0), Some(10), Some(1), None, Some(4)]);
```

or if `vec.replace(index, None)` is too much, you can do

```rust ignore
assert_eq!(vec.take(1), Some(Some(10)));

assert_eq!(vec, [Some(0), None, Some(1), None, Some(4)]);
```

Of course, you can also truncate or clear the vector

```rust
# use vec_option::VecOption;
let mut vec = VecOption::from(vec![0, 1, 3, 4]);

assert_eq!(vec.len(), 4);

vec.truncate(2);

assert_eq!(vec, [Some(0), Some(1)]);

vec.clear();

assert!(vec.is_empty());
```

But due to the limitations imposed by spliting the representation of the vector, you can't really get a
`&Option<T>`/`&mut Option<T>` outside of a closure.
In fact, you can't get an `&Option<T>` at all, it would be fairly useless, as the only thing you can really do with it is convert it to a `Option<&T>`. But `&mut Option<T>` is usefull, so there are a handful of functions that allow you to operate with them.

These functions below are like the corrosponding functions in `Iterator`, they iterate over the vector and allow you to do stuff based on which one you call. The only difference is that you get to operate on `&mut Option<T>` directly. Again, if the closure panics, it will be as if you took the value out of the vector.

```rust ignore
vec.try_fold(...);

vec.fold(...);

vec.try_for_each(...);

vec.for_each(...);
```

But because of these limitations, you can very quickly fill up your vector with `None` and set all of the elements in your vector to `None`! This can compile down to just a `memset` if your types don't have drop glue!

```rust
# use vec_option::VecOption;
let mut vec = VecOption::from(vec![0, 1, 2, 3, 4]);

assert_eq!(vec, [Some(0), Some(1), Some(2), Some(3), Some(4)]);

vec.extend_none(5);

assert_eq!(vec, [Some(0), Some(1), Some(2), Some(3), Some(4), None, None, None, None, None]);

vec.set_all_none();

assert_eq!(vec, [None, None, None, None, None, None, None, None, None, None]);
```
*/

mod bit_vec;
// use bit_vec as bit_vec;

use bit_vec::BitVec;

use std::mem::MaybeUninit;
use std::ops::{Bound, Deref, DerefMut, RangeBounds};

/// # Safety
///
/// This code must never be run
#[cold]
unsafe fn unreachable_unchecked() -> ! {
    use std::hint::unreachable_unchecked;

    debug_assert!(false, "unreachable");
    unreachable_unchecked()
}

fn as_range<R: RangeBounds<usize>>(range: &R, len: usize) -> (usize, usize) {
    let start = match range.start_bound() {
        Bound::Unbounded => 0,
        Bound::Included(&x) => x,
        Bound::Excluded(&x) => x + 1,
    };

    let end = match range.end_bound() {
        Bound::Unbounded => len,
        Bound::Included(&x) => x + 1,
        Bound::Excluded(&x) => x,
    };

    (start, end)
}

trait UnwrapUnchecked {
    type Output;

    /// # Safety
    ///
    /// The Option<T> must be in the `Some` variant
    unsafe fn unwrap_unchecked(self) -> Self::Output;
}

impl<T> UnwrapUnchecked for Option<T> {
    type Output = T;

    unsafe fn unwrap_unchecked(self) -> Self::Output {
        match self {
            Some(value) => value,
            None => unreachable_unchecked(),
        }
    }
}

/// # Safety
///
/// The flag must corrospond to the data
///
/// i.e. if flag is true, then data must be initialized
unsafe fn from_raw_parts<T>(flag: bool, data: MaybeUninit<T>) -> Option<T> {
    if flag {
        Some(data.assume_init())
    } else {
        None
    }
}

/// # Safety
///
/// The flag must corrospond to the data
///
/// i.e. if flag is true, then data must be initialized
unsafe fn ref_from_raw_parts<T>(flag: bool, data: &MaybeUninit<T>) -> Option<&T> {
    if flag {
        Some(&*data.as_ptr())
    } else {
        None
    }
}

/// A space optimized version of `Vec<Option<T>>` that stores the discriminant seperately
///
/// See crate-level docs for more information
///
pub struct VecOption<T> {
    data: Vec<MaybeUninit<T>>,
    flag: BitVec,
}

/// The capacity information of the given `VecOption<T>`
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CapacityInfo {
    /// The capacity of the data vector that holds `T`s
    pub data: usize,

    /// The capacity of the `BitVec` that holds the discriminants
    pub flag: usize,

    _priv: (),
}

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

/// A proxy to a mutable reference to an option in a `VecOption<T>`
///
/// If this `OptionProxy` is leaked, then the option in the `VecOption<T>` will be set to `None`
/// and the old value of that element will be leaked
///
/// This serves as a way to access the option directly, and will update the `VecOption<T>` on drop
pub struct OptionProxy<'a, T> {
    data: &'a mut MaybeUninit<T>,
    flag: bit_vec::BitProxy<'a>,
    value: Option<T>,
}

impl<'a, T> OptionProxy<'a, T> {
    unsafe fn new(mut flag: bit_vec::BitProxy<'a>, data: &'a mut MaybeUninit<T>) -> Self {
        let data_v = std::mem::replace(data, MaybeUninit::uninit());
        let flag_v = std::mem::replace(&mut *flag, false);

        flag.flush();

        let value = from_raw_parts(flag_v, data_v);

        Self { data, flag, value }
    }
}

impl<T> Deref for OptionProxy<'_, T> {
    type Target = Option<T>;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T> DerefMut for OptionProxy<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}

impl<T> Drop for OptionProxy<'_, T> {
    fn drop(&mut self) {
        if let Some(value) = self.value.take() {
            // data_slot is valid and contains uninitialized memory
            // so do not drop it, but it is valid to write to
            unsafe {
                self.data.as_mut_ptr().write(value);
                *self.flag = true;
            }
        }
    }
}

impl<T> VecOption<T> {
    /// Creates an empty vector, does not allocate
    pub fn new() -> Self {
        Self {
            data: Vec::new(),
            flag: BitVec::new(),
        }
    }

    /// Creates an empty vector
    ///
    /// allocates at least `cap` elements of space
    pub fn with_capacity(cap: usize) -> Self {
        Self {
            data: Vec::with_capacity(cap),
            flag: BitVec::with_capacity(cap),
        }
    }

    /// reserves at least `amount` elements
    ///
    /// if there is already enough space, this does nothing
    pub fn reserve(&mut self, amount: usize) {
        self.data.reserve(amount);
        self.flag.reserve(amount);
    }

    /// reserves exactly `amount` elements
    ///
    /// if there is already enough space, this does nothing
    pub fn reserve_exact(&mut self, amount: usize) {
        self.data.reserve_exact(amount);
        self.flag.reserve_exact(amount);
    }

    /// The length of this vector
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// The capacity of the vector
    pub fn capacity(&self) -> CapacityInfo {
        CapacityInfo {
            data: self.data.capacity(),
            flag: self.flag.alloc_info().cap,
            _priv: (),
        }
    }

    /// Is this vector empty
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Put a value at the end of the vector
    ///
    /// Reallocates if there is not enough space
    pub fn push<V: Into<Option<T>>>(&mut self, value: V) {
        let value = value.into();

        match value {
            Some(value) => {
                self.data.push(MaybeUninit::new(value));
                self.flag.push(true);
            }
            None => {
                self.data.push(MaybeUninit::uninit());
                self.flag.push(false);
            }
        }
    }

    /// Remove the last element of the vector
    ///
    /// returns `None` if the vector is empty
    pub fn pop(&mut self) -> Option<Option<T>> {
        unsafe {
            let flag = self.flag.pop()?;

            // This is safe because flag pop does the necessary checks to make sure that
            // there are more elements
            // This relies on the fact that `flag.len() == data.len()`
            let data = self.data.pop().unwrap_unchecked();

            // The flag and data are a pair, (same index)
            Some(from_raw_parts(flag, data))
        }
    }

    /// Returns a proxy to a mutable reference to the element at `index` or None if out of bounds.
    pub fn get_mut(&mut self, index: usize) -> Option<OptionProxy<'_, T>> {
        unsafe {
            let flag = self.flag.get_mut(index)?;

            // This is safe because flag pop does the necessary checks to make sure that
            // there are more elements
            // This relies on the fact that `flag.len() == data.len()`
            let data = self.data.get_unchecked_mut(index);

            // The flag and data are a pair, (same index)
            Some(OptionProxy::new(flag, data))
        }
    }

    /// Returns a reference to the element at `index` or None if out of bounds.
    pub fn get(&self, index: usize) -> Option<Option<&T>> {
        unsafe {
            let flag = self.flag.get(index)?;

            // This is safe because flag pop does the necessary checks to make sure that
            // there are more elements
            // This relies on the fact that `flag.len() == data.len()`
            let data = self.data.get_unchecked(index);

            // The flag and data are a pair, (same index)
            Some(ref_from_raw_parts(flag, data))
        }
    }

    /// Swaps two elements of the vector, panics if either index is out of bounds
    pub fn swap(&mut self, a: usize, b: usize) {
        self.data.swap(a, b);
        unsafe {
            // Swap did the necessary length checks to make sure that
            // `a` and `b` are in bounds
            let fa = self.flag.get_unchecked(a);
            let fb = self.flag.get_unchecked(b);

            self.flag.set(a, fb);
            self.flag.set(b, fa);
        }
    }

    /// Returns the element at `index` or None if out of bounds.
    ///
    /// Replaces the element at `index` with None.
    pub fn take(&mut self, index: usize) -> Option<Option<T>> {
        self.replace(index, None)
    }

    /// Replace the element at `index` with `value`
    pub fn replace<O: Into<Option<T>>>(&mut self, index: usize, value: O) -> Option<Option<T>> {
        unsafe {
            let value = value.into();

            let flag = self.flag.get(index)?;

            // index was checked by flag.get
            let data = self.data.get_unchecked_mut(index);

            let out = if flag {
                // flag corrosponds to data
                Some(data.as_ptr().read())
            } else {
                None
            };

            match value {
                Some(value) => {
                    self.flag.set(index, true);

                    // data is valid, use write to prevent
                    // dropping uninitialized memory
                    data.as_mut_ptr().write(value);
                }
                None => self.flag.set(index, false),
            }

            Some(out)
        }
    }

    /// Reduces the length of the vector to `len` and drops all excess elements
    ///
    /// If `len` is greater than the length of the vector, nothing happens
    pub fn truncate(&mut self, len: usize) {
        if self.data.len() <= len {
            return;
        }

        if std::mem::needs_drop::<T>() {
            for (i, data) in self.data.iter_mut().enumerate().skip(len) {
                unsafe {
                    // index corrosponds to the index of a data, so it is valid
                    if self.flag.get_unchecked(i) {
                        self.flag.set(i, false);

                        // data is initialized, checked by flag
                        data.as_mut_ptr().drop_in_place()
                    }
                }
            }
        }

        // decreasing the length is always fine
        unsafe {
            self.data.set_len(len);
            self.flag.set_len(len);
        }
    }

    /// Clears the vector
    pub fn clear(&mut self) {
        self.truncate(0)
    }

    /// Sets all of the elements in the vector to `None` and drops
    /// all values in the closure
    pub fn set_all_none(&mut self) {
        if std::mem::needs_drop::<T>() {
            for (i, data) in self.data.iter_mut().enumerate() {
                unsafe {
                    if self.flag.get_unchecked(i) {
                        self.flag.set(i, false);
                        data.as_mut_ptr().drop_in_place()
                    }
                }
            }
        } else {
            self.flag.set_all(false);
        }
    }

    /// Extends the vector with `additional` number of `None`s
    pub fn extend_none(&mut self, additional: usize) {
        self.flag.grow(additional, false);

        unsafe {
            self.reserve(additional);

            let len = self.len();

            // Because this is a Vec<MaybeUninit<T>>, we only need to
            // guarantee that we have enough space in the allocatation
            // for `set_len` to be safe, and that was done with the reserve
            self.data.set_len(len + additional);
        }
    }

    /// returns an iterator over references to the elements in the vector
    pub fn iter(&self) -> Iter<'_, T> {
        Iter {
            data: self.data.iter(),
            flag: self.flag.iter(),
        }
    }

    /// returns an iterator over mutable references to the elements in the vector
    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
        IterMut {
            data: self.data.iter_mut(),
            flag: self.flag.iter_mut(),
        }
    }

    /// Iterates over all of the `Option<T>`s in the vector and applies the closure to each one of them until
    /// the closure short-circuits, then iteration ends
    ///
    /// The closure is passed the `init`, `index`, and a mutable reference to the corrosponding element of the vector
    #[cfg(feature = "nightly")]
    pub fn try_fold<Range: RangeBounds<usize>, A, R: std::ops::Try<Ok = A>, F: FnMut(A, usize, &mut Option<T>) -> R>(
        &mut self,
        range: Range,
        mut init: A,
        mut f: F,
    ) -> R
    where
        Range: std::slice::SliceIndex<[MaybeUninit<T>], Output = [MaybeUninit<T>]>,
    {
        let (start, end) = as_range(&range, self.len());

        let data = self.data[range].iter_mut().enumerate();
        let flag = self.flag.iter_mut().take(end).skip(start);

        for ((i, data_slot), mut flag_slot) in data.zip(flag) {
            let flag_slot: &mut bool = &mut flag_slot;

            let data = std::mem::replace(data_slot, MaybeUninit::uninit());
            let flag = std::mem::replace(flag_slot, false);

            // The flag and data are a pair, (same index)
            let mut opt = unsafe { from_raw_parts(flag, data) };

            let res = f(init, i, &mut opt);

            if let Some(value) = opt {
                *data_slot = MaybeUninit::new(value);
                *flag_slot = true;
            }

            init = res?;
        }

        R::from_ok(init)
    }

    /// Iterates over all of the `Option<T>`s in the vector and applies the closure to each one of them until
    /// the closure returns `Err(..)`, then iteration ends
    ///
    /// The closure is passed the `init`, `index`, and a mutable reference to the corrosponding element of the vector
    ///
    /// This is similar to `Iterator::try_fold`
    #[cfg(not(feature = "nightly"))]
    pub fn try_fold<
        Range: RangeBounds<usize>,
        A,
        B,
        F: FnMut(A, usize, &mut Option<T>) -> Result<A, B>,
    >(
        &mut self,
        range: Range,
        mut init: A,
        mut f: F,
    ) -> Result<A, B>
    where
        Range: std::slice::SliceIndex<[MaybeUninit<T>], Output = [MaybeUninit<T>]>,
    {
        let (start, end) = as_range(&range, self.len());

        let data = self.data[range].iter_mut().enumerate();
        let flag = self.flag.iter_mut().take(end).skip(start);

        for ((i, data_slot), mut flag_slot) in data.zip(flag) {
            let i = i + start;
            let flag_slot: &mut bool = &mut flag_slot;

            let data = std::mem::replace(data_slot, MaybeUninit::uninit());
            let flag = std::mem::replace(flag_slot, false);

            // The flag and data are a pair, (same index)
            let mut opt = unsafe { from_raw_parts(flag, data) };

            let res = f(init, i, &mut opt);

            if let Some(value) = opt {
                *data_slot = MaybeUninit::new(value);
                *flag_slot = true;
            }

            init = res?;
        }

        Ok(init)
    }

    /// Iterates over all of the `Option<T>`s in the vector and applies the closure to each one
    ///
    /// The closure is passed the `init`, `index`, and a mutable reference to the corrosponding element of the vector
    ///
    /// This is similar to `Iterator::fold`
    pub fn fold<Range: RangeBounds<usize>, A, F: FnMut(A, usize, &mut Option<T>) -> A>(
        &mut self,
        range: Range,
        init: A,
        mut f: F,
    ) -> A
    where
        Range: std::slice::SliceIndex<[MaybeUninit<T>], Output = [MaybeUninit<T>]>,
    {
        let ret = self.try_fold(range, init, move |a, i, x| {
            Ok::<_, std::convert::Infallible>(f(a, i, x))
        });

        match ret {
            Ok(x) => x,
            Err(x) => match x {},
        }
    }

    /// Iterates over all of the `Option<T>`s in the vector and applies the closure to each one of them until
    /// the closure short-circuits, then iteration ends
    ///
    /// The closure is passed the `index`, and a mutable reference to the corrosponding element of the vector
    ///
    /// This is similar to `Iterator::try_for_each`
    #[cfg(feature = "nightly")]
    pub fn try_for_each<
        Range: RangeBounds<usize>,
        R: std::ops::Try<Ok = ()>,
        F: FnMut(usize, &mut Option<T>) -> R,
    >(
        &mut self,
        range: Range,
        mut f: F,
    ) -> R
    where
        Range: std::slice::SliceIndex<[MaybeUninit<T>], Output = [MaybeUninit<T>]>,
    {
        self.try_fold(range, (), move |(), i, x| f(i, x))
    }

    /// Iterates over all of the `Option<T>`s in the vector and applies the closure to each one of them until
    /// the closure returns `Err(..)`, then iteration ends
    ///
    /// The closure is passed the `index`, and a mutable reference to the corrosponding element of the vector
    ///
    /// This is similar to `Iterator::try_for_each`
    #[cfg(not(feature = "nightly"))]
    pub fn try_for_each<
        Range: RangeBounds<usize>,
        B,
        F: FnMut(usize, &mut Option<T>) -> Result<(), B>,
    >(
        &mut self,
        range: Range,
        mut f: F,
    ) -> Result<(), B>
    where
        Range: std::slice::SliceIndex<[MaybeUninit<T>], Output = [MaybeUninit<T>]>,
    {
        self.try_fold(range, (), move |(), i, x| f(i, x))
    }

    /// Iterates over all of the `Option<T>`s in the vector and applies the closure to each one
    ///
    /// The closure is passed the `index`, and a mutable reference to the corrosponding element of the vector
    ///
    /// This is similar to `Iterator::for_each`
    pub fn for_each<Range: RangeBounds<usize>, F: FnMut(usize, &mut Option<T>)>(
        &mut self,
        range: Range,
        mut f: F,
    ) where
        Range: std::slice::SliceIndex<[MaybeUninit<T>], Output = [MaybeUninit<T>]>,
    {
        self.fold(range, (), move |(), i, x| f(i, x))
    }
}

impl<T> Drop for VecOption<T> {
    fn drop(&mut self) {
        if std::mem::needs_drop::<T>() {
            self.clear()
        }
    }
}

fn clone_impl<T: Clone>(vec: &VecOption<T>) -> VecOption<T> {
    vec.iter().map(|x| x.cloned()).collect()
}

impl<T: Clone> Clone for VecOption<T> {
    #[cfg(feature = "nightly")]
    default fn clone(&self) -> Self {
        clone_impl(self)
    }

    #[cfg(not(feature = "nightly"))]
    fn clone(&self) -> Self {
        clone_impl(self)
    }
}

#[cfg(feature = "nightly")]
impl<T: Copy> Clone for VecOption<T> {
    fn clone(&self) -> Self {
        let len = self.len();
        let mut new = Self {
            data: Vec::with_capacity(len),
            flag: self.flag.clone(),
        };

        unsafe {
            new.data.set_len(len);
            new.data.copy_from_slice(&self.data);
        }

        new
    }
}

impl<T: PartialEq> PartialEq for VecOption<T> {
    fn eq(&self, other: &Self) -> bool {
        self.iter().eq(other.iter())
    }
}

impl<T: PartialEq> PartialEq<[T]> for VecOption<T> {
    fn eq(&self, other: &[T]) -> bool {
        self.iter().eq(other.iter().map(Some))
    }
}

impl<T: PartialEq, S: AsRef<[Option<T>]>> PartialEq<S> for VecOption<T> {
    fn eq(&self, other: &S) -> bool {
        self.iter().eq(other.as_ref().iter().map(Option::as_ref))
    }
}

impl<T: Eq> Eq for VecOption<T> {}

impl<T: PartialOrd> PartialOrd for VecOption<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.iter().partial_cmp(other.iter())
    }
}

impl<T: Ord> Ord for VecOption<T> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.iter().cmp(other.iter())
    }
}

use std::hash::{Hash, Hasher};

impl<T: Hash> Hash for VecOption<T> {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.iter().for_each(|i| i.hash(hasher))
    }
}

impl<T> std::iter::Extend<Option<T>> for VecOption<T> {
    fn extend<I: IntoIterator<Item = Option<T>>>(&mut self, iter: I) {
        let iter = iter.into_iter();

        let (additional, _) = iter.size_hint();

        self.reserve(additional);

        iter.for_each(|x| self.push(x));
    }
}

impl<T> std::iter::Extend<T> for VecOption<T> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        let iter = iter.into_iter();

        let (additional, _) = iter.size_hint();

        self.reserve(additional);

        iter.for_each(|x| self.push(x));
    }
}

impl<T> std::iter::FromIterator<Option<T>> for VecOption<T> {
    fn from_iter<I: IntoIterator<Item = Option<T>>>(iter: I) -> Self {
        let mut vec = Self::new();
        vec.extend(iter);
        vec
    }
}

impl<T> From<Vec<T>> for VecOption<T> {
    fn from(mut vec: Vec<T>) -> Self {
        let len = vec.len();

        let data = unsafe {
            Vec::from_raw_parts(vec.as_mut_ptr() as *mut MaybeUninit<T>, len, vec.capacity())
        };

        std::mem::forget(vec);

        let mut flag = BitVec::with_capacity(len);
        flag.grow(len, true);

        Self { data, flag }
    }
}

impl<T> From<Vec<Option<T>>> for VecOption<T> {
    fn from(vec: Vec<Option<T>>) -> Self {
        let mut vec_opt = VecOption::new();

        vec_opt.extend(vec);

        vec_opt
    }
}

impl<T> Drop for IntoIter<T> {
    fn drop(&mut self) {
        self.for_each(drop);
    }
}

/// This struct is created by the `into_iter` method on `VecOption` (provided by the `IntoIterator` trait).
pub struct IntoIter<T> {
    data: std::vec::IntoIter<MaybeUninit<T>>,
    flag: bit_vec::IntoIter,
}

impl<T> Iterator for IntoIter<T> {
    type Item = Option<T>;

    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            let flag = self.flag.next()?;
            let data = self.data.next().unwrap_unchecked();

            Some(from_raw_parts(flag, data))
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.data.size_hint()
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        if std::mem::needs_drop::<T>() {
            for _ in 1..n {
                self.next()?;
            }
            self.next()
        } else {
            unsafe {
                let flag = self.flag.nth(n)?;
                let data = self.data.nth(n).unwrap_unchecked();

                Some(from_raw_parts(flag, data))
            }
        }
    }
}

impl<T> DoubleEndedIterator for IntoIter<T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        unsafe {
            let flag = self.flag.next_back()?;
            let data = self.data.next_back().unwrap_unchecked();

            Some(from_raw_parts(flag, data))
        }
    }

    #[cfg(feature = "nightly")]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        if std::mem::needs_drop::<T>() {
            for _ in 1..n {
                self.next_back()?;
            }
            self.next_back()
        } else {
            unsafe {
                let flag = self.flag.nth_back(n)?;
                let data = self.data.nth_back(n).unwrap_unchecked();

                Some(from_raw_parts(flag, data))
            }
        }
    }
}

impl<T> ExactSizeIterator for IntoIter<T> {}
impl<T> std::iter::FusedIterator for IntoIter<T> {}

/// This struct is created by the `iter_mut` method on `VecOption`
pub struct IterMut<'a, T> {
    data: std::slice::IterMut<'a, MaybeUninit<T>>,
    flag: bit_vec::IterMut<'a>,
}

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

    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            let flag = self.flag.next()?;
            let data = self.data.next().unwrap_unchecked();

            Some(OptionProxy::new(flag, data))
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.data.size_hint()
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        unsafe {
            let data = self.data.nth(n)?;
            let flag = self.flag.nth(n).unwrap_unchecked();

            Some(OptionProxy::new(flag, data))
        }
    }
}

impl<T> DoubleEndedIterator for IterMut<'_, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        unsafe {
            let flag = self.flag.next_back()?;
            let data = self.data.next_back().unwrap_unchecked();

            Some(OptionProxy::new(flag, data))
        }
    }

    #[cfg(feature = "nightly")]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        unsafe {
            let data = self.data.nth_back(n)?;
            let flag = self.flag.nth_back(n).unwrap_unchecked();

            Some(OptionProxy::new(flag, data))
        }
    }
}

/// This struct is created by the `iter` method on `VecOption`
pub struct Iter<'a, T> {
    data: std::slice::Iter<'a, MaybeUninit<T>>,
    flag: bit_vec::Iter<'a>,
}

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

    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            let flag = self.flag.next()?;
            let data = self.data.next().unwrap_unchecked();

            Some(ref_from_raw_parts(flag, data))
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.data.size_hint()
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        unsafe {
            let data = self.data.nth(n)?;
            let flag = self.flag.nth(n).unwrap_unchecked();

            Some(ref_from_raw_parts(flag, data))
        }
    }
}

impl<T> DoubleEndedIterator for Iter<'_, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        unsafe {
            let flag = self.flag.next_back()?;
            let data = self.data.next_back().unwrap_unchecked();

            Some(ref_from_raw_parts(flag, data))
        }
    }

    #[cfg(feature = "nightly")]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        unsafe {
            let data = self.data.nth_back(n)?;
            let flag = self.flag.nth_back(n).unwrap_unchecked();

            Some(ref_from_raw_parts(flag, data))
        }
    }
}

impl<T> ExactSizeIterator for Iter<'_, T> {}
impl<T> std::iter::FusedIterator for Iter<'_, T> {}

impl<T> IntoIterator for VecOption<T> {
    type Item = Option<T>;
    type IntoIter = IntoIter<T>;

    fn into_iter(mut self) -> Self::IntoIter {
        IntoIter {
            data: std::mem::replace(&mut self.data, Vec::new()).into_iter(),
            flag: std::mem::replace(&mut self.flag, BitVec::new()).into_iter(),
        }
    }
}

impl<'a, T> IntoIterator for &'a mut VecOption<T> {
    type Item = OptionProxy<'a, T>;
    type IntoIter = IterMut<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<'a, T> IntoIterator for &'a VecOption<T> {
    type Item = Option<&'a T>;
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

use std::fmt;

impl<T: fmt::Debug> fmt::Debug for VecOption<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut f = f.debug_list();

        for i in self {
            f.entry(&i);
        }

        f.finish()
    }
}

#[test]
fn test() {
    let mut vec = VecOption::new();

    vec.push(10);
    vec.push(Some(20));

    vec.extend_none(10);

    vec.push(30);
    vec.push(40);
    vec.push(50);
    vec.push(60);

    assert_eq!(
        vec,
        [
            Some(10),
            Some(20),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            Some(30),
            Some(40),
            Some(50),
            Some(60)
        ]
    );

    vec.set_all_none();

    assert!(vec.iter().eq(std::iter::repeat(None).take(16)));

    vec.clear();

    assert!(vec.is_empty());

    vec.extend(vec![10, 30, 20]);

    assert_eq!(vec, [Some(10), Some(30), Some(20)]);
    assert_eq!(vec, [10, 30, 20][..]);

    assert_eq!(vec, vec.clone());

    assert_eq!(vec.take(1), Some(Some(30)));
    assert_eq!(vec.replace(1, 40), Some(None));
    assert_eq!(vec.take(1), Some(Some(40)));
    vec.swap(0, 1);
    assert_eq!(vec, [None, Some(10), Some(20)]);

    vec.clear();

    vec.extend(0..10);

    vec.for_each(.., |_, opt| {
        if let Some(ref mut x) = *opt {
            if *x % 2 == 0 {
                *opt = None
            } else {
                *x *= 2
            }
        }
    });

    assert_eq!(
        vec,
        [
            None,
            Some(2),
            None,
            Some(6),
            None,
            Some(10),
            None,
            Some(14),
            None,
            Some(18)
        ]
    );

    let mut counter = 0;
    vec.for_each(.., |_, opt| {
        if let Some(ref mut x) = *opt {
            if *x % 3 == 0 {
                *x /= 2
            } else {
                *opt = None
            }
        } else {
            counter += 1;
            *opt = Some(counter);
        }
    });

    assert_eq!(
        vec,
        [
            Some(1),
            None,
            Some(2),
            Some(3),
            Some(3),
            None,
            Some(4),
            None,
            Some(5),
            Some(9)
        ]
    );
    
    let val = vec.try_fold(2..6, 0, |acc, _, opt| {
        let res = opt.map(|x| {
            acc + x
        }).ok_or(acc);

        *opt = None;

        res
    });

    assert_eq!(val, Err(8));

    assert_eq!(
        vec,
        [
            Some(1),
            None,
            None,
            None,
            None,
            None,
            Some(4),
            None,
            Some(5),
            Some(9)
        ]
    );
}