vec_option/
lib.rs

1#![cfg_attr(feature = "nightly", feature(specialization, try_trait))]
2#![allow(clippy::option_option)]
3#![forbid(missing_docs)]
4
5/*!
6# vec-option
7
8A space optimized version of `Vec<Option<T>>` that stores the discriminant seperately.
9
10## Feature flags
11
12`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.
13
14## Pros
15
16* Can have a smaller memory footprint compared to `Vec<Option<T>>` if `Option<T>`'s space optimizations don't take effect
17* More cache-friendly if `Option<T>`'s space optimizations don't take effect
18* Quickly set the entire collection to contain `None`
19* Fast extend with `None`
20
21## Cons
22
23* 2 allocations, instead of a single allocation
24* Cannot remove elements from the middle of the vector
25* Cannot work on the option's directly
26
27## Example
28
29Just like a normal vector, you can push and pop elements from the end of the vector
30
31```rust
32# use vec_option::VecOption;
33let mut vec = VecOption::new();
34
35vec.push(10);
36
37assert_eq!(vec, [Some(10)]);
38
39vec.push(20);
40vec.push(None);
41vec.push(Some(30));
42
43assert_eq!(vec, [Some(10), Some(20), None, Some(30)]);
44
45assert_eq!(vec.pop(), Some(Some(30)));
46assert_eq!(vec.pop(), Some(None));
47assert_eq!(vec.pop(), Some(Some(20)));
48assert_eq!(vec.pop(), Some(Some(10)));
49assert_eq!(vec.pop(), None);
50assert_eq!(vec, []);
51```
52
53You can get elements from the vector
54
55```rust
56# use vec_option::VecOption;
57let mut vec = VecOption::from(vec![0, 1, 2, 3, 4]);
58assert_eq!(vec.len(), 5);
59assert_eq!(vec, [Some(0), Some(1), Some(2), Some(3), Some(4)]);
60// assert_eq!(vec.get(2), Some(Some(&2)));
61// assert_eq!(vec.get_mut(4), Some(Some(&mut 4)));
62assert_eq!(vec.get(5), None);
63```
64
65You can swap and replace elements
66
67```rust ignore
68vec.swap(2, 1);
69
70assert_eq!(vec, [Some(0), Some(2), Some(1), Some(3), Some(4)]);
71
72assert_eq!(vec.replace(3, None), Some(Some(3)));
73assert_eq!(vec.replace(1, Some(10)), Some(Some(1)));
74
75assert_eq!(vec, [Some(0), Some(10), Some(1), None, Some(4)]);
76```
77
78or if `vec.replace(index, None)` is too much, you can do
79
80```rust ignore
81assert_eq!(vec.take(1), Some(Some(10)));
82
83assert_eq!(vec, [Some(0), None, Some(1), None, Some(4)]);
84```
85
86Of course, you can also truncate or clear the vector
87
88```rust
89# use vec_option::VecOption;
90let mut vec = VecOption::from(vec![0, 1, 3, 4]);
91
92assert_eq!(vec.len(), 4);
93
94vec.truncate(2);
95
96assert_eq!(vec, [Some(0), Some(1)]);
97
98vec.clear();
99
100assert!(vec.is_empty());
101```
102
103But due to the limitations imposed by spliting the representation of the vector, you can't really get a
104`&Option<T>`/`&mut Option<T>` outside of a closure.
105In 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.
106
107These 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.
108
109```rust ignore
110vec.try_fold(...);
111
112vec.fold(...);
113
114vec.try_for_each(...);
115
116vec.for_each(...);
117```
118
119But 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!
120
121```rust
122# use vec_option::VecOption;
123let mut vec = VecOption::from(vec![0, 1, 2, 3, 4]);
124
125assert_eq!(vec, [Some(0), Some(1), Some(2), Some(3), Some(4)]);
126
127vec.extend_none(5);
128
129assert_eq!(vec, [Some(0), Some(1), Some(2), Some(3), Some(4), None, None, None, None, None]);
130
131vec.set_all_none();
132
133assert_eq!(vec, [None, None, None, None, None, None, None, None, None, None]);
134```
135*/
136
137mod bit_vec;
138// use bit_vec as bit_vec;
139
140use bit_vec::BitVec;
141
142use std::mem::MaybeUninit;
143use std::ops::{Bound, Deref, DerefMut, RangeBounds};
144
145/// # Safety
146///
147/// This code must never be run
148#[cold]
149unsafe fn unreachable_unchecked() -> ! {
150    use std::hint::unreachable_unchecked;
151
152    debug_assert!(false, "unreachable");
153    unreachable_unchecked()
154}
155
156fn as_range<R: RangeBounds<usize>>(range: &R, len: usize) -> (usize, usize) {
157    let start = match range.start_bound() {
158        Bound::Unbounded => 0,
159        Bound::Included(&x) => x,
160        Bound::Excluded(&x) => x + 1,
161    };
162
163    let end = match range.end_bound() {
164        Bound::Unbounded => len,
165        Bound::Included(&x) => x + 1,
166        Bound::Excluded(&x) => x,
167    };
168
169    (start, end)
170}
171
172trait UnwrapUnchecked {
173    type Output;
174
175    /// # Safety
176    ///
177    /// The Option<T> must be in the `Some` variant
178    unsafe fn unwrap_unchecked(self) -> Self::Output;
179}
180
181impl<T> UnwrapUnchecked for Option<T> {
182    type Output = T;
183
184    unsafe fn unwrap_unchecked(self) -> Self::Output {
185        match self {
186            Some(value) => value,
187            None => unreachable_unchecked(),
188        }
189    }
190}
191
192/// # Safety
193///
194/// The flag must corrospond to the data
195///
196/// i.e. if flag is true, then data must be initialized
197unsafe fn from_raw_parts<T>(flag: bool, data: MaybeUninit<T>) -> Option<T> {
198    if flag {
199        Some(data.assume_init())
200    } else {
201        None
202    }
203}
204
205/// # Safety
206///
207/// The flag must corrospond to the data
208///
209/// i.e. if flag is true, then data must be initialized
210unsafe fn ref_from_raw_parts<T>(flag: bool, data: &MaybeUninit<T>) -> Option<&T> {
211    if flag {
212        Some(&*data.as_ptr())
213    } else {
214        None
215    }
216}
217
218/// A space optimized version of `Vec<Option<T>>` that stores the discriminant seperately
219///
220/// See crate-level docs for more information
221///
222pub struct VecOption<T> {
223    data: Vec<MaybeUninit<T>>,
224    flag: BitVec,
225}
226
227/// The capacity information of the given `VecOption<T>`
228#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
229pub struct CapacityInfo {
230    /// The capacity of the data vector that holds `T`s
231    pub data: usize,
232
233    /// The capacity of the `BitVec` that holds the discriminants
234    pub flag: usize,
235
236    _priv: (),
237}
238
239impl<T> Default for VecOption<T> {
240    fn default() -> Self {
241        Self::new()
242    }
243}
244
245/// A proxy to a mutable reference to an option in a `VecOption<T>`
246///
247/// If this `OptionProxy` is leaked, then the option in the `VecOption<T>` will be set to `None`
248/// and the old value of that element will be leaked
249///
250/// This serves as a way to access the option directly, and will update the `VecOption<T>` on drop
251pub struct OptionProxy<'a, T> {
252    data: &'a mut MaybeUninit<T>,
253    flag: bit_vec::BitProxy<'a>,
254    value: Option<T>,
255}
256
257impl<'a, T> OptionProxy<'a, T> {
258    unsafe fn new(mut flag: bit_vec::BitProxy<'a>, data: &'a mut MaybeUninit<T>) -> Self {
259        let data_v = std::mem::replace(data, MaybeUninit::uninit());
260        let flag_v = std::mem::replace(&mut *flag, false);
261
262        flag.flush();
263
264        let value = from_raw_parts(flag_v, data_v);
265
266        Self { data, flag, value }
267    }
268}
269
270impl<T> Deref for OptionProxy<'_, T> {
271    type Target = Option<T>;
272
273    fn deref(&self) -> &Self::Target {
274        &self.value
275    }
276}
277
278impl<T> DerefMut for OptionProxy<'_, T> {
279    fn deref_mut(&mut self) -> &mut Self::Target {
280        &mut self.value
281    }
282}
283
284impl<T> Drop for OptionProxy<'_, T> {
285    fn drop(&mut self) {
286        if let Some(value) = self.value.take() {
287            // data_slot is valid and contains uninitialized memory
288            // so do not drop it, but it is valid to write to
289            unsafe {
290                self.data.as_mut_ptr().write(value);
291                *self.flag = true;
292            }
293        }
294    }
295}
296
297impl<T> VecOption<T> {
298    /// Creates an empty vector, does not allocate
299    pub fn new() -> Self {
300        Self {
301            data: Vec::new(),
302            flag: BitVec::new(),
303        }
304    }
305
306    /// Creates an empty vector
307    ///
308    /// allocates at least `cap` elements of space
309    pub fn with_capacity(cap: usize) -> Self {
310        Self {
311            data: Vec::with_capacity(cap),
312            flag: BitVec::with_capacity(cap),
313        }
314    }
315
316    /// reserves at least `amount` elements
317    ///
318    /// if there is already enough space, this does nothing
319    pub fn reserve(&mut self, amount: usize) {
320        self.data.reserve(amount);
321        self.flag.reserve(amount);
322    }
323
324    /// reserves exactly `amount` elements
325    ///
326    /// if there is already enough space, this does nothing
327    pub fn reserve_exact(&mut self, amount: usize) {
328        self.data.reserve_exact(amount);
329        self.flag.reserve_exact(amount);
330    }
331
332    /// The length of this vector
333    pub fn len(&self) -> usize {
334        self.data.len()
335    }
336
337    /// The capacity of the vector
338    pub fn capacity(&self) -> CapacityInfo {
339        CapacityInfo {
340            data: self.data.capacity(),
341            flag: self.flag.alloc_info().cap,
342            _priv: (),
343        }
344    }
345
346    /// Is this vector empty
347    pub fn is_empty(&self) -> bool {
348        self.data.is_empty()
349    }
350
351    /// Put a value at the end of the vector
352    ///
353    /// Reallocates if there is not enough space
354    pub fn push<V: Into<Option<T>>>(&mut self, value: V) {
355        let value = value.into();
356
357        match value {
358            Some(value) => {
359                self.data.push(MaybeUninit::new(value));
360                self.flag.push(true);
361            }
362            None => {
363                self.data.push(MaybeUninit::uninit());
364                self.flag.push(false);
365            }
366        }
367    }
368
369    /// Remove the last element of the vector
370    ///
371    /// returns `None` if the vector is empty
372    pub fn pop(&mut self) -> Option<Option<T>> {
373        unsafe {
374            let flag = self.flag.pop()?;
375
376            // This is safe because flag pop does the necessary checks to make sure that
377            // there are more elements
378            // This relies on the fact that `flag.len() == data.len()`
379            let data = self.data.pop().unwrap_unchecked();
380
381            // The flag and data are a pair, (same index)
382            Some(from_raw_parts(flag, data))
383        }
384    }
385
386    /// Returns a proxy to a mutable reference to the element at `index` or None if out of bounds.
387    pub fn get_mut(&mut self, index: usize) -> Option<OptionProxy<'_, T>> {
388        unsafe {
389            let flag = self.flag.get_mut(index)?;
390
391            // This is safe because flag pop does the necessary checks to make sure that
392            // there are more elements
393            // This relies on the fact that `flag.len() == data.len()`
394            let data = self.data.get_unchecked_mut(index);
395
396            // The flag and data are a pair, (same index)
397            Some(OptionProxy::new(flag, data))
398        }
399    }
400
401    /// Returns a reference to the element at `index` or None if out of bounds.
402    pub fn get(&self, index: usize) -> Option<Option<&T>> {
403        unsafe {
404            let flag = self.flag.get(index)?;
405
406            // This is safe because flag pop does the necessary checks to make sure that
407            // there are more elements
408            // This relies on the fact that `flag.len() == data.len()`
409            let data = self.data.get_unchecked(index);
410
411            // The flag and data are a pair, (same index)
412            Some(ref_from_raw_parts(flag, data))
413        }
414    }
415
416    /// Swaps two elements of the vector, panics if either index is out of bounds
417    pub fn swap(&mut self, a: usize, b: usize) {
418        self.data.swap(a, b);
419        unsafe {
420            // Swap did the necessary length checks to make sure that
421            // `a` and `b` are in bounds
422            let fa = self.flag.get_unchecked(a);
423            let fb = self.flag.get_unchecked(b);
424
425            self.flag.set(a, fb);
426            self.flag.set(b, fa);
427        }
428    }
429
430    /// Returns the element at `index` or None if out of bounds.
431    ///
432    /// Replaces the element at `index` with None.
433    pub fn take(&mut self, index: usize) -> Option<Option<T>> {
434        self.replace(index, None)
435    }
436
437    /// Replace the element at `index` with `value`
438    pub fn replace<O: Into<Option<T>>>(&mut self, index: usize, value: O) -> Option<Option<T>> {
439        unsafe {
440            let value = value.into();
441
442            let flag = self.flag.get(index)?;
443
444            // index was checked by flag.get
445            let data = self.data.get_unchecked_mut(index);
446
447            let out = if flag {
448                // flag corrosponds to data
449                Some(data.as_ptr().read())
450            } else {
451                None
452            };
453
454            match value {
455                Some(value) => {
456                    self.flag.set(index, true);
457
458                    // data is valid, use write to prevent
459                    // dropping uninitialized memory
460                    data.as_mut_ptr().write(value);
461                }
462                None => self.flag.set(index, false),
463            }
464
465            Some(out)
466        }
467    }
468
469    /// Reduces the length of the vector to `len` and drops all excess elements
470    ///
471    /// If `len` is greater than the length of the vector, nothing happens
472    pub fn truncate(&mut self, len: usize) {
473        if self.data.len() <= len {
474            return;
475        }
476
477        if std::mem::needs_drop::<T>() {
478            for (i, data) in self.data.iter_mut().enumerate().skip(len) {
479                unsafe {
480                    // index corrosponds to the index of a data, so it is valid
481                    if self.flag.get_unchecked(i) {
482                        self.flag.set(i, false);
483
484                        // data is initialized, checked by flag
485                        data.as_mut_ptr().drop_in_place()
486                    }
487                }
488            }
489        }
490
491        // decreasing the length is always fine
492        unsafe {
493            self.data.set_len(len);
494            self.flag.set_len(len);
495        }
496    }
497
498    /// Clears the vector
499    pub fn clear(&mut self) {
500        self.truncate(0)
501    }
502
503    /// Sets all of the elements in the vector to `None` and drops
504    /// all values in the closure
505    pub fn set_all_none(&mut self) {
506        if std::mem::needs_drop::<T>() {
507            for (i, data) in self.data.iter_mut().enumerate() {
508                unsafe {
509                    if self.flag.get_unchecked(i) {
510                        self.flag.set(i, false);
511                        data.as_mut_ptr().drop_in_place()
512                    }
513                }
514            }
515        } else {
516            self.flag.set_all(false);
517        }
518    }
519
520    /// Extends the vector with `additional` number of `None`s
521    pub fn extend_none(&mut self, additional: usize) {
522        self.flag.grow(additional, false);
523
524        unsafe {
525            self.reserve(additional);
526
527            let len = self.len();
528
529            // Because this is a Vec<MaybeUninit<T>>, we only need to
530            // guarantee that we have enough space in the allocatation
531            // for `set_len` to be safe, and that was done with the reserve
532            self.data.set_len(len + additional);
533        }
534    }
535
536    /// returns an iterator over references to the elements in the vector
537    pub fn iter(&self) -> Iter<'_, T> {
538        Iter {
539            data: self.data.iter(),
540            flag: self.flag.iter(),
541        }
542    }
543
544    /// returns an iterator over mutable references to the elements in the vector
545    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
546        IterMut {
547            data: self.data.iter_mut(),
548            flag: self.flag.iter_mut(),
549        }
550    }
551
552    /// Iterates over all of the `Option<T>`s in the vector and applies the closure to each one of them until
553    /// the closure short-circuits, then iteration ends
554    ///
555    /// The closure is passed the `init`, `index`, and a mutable reference to the corrosponding element of the vector
556    #[cfg(feature = "nightly")]
557    pub fn try_fold<Range: RangeBounds<usize>, A, R: std::ops::Try<Ok = A>, F: FnMut(A, usize, &mut Option<T>) -> R>(
558        &mut self,
559        range: Range,
560        mut init: A,
561        mut f: F,
562    ) -> R
563    where
564        Range: std::slice::SliceIndex<[MaybeUninit<T>], Output = [MaybeUninit<T>]>,
565    {
566        let (start, end) = as_range(&range, self.len());
567
568        let data = self.data[range].iter_mut().enumerate();
569        let flag = self.flag.iter_mut().take(end).skip(start);
570
571        for ((i, data_slot), mut flag_slot) in data.zip(flag) {
572            let flag_slot: &mut bool = &mut flag_slot;
573
574            let data = std::mem::replace(data_slot, MaybeUninit::uninit());
575            let flag = std::mem::replace(flag_slot, false);
576
577            // The flag and data are a pair, (same index)
578            let mut opt = unsafe { from_raw_parts(flag, data) };
579
580            let res = f(init, i, &mut opt);
581
582            if let Some(value) = opt {
583                *data_slot = MaybeUninit::new(value);
584                *flag_slot = true;
585            }
586
587            init = res?;
588        }
589
590        R::from_ok(init)
591    }
592
593    /// Iterates over all of the `Option<T>`s in the vector and applies the closure to each one of them until
594    /// the closure returns `Err(..)`, then iteration ends
595    ///
596    /// The closure is passed the `init`, `index`, and a mutable reference to the corrosponding element of the vector
597    ///
598    /// This is similar to `Iterator::try_fold`
599    #[cfg(not(feature = "nightly"))]
600    pub fn try_fold<
601        Range: RangeBounds<usize>,
602        A,
603        B,
604        F: FnMut(A, usize, &mut Option<T>) -> Result<A, B>,
605    >(
606        &mut self,
607        range: Range,
608        mut init: A,
609        mut f: F,
610    ) -> Result<A, B>
611    where
612        Range: std::slice::SliceIndex<[MaybeUninit<T>], Output = [MaybeUninit<T>]>,
613    {
614        let (start, end) = as_range(&range, self.len());
615
616        let data = self.data[range].iter_mut().enumerate();
617        let flag = self.flag.iter_mut().take(end).skip(start);
618
619        for ((i, data_slot), mut flag_slot) in data.zip(flag) {
620            let i = i + start;
621            let flag_slot: &mut bool = &mut flag_slot;
622
623            let data = std::mem::replace(data_slot, MaybeUninit::uninit());
624            let flag = std::mem::replace(flag_slot, false);
625
626            // The flag and data are a pair, (same index)
627            let mut opt = unsafe { from_raw_parts(flag, data) };
628
629            let res = f(init, i, &mut opt);
630
631            if let Some(value) = opt {
632                *data_slot = MaybeUninit::new(value);
633                *flag_slot = true;
634            }
635
636            init = res?;
637        }
638
639        Ok(init)
640    }
641
642    /// Iterates over all of the `Option<T>`s in the vector and applies the closure to each one
643    ///
644    /// The closure is passed the `init`, `index`, and a mutable reference to the corrosponding element of the vector
645    ///
646    /// This is similar to `Iterator::fold`
647    pub fn fold<Range: RangeBounds<usize>, A, F: FnMut(A, usize, &mut Option<T>) -> A>(
648        &mut self,
649        range: Range,
650        init: A,
651        mut f: F,
652    ) -> A
653    where
654        Range: std::slice::SliceIndex<[MaybeUninit<T>], Output = [MaybeUninit<T>]>,
655    {
656        let ret = self.try_fold(range, init, move |a, i, x| {
657            Ok::<_, std::convert::Infallible>(f(a, i, x))
658        });
659
660        match ret {
661            Ok(x) => x,
662            Err(x) => match x {},
663        }
664    }
665
666    /// Iterates over all of the `Option<T>`s in the vector and applies the closure to each one of them until
667    /// the closure short-circuits, then iteration ends
668    ///
669    /// The closure is passed the `index`, and a mutable reference to the corrosponding element of the vector
670    ///
671    /// This is similar to `Iterator::try_for_each`
672    #[cfg(feature = "nightly")]
673    pub fn try_for_each<
674        Range: RangeBounds<usize>,
675        R: std::ops::Try<Ok = ()>,
676        F: FnMut(usize, &mut Option<T>) -> R,
677    >(
678        &mut self,
679        range: Range,
680        mut f: F,
681    ) -> R
682    where
683        Range: std::slice::SliceIndex<[MaybeUninit<T>], Output = [MaybeUninit<T>]>,
684    {
685        self.try_fold(range, (), move |(), i, x| f(i, x))
686    }
687
688    /// Iterates over all of the `Option<T>`s in the vector and applies the closure to each one of them until
689    /// the closure returns `Err(..)`, then iteration ends
690    ///
691    /// The closure is passed the `index`, and a mutable reference to the corrosponding element of the vector
692    ///
693    /// This is similar to `Iterator::try_for_each`
694    #[cfg(not(feature = "nightly"))]
695    pub fn try_for_each<
696        Range: RangeBounds<usize>,
697        B,
698        F: FnMut(usize, &mut Option<T>) -> Result<(), B>,
699    >(
700        &mut self,
701        range: Range,
702        mut f: F,
703    ) -> Result<(), B>
704    where
705        Range: std::slice::SliceIndex<[MaybeUninit<T>], Output = [MaybeUninit<T>]>,
706    {
707        self.try_fold(range, (), move |(), i, x| f(i, x))
708    }
709
710    /// Iterates over all of the `Option<T>`s in the vector and applies the closure to each one
711    ///
712    /// The closure is passed the `index`, and a mutable reference to the corrosponding element of the vector
713    ///
714    /// This is similar to `Iterator::for_each`
715    pub fn for_each<Range: RangeBounds<usize>, F: FnMut(usize, &mut Option<T>)>(
716        &mut self,
717        range: Range,
718        mut f: F,
719    ) where
720        Range: std::slice::SliceIndex<[MaybeUninit<T>], Output = [MaybeUninit<T>]>,
721    {
722        self.fold(range, (), move |(), i, x| f(i, x))
723    }
724}
725
726impl<T> Drop for VecOption<T> {
727    fn drop(&mut self) {
728        if std::mem::needs_drop::<T>() {
729            self.clear()
730        }
731    }
732}
733
734fn clone_impl<T: Clone>(vec: &VecOption<T>) -> VecOption<T> {
735    vec.iter().map(|x| x.cloned()).collect()
736}
737
738impl<T: Clone> Clone for VecOption<T> {
739    #[cfg(feature = "nightly")]
740    default fn clone(&self) -> Self {
741        clone_impl(self)
742    }
743
744    #[cfg(not(feature = "nightly"))]
745    fn clone(&self) -> Self {
746        clone_impl(self)
747    }
748}
749
750#[cfg(feature = "nightly")]
751impl<T: Copy> Clone for VecOption<T> {
752    fn clone(&self) -> Self {
753        let len = self.len();
754        let mut new = Self {
755            data: Vec::with_capacity(len),
756            flag: self.flag.clone(),
757        };
758
759        unsafe {
760            new.data.set_len(len);
761            new.data.copy_from_slice(&self.data);
762        }
763
764        new
765    }
766}
767
768impl<T: PartialEq> PartialEq for VecOption<T> {
769    fn eq(&self, other: &Self) -> bool {
770        self.iter().eq(other.iter())
771    }
772}
773
774impl<T: PartialEq> PartialEq<[T]> for VecOption<T> {
775    fn eq(&self, other: &[T]) -> bool {
776        self.iter().eq(other.iter().map(Some))
777    }
778}
779
780impl<T: PartialEq, S: AsRef<[Option<T>]>> PartialEq<S> for VecOption<T> {
781    fn eq(&self, other: &S) -> bool {
782        self.iter().eq(other.as_ref().iter().map(Option::as_ref))
783    }
784}
785
786impl<T: Eq> Eq for VecOption<T> {}
787
788impl<T: PartialOrd> PartialOrd for VecOption<T> {
789    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
790        self.iter().partial_cmp(other.iter())
791    }
792}
793
794impl<T: Ord> Ord for VecOption<T> {
795    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
796        self.iter().cmp(other.iter())
797    }
798}
799
800use std::hash::{Hash, Hasher};
801
802impl<T: Hash> Hash for VecOption<T> {
803    fn hash<H: Hasher>(&self, hasher: &mut H) {
804        self.iter().for_each(|i| i.hash(hasher))
805    }
806}
807
808impl<T> std::iter::Extend<Option<T>> for VecOption<T> {
809    fn extend<I: IntoIterator<Item = Option<T>>>(&mut self, iter: I) {
810        let iter = iter.into_iter();
811
812        let (additional, _) = iter.size_hint();
813
814        self.reserve(additional);
815
816        iter.for_each(|x| self.push(x));
817    }
818}
819
820impl<T> std::iter::Extend<T> for VecOption<T> {
821    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
822        let iter = iter.into_iter();
823
824        let (additional, _) = iter.size_hint();
825
826        self.reserve(additional);
827
828        iter.for_each(|x| self.push(x));
829    }
830}
831
832impl<T> std::iter::FromIterator<Option<T>> for VecOption<T> {
833    fn from_iter<I: IntoIterator<Item = Option<T>>>(iter: I) -> Self {
834        let mut vec = Self::new();
835        vec.extend(iter);
836        vec
837    }
838}
839
840impl<T> From<Vec<T>> for VecOption<T> {
841    fn from(mut vec: Vec<T>) -> Self {
842        let len = vec.len();
843
844        let data = unsafe {
845            Vec::from_raw_parts(vec.as_mut_ptr() as *mut MaybeUninit<T>, len, vec.capacity())
846        };
847
848        std::mem::forget(vec);
849
850        let mut flag = BitVec::with_capacity(len);
851        flag.grow(len, true);
852
853        Self { data, flag }
854    }
855}
856
857impl<T> From<Vec<Option<T>>> for VecOption<T> {
858    fn from(vec: Vec<Option<T>>) -> Self {
859        let mut vec_opt = VecOption::new();
860
861        vec_opt.extend(vec);
862
863        vec_opt
864    }
865}
866
867impl<T> Drop for IntoIter<T> {
868    fn drop(&mut self) {
869        self.for_each(drop);
870    }
871}
872
873/// This struct is created by the `into_iter` method on `VecOption` (provided by the `IntoIterator` trait).
874pub struct IntoIter<T> {
875    data: std::vec::IntoIter<MaybeUninit<T>>,
876    flag: bit_vec::IntoIter,
877}
878
879impl<T> Iterator for IntoIter<T> {
880    type Item = Option<T>;
881
882    fn next(&mut self) -> Option<Self::Item> {
883        unsafe {
884            let flag = self.flag.next()?;
885            let data = self.data.next().unwrap_unchecked();
886
887            Some(from_raw_parts(flag, data))
888        }
889    }
890
891    fn size_hint(&self) -> (usize, Option<usize>) {
892        self.data.size_hint()
893    }
894
895    fn nth(&mut self, n: usize) -> Option<Self::Item> {
896        if std::mem::needs_drop::<T>() {
897            for _ in 1..n {
898                self.next()?;
899            }
900            self.next()
901        } else {
902            unsafe {
903                let flag = self.flag.nth(n)?;
904                let data = self.data.nth(n).unwrap_unchecked();
905
906                Some(from_raw_parts(flag, data))
907            }
908        }
909    }
910}
911
912impl<T> DoubleEndedIterator for IntoIter<T> {
913    fn next_back(&mut self) -> Option<Self::Item> {
914        unsafe {
915            let flag = self.flag.next_back()?;
916            let data = self.data.next_back().unwrap_unchecked();
917
918            Some(from_raw_parts(flag, data))
919        }
920    }
921
922    #[cfg(feature = "nightly")]
923    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
924        if std::mem::needs_drop::<T>() {
925            for _ in 1..n {
926                self.next_back()?;
927            }
928            self.next_back()
929        } else {
930            unsafe {
931                let flag = self.flag.nth_back(n)?;
932                let data = self.data.nth_back(n).unwrap_unchecked();
933
934                Some(from_raw_parts(flag, data))
935            }
936        }
937    }
938}
939
940impl<T> ExactSizeIterator for IntoIter<T> {}
941impl<T> std::iter::FusedIterator for IntoIter<T> {}
942
943/// This struct is created by the `iter_mut` method on `VecOption`
944pub struct IterMut<'a, T> {
945    data: std::slice::IterMut<'a, MaybeUninit<T>>,
946    flag: bit_vec::IterMut<'a>,
947}
948
949impl<'a, T> Iterator for IterMut<'a, T> {
950    type Item = OptionProxy<'a, T>;
951
952    fn next(&mut self) -> Option<Self::Item> {
953        unsafe {
954            let flag = self.flag.next()?;
955            let data = self.data.next().unwrap_unchecked();
956
957            Some(OptionProxy::new(flag, data))
958        }
959    }
960
961    fn size_hint(&self) -> (usize, Option<usize>) {
962        self.data.size_hint()
963    }
964
965    fn nth(&mut self, n: usize) -> Option<Self::Item> {
966        unsafe {
967            let data = self.data.nth(n)?;
968            let flag = self.flag.nth(n).unwrap_unchecked();
969
970            Some(OptionProxy::new(flag, data))
971        }
972    }
973}
974
975impl<T> DoubleEndedIterator for IterMut<'_, T> {
976    fn next_back(&mut self) -> Option<Self::Item> {
977        unsafe {
978            let flag = self.flag.next_back()?;
979            let data = self.data.next_back().unwrap_unchecked();
980
981            Some(OptionProxy::new(flag, data))
982        }
983    }
984
985    #[cfg(feature = "nightly")]
986    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
987        unsafe {
988            let data = self.data.nth_back(n)?;
989            let flag = self.flag.nth_back(n).unwrap_unchecked();
990
991            Some(OptionProxy::new(flag, data))
992        }
993    }
994}
995
996/// This struct is created by the `iter` method on `VecOption`
997pub struct Iter<'a, T> {
998    data: std::slice::Iter<'a, MaybeUninit<T>>,
999    flag: bit_vec::Iter<'a>,
1000}
1001
1002impl<'a, T> Iterator for Iter<'a, T> {
1003    type Item = Option<&'a T>;
1004
1005    fn next(&mut self) -> Option<Self::Item> {
1006        unsafe {
1007            let flag = self.flag.next()?;
1008            let data = self.data.next().unwrap_unchecked();
1009
1010            Some(ref_from_raw_parts(flag, data))
1011        }
1012    }
1013
1014    fn size_hint(&self) -> (usize, Option<usize>) {
1015        self.data.size_hint()
1016    }
1017
1018    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1019        unsafe {
1020            let data = self.data.nth(n)?;
1021            let flag = self.flag.nth(n).unwrap_unchecked();
1022
1023            Some(ref_from_raw_parts(flag, data))
1024        }
1025    }
1026}
1027
1028impl<T> DoubleEndedIterator for Iter<'_, T> {
1029    fn next_back(&mut self) -> Option<Self::Item> {
1030        unsafe {
1031            let flag = self.flag.next_back()?;
1032            let data = self.data.next_back().unwrap_unchecked();
1033
1034            Some(ref_from_raw_parts(flag, data))
1035        }
1036    }
1037
1038    #[cfg(feature = "nightly")]
1039    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1040        unsafe {
1041            let data = self.data.nth_back(n)?;
1042            let flag = self.flag.nth_back(n).unwrap_unchecked();
1043
1044            Some(ref_from_raw_parts(flag, data))
1045        }
1046    }
1047}
1048
1049impl<T> ExactSizeIterator for Iter<'_, T> {}
1050impl<T> std::iter::FusedIterator for Iter<'_, T> {}
1051
1052impl<T> IntoIterator for VecOption<T> {
1053    type Item = Option<T>;
1054    type IntoIter = IntoIter<T>;
1055
1056    fn into_iter(mut self) -> Self::IntoIter {
1057        IntoIter {
1058            data: std::mem::replace(&mut self.data, Vec::new()).into_iter(),
1059            flag: std::mem::replace(&mut self.flag, BitVec::new()).into_iter(),
1060        }
1061    }
1062}
1063
1064impl<'a, T> IntoIterator for &'a mut VecOption<T> {
1065    type Item = OptionProxy<'a, T>;
1066    type IntoIter = IterMut<'a, T>;
1067
1068    fn into_iter(self) -> Self::IntoIter {
1069        self.iter_mut()
1070    }
1071}
1072
1073impl<'a, T> IntoIterator for &'a VecOption<T> {
1074    type Item = Option<&'a T>;
1075    type IntoIter = Iter<'a, T>;
1076
1077    fn into_iter(self) -> Self::IntoIter {
1078        self.iter()
1079    }
1080}
1081
1082use std::fmt;
1083
1084impl<T: fmt::Debug> fmt::Debug for VecOption<T> {
1085    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1086        let mut f = f.debug_list();
1087
1088        for i in self {
1089            f.entry(&i);
1090        }
1091
1092        f.finish()
1093    }
1094}
1095
1096#[test]
1097fn test() {
1098    let mut vec = VecOption::new();
1099
1100    vec.push(10);
1101    vec.push(Some(20));
1102
1103    vec.extend_none(10);
1104
1105    vec.push(30);
1106    vec.push(40);
1107    vec.push(50);
1108    vec.push(60);
1109
1110    assert_eq!(
1111        vec,
1112        [
1113            Some(10),
1114            Some(20),
1115            None,
1116            None,
1117            None,
1118            None,
1119            None,
1120            None,
1121            None,
1122            None,
1123            None,
1124            None,
1125            Some(30),
1126            Some(40),
1127            Some(50),
1128            Some(60)
1129        ]
1130    );
1131
1132    vec.set_all_none();
1133
1134    assert!(vec.iter().eq(std::iter::repeat(None).take(16)));
1135
1136    vec.clear();
1137
1138    assert!(vec.is_empty());
1139
1140    vec.extend(vec![10, 30, 20]);
1141
1142    assert_eq!(vec, [Some(10), Some(30), Some(20)]);
1143    assert_eq!(vec, [10, 30, 20][..]);
1144
1145    assert_eq!(vec, vec.clone());
1146
1147    assert_eq!(vec.take(1), Some(Some(30)));
1148    assert_eq!(vec.replace(1, 40), Some(None));
1149    assert_eq!(vec.take(1), Some(Some(40)));
1150    vec.swap(0, 1);
1151    assert_eq!(vec, [None, Some(10), Some(20)]);
1152
1153    vec.clear();
1154
1155    vec.extend(0..10);
1156
1157    vec.for_each(.., |_, opt| {
1158        if let Some(ref mut x) = *opt {
1159            if *x % 2 == 0 {
1160                *opt = None
1161            } else {
1162                *x *= 2
1163            }
1164        }
1165    });
1166
1167    assert_eq!(
1168        vec,
1169        [
1170            None,
1171            Some(2),
1172            None,
1173            Some(6),
1174            None,
1175            Some(10),
1176            None,
1177            Some(14),
1178            None,
1179            Some(18)
1180        ]
1181    );
1182
1183    let mut counter = 0;
1184    vec.for_each(.., |_, opt| {
1185        if let Some(ref mut x) = *opt {
1186            if *x % 3 == 0 {
1187                *x /= 2
1188            } else {
1189                *opt = None
1190            }
1191        } else {
1192            counter += 1;
1193            *opt = Some(counter);
1194        }
1195    });
1196
1197    assert_eq!(
1198        vec,
1199        [
1200            Some(1),
1201            None,
1202            Some(2),
1203            Some(3),
1204            Some(3),
1205            None,
1206            Some(4),
1207            None,
1208            Some(5),
1209            Some(9)
1210        ]
1211    );
1212    
1213    let val = vec.try_fold(2..6, 0, |acc, _, opt| {
1214        let res = opt.map(|x| {
1215            acc + x
1216        }).ok_or(acc);
1217
1218        *opt = None;
1219
1220        res
1221    });
1222
1223    assert_eq!(val, Err(8));
1224
1225    assert_eq!(
1226        vec,
1227        [
1228            Some(1),
1229            None,
1230            None,
1231            None,
1232            None,
1233            None,
1234            Some(4),
1235            None,
1236            Some(5),
1237            Some(9)
1238        ]
1239    );
1240}