two_sided_vec/
lib.rs

1#![feature(
2    dropck_eyepatch, // Needed to bypass dropchk
3    allocator_api, // We need to allocate raw memory
4    alloc_layout_extra, // We need to allocate memory
5    trusted_len, // Trusted length iterators improve performance
6    min_specialization, // Used to improve extend performance
7)]
8#[cfg(feature = "serde")]
9extern crate serde;
10
11use std::{slice, ptr, iter};
12use std::fmt::{self, Formatter, Debug};
13use std::ops::{Index, Range, RangeFull, RangeFrom, RangeTo, IndexMut};
14use std::hash::{Hash, Hasher};
15
16pub mod raw;
17mod extend;
18#[cfg(feature = "serde")]
19mod serialize;
20/// The prelude of traits and objects which are generally useful.
21pub mod prelude {
22    pub use super::{TwoSidedExtend, TwoSidedVec};
23}
24
25pub use self::extend::TwoSidedExtend;
26use self::raw::{RawTwoSidedVec, Capacity, CapacityRequest};
27
28/// Internal macro used to count the number of expressions passed to the `two_sided_vec!` macro.
29#[macro_export(local_inner_macros)]
30#[doc(hidden)]
31macro_rules! count_exprs {
32    () => (0);
33    ($one:expr) => (1);
34    ($first:expr, $($value:expr),*) => ($crate::count_exprs!($($value),*) + 1)
35}
36/// Creates a `TwoSidedVec` from the specified elements.
37///
38/// ## Examples
39/// ````
40/// # #[macro_use] extern crate two_sided_vec;
41/// # fn main() {
42/// let example = two_sided_vec![1, 2, 3; 4, 5, 6];
43/// assert_eq!(example.back(), &[1, 2, 3]);
44/// assert_eq!(example.front(), &[4, 5, 6]);
45/// let example = two_sided_vec![4, 5, 6];
46/// assert_eq!(example.back(), &[]);
47/// assert_eq!(example.front(), &[4, 5, 6]);
48/// # }
49/// ````
50#[macro_export]
51macro_rules! two_sided_vec {
52    () => (TwoSidedVec::new());
53    ($($element:expr),*) => (two_sided_vec![; $($element),*]);
54    ($($back:expr),*; $($front:expr),*) =>  {{
55        let mut result = $crate::TwoSidedVec::with_capacity(
56            $crate::count_exprs!($($back),*),
57            $crate::count_exprs!($($front),*)
58        );
59        $(result.push_back($back);)*
60        if !result.back().is_empty() {
61            result.back_mut().reverse();
62        }
63        $(result.push_front($front);)*
64        result
65    }}
66}
67
68impl<T> Default for RawTwoSidedVec<T> {
69    fn default() -> Self {
70        RawTwoSidedVec::new()
71    }
72}
73/// A simple 'two sided' vector, that can grow both forwards and backwards.
74///
75/// The front and the back can be viewed as seperate and independent vectors,
76/// with negative indexing accessing the back and positive indexing accessing the front.
77/// This allows you to **append to the back without modifying positive indexes**.
78/// Unless you actually need pushing to the back to appear to shift the front forward,
79/// like `VecDeque` does, this negative index system will probably be better for your situation.
80///
81/// Internally this allows a much simpler and faster implementation,
82/// since there's only a single pointer to the middle that grows up and down.
83/// Internally, we have to reallocate the buffer if we run out of capacity in either the
84/// negative or positive difes grow separately and
85/// Although bounds checks are _slightly_ slower since they involve two comparisons,
86/// the access itself should be just as fast.
87pub struct TwoSidedVec<T> {
88    memory: RawTwoSidedVec<T>,
89    start_index: isize,
90    end_index: isize,
91}
92impl<T> TwoSidedVec<T> {
93    #[inline]
94    pub fn new() -> Self {
95        unsafe {
96            TwoSidedVec::from_raw(RawTwoSidedVec::new())
97        }
98    }
99    #[inline]
100    pub fn with_capacity(back: usize, front: usize) -> Self {
101        unsafe {
102            TwoSidedVec::from_raw(RawTwoSidedVec::with_capacity(Capacity { back, front }))
103        }
104    }
105    #[inline]
106    unsafe fn from_raw(memory: RawTwoSidedVec<T>) -> Self {
107        TwoSidedVec { memory, start_index: 0, end_index: 0 }
108    }
109    /// Take a slice of the front of this queue
110    #[inline]
111    pub fn front(&self) -> &[T] {
112        unsafe {
113            slice::from_raw_parts(self.middle_ptr(), self.len_front())
114        }
115    }
116    /// Take a slice of the back of this queue
117    #[inline]
118    pub fn back(&self) -> &[T] {
119        unsafe {
120            slice::from_raw_parts(self.start_ptr(), self.len_back())
121        }
122    }
123    /// Take a mutable slice of the front of this queue
124    #[inline]
125    pub fn front_mut(&mut self) -> &mut [T] {
126        self.split_mut().1
127    }
128    /// Take a mutable slice of the back of this queue
129    #[inline]
130    pub fn back_mut(&mut self) -> &mut [T] {
131        self.split_mut().0
132    }
133    /// Take seperate slices of the back and the front of the vector respectively.
134    #[inline]
135    pub fn split(&self) -> (&[T], &[T]) {
136        (self.back(), self.front())
137    }
138    /// Take seperate mutable slices of the back and front of the vector respectively.
139    #[inline]
140    pub fn split_mut(&mut self) -> (&mut [T], &mut [T]) {
141        unsafe {
142            (
143                slice::from_raw_parts_mut(self.start_ptr(), self.len_back()),
144                slice::from_raw_parts_mut(self.middle_ptr(), self.len_front())
145            )
146        }
147    }
148    #[inline]
149    pub fn push_front(&mut self, value: T) {
150        self.reserve_front(1);
151        unsafe {
152            ptr::write(self.end_ptr(), value);
153            self.end_index += 1;
154        }
155    }
156    #[inline]
157    pub fn pop_front(&mut self) -> Option<T> {
158        if self.end_index > 0 {
159            self.end_index -= 1;
160            unsafe {
161                Some(ptr::read(self.end_ptr()))
162            }
163        } else {
164            None
165        }
166    }
167    #[inline]
168    pub fn pop_back(&mut self) -> Option<T> {
169        if self.start_index < 0 {
170            self.start_index += 1;
171            unsafe {
172                Some(ptr::read(self.middle_ptr().offset(self.start_index - 1)))
173            }
174        } else {
175            None
176        }
177    }
178    /// Push the specified value into the front of this queue,
179    /// without modifying its `end` or touching the front of the queue.
180    ///
181    /// This effectively **preserves all positive indexes**,
182    /// which may or may not be useful for your situation.
183    #[inline]
184    pub fn push_back(&mut self, value: T) {
185        self.reserve_back(1);
186        unsafe {
187            ptr::write(self.start_ptr().offset(-1), value);
188            self.start_index -= 1;
189        }
190    }
191    fn default_extend_back<I: Iterator<Item=T>>(&mut self, iter: I) {
192        if let Some(hint) = iter.size_hint().1 { self.reserve_back(hint) };
193        for value in iter {
194            self.push_back(value);
195        }
196    }
197    fn default_extend_front<I: Iterator<Item=T>>(&mut self, iter: I) {
198        if let Some(hint) = iter.size_hint().1 { self.reserve_front(hint) };
199        for value in iter {
200            self.push_front(value);
201        }
202    }
203    unsafe fn raw_extend_back(&mut self, mut target: *const T, len: usize) {
204        self.reserve_back(len);
205        let target_end = target.add(len);
206        let mut start_ptr = self.start_ptr();
207        while target < target_end {
208            start_ptr = start_ptr.sub(1);
209            start_ptr.copy_from_nonoverlapping(target, 1);
210            target = target.add(1);
211        }
212        self.start_index -= len as isize;
213        debug_assert_eq!(self.start_ptr(), start_ptr);
214    }
215    unsafe fn raw_extend_front(&mut self, target: *const T, len: usize) {
216        self.reserve_front(len);
217        self.end_ptr().copy_from_nonoverlapping(target, len);
218        self.end_index += len as isize;
219    }
220    #[inline]
221    pub fn reserve_back(&mut self, amount: usize) {
222        debug_assert!(self.check_sanity());
223        if !self.can_fit_back(amount) {
224            self.grow(0, amount);
225        }
226        debug_assert!(self.can_fit_back(amount))
227    }
228    #[inline]
229    pub fn reserve_front(&mut self, amount: usize) {
230        debug_assert!(self.check_sanity());
231        if !self.can_fit_front(amount) {
232            self.grow(amount, 0);
233        }
234        debug_assert!(
235            self.can_fit_front(amount),
236            "Insufficient capacity {:?} for {} additional elements. end_index = {}, start_index = {}, len = {}",
237            self.memory.capacity(), amount, self.end_index, self.start_index, self.len()
238        );
239    }
240    #[cold] #[inline(never)]
241    fn grow(&mut self, front: usize, back: usize) {
242        let request = CapacityRequest {
243            used: Capacity { back: self.len_back(), front: self.len_front() },
244            needed: Capacity { front, back }
245        };
246        self.memory.reserve(request);
247    }
248    #[inline]
249    fn can_fit_front(&self, amount: usize) -> bool {
250        let remaining_front = self.capacity_front() - self.len_front();
251        remaining_front >= amount
252    }
253    #[inline]
254    fn can_fit_back(&self, amount: usize) -> bool {
255        let remaining_back = self.capacity_back() - self.len_back();
256        remaining_back >= amount
257    }
258    #[inline]
259    pub fn capacity_back(&self) -> usize {
260        self.memory.capacity().back
261    }
262    #[inline]
263    pub fn capacity_front(&self) -> usize {
264        self.memory.capacity().front
265    }
266    /// Return the length of the entire vector, which is the sum of the
267    /// lengths of the front and back parts.
268    ///
269    /// The **length isn't where the vector ends**,
270    /// since it could have elements in the back with negative indexes.
271    /// Use `vec.start()` and `vec.end()` if you want to know the start and end indexes.
272    /// The total length is exactly equivalent to `vec.len_back() + vec.len_front()`
273    #[inline]
274    pub fn len(&self) -> usize {
275        debug_assert!(self.start_index <= self.end_index);
276        self.end_index.wrapping_sub(self.start_index) as usize
277    }
278    #[inline]
279    pub fn is_empty(&self) -> bool {
280        self.start_index == self.end_index
281    }
282    /// Return the length of the back of the vector.
283    #[inline]
284    pub fn len_back(&self) -> usize {
285        debug_assert!(self.start_index <= 0);
286        // NOTE: We perform the cast immediately after the negation to handle overflow properly
287        self.start_index.wrapping_neg() as usize
288    }
289    /// Return the length of the front of the vector
290    #[inline]
291    pub fn len_front(&self) -> usize {
292        debug_assert!(self.end_index >= 0);
293        self.end_index as usize
294    }
295    /// Give the (inclusive) start of the queue's elements.
296    /// which may be negative if the queue's back isn't empty
297    ///
298    /// This is exactly equivelant to `-vec.back().len()`.
299    #[inline]
300    pub fn start(&self) -> isize {
301        self.start_index
302    }
303    /// Give the (exclusive) end of the queue's elements,
304    /// which may be less than the length if the queue's back contains some elements.
305    ///
306    /// This is exactly equivalent to `vec.front().len()`
307    #[inline]
308    pub fn end(&self) -> isize {
309        self.end_index
310    }
311    /// Return the `[start, end)` range of the element indices,
312    /// equivalent to a tuple of `(queue.start(), queue.end())`.
313    #[inline]
314    pub fn range(&self) -> Range<isize> {
315        self.start_index..self.end_index
316    }
317    /// Iterate over the entire vector, including both the back and front.
318    #[inline]
319    pub fn iter_entire(&self) -> slice::Iter<T> {
320        self[..].iter()
321    }
322    #[inline]
323    pub fn get<I: TwoSidedIndex<T>>(&self, index: I) -> Option<&I::Output> {
324        index.get(self)
325    }
326    #[inline]
327    pub fn get_mut<I: TwoSidedIndex<T>>(&mut self, index: I) -> Option<&mut I::Output> {
328        index.get_mut(self)
329    }
330    /// Get a reference to value at the specified index
331    ///
332    /// ## Safety
333    /// Undefined behavior if the index is out of bounds
334    #[inline]
335    pub unsafe fn get_unchecked<I: TwoSidedIndex<T>>(&self, index: I) -> &I::Output {
336        index.get_unchecked(self)
337    }
338
339    /// Get a mutable reference to value at the specified index
340    ///
341    /// ## Safety
342    /// Undefined behavior if the index is out of bounds
343    #[inline]
344    pub unsafe fn get_unchecked_mut<I: TwoSidedIndex<T>>(&mut self, index: I) -> &mut I::Output {
345        index.get_unchecked_mut(self)
346    }
347    /// Give a raw pointer to the start of the elements
348    #[inline]
349    pub fn start_ptr(&self) -> *mut T {
350        unsafe {
351            self.middle_ptr().offset(self.start_index)
352        }
353    }
354    /// Give a raw pointer to the middle of the elements
355    #[inline]
356    pub fn middle_ptr(&self) -> *mut T {
357        self.memory.middle()
358    }
359    #[inline]
360    pub fn end_ptr(&self) -> *mut T {
361        unsafe {
362            self.middle_ptr().offset(self.end_index)
363        }
364    }
365    #[inline]
366    pub fn split_at(&self, index: isize) -> (&[T], &[T]) {
367        (&self[..index], &self[index..])
368    }
369    fn check_sanity(&self) -> bool {
370        assert!(self.start_index <= 0 && self.end_index >= 0);
371        // These should be implied by the other checks
372        debug_assert!(self.start_ptr() <= self.middle_ptr());
373        debug_assert!(self.end_ptr() >= self.middle_ptr());
374        true
375    }
376    pub fn clear(&mut self) {
377        while let Some(value) = self.pop_back()  {
378            drop(value)
379        }
380        while let Some(value) = self.pop_front() {
381            drop(value)
382        }
383        debug_assert_eq!(self.len(), 0);
384    }
385    /// Enumerate the indices and values of the elements in the back of the vector.
386    ///
387    /// The primary advantage over regular enumeration is that it
388    /// gives proper negative indices since the elements are in the back.
389    #[inline]
390    pub fn enumerate_back(&self) -> SignedEnumerate<slice::Iter<T>> {
391        SignedEnumerate::new(self.start_index, self.back().iter())
392    }
393    /// Enumerate the indices and values of the elements in the front of the vector.
394    ///
395    /// The only possible advantage over regular enumeration is that it
396    /// gives positive `isize` indices for consistency with enumeration over the back.
397    #[inline]
398    pub fn enumerate_front(&self) -> SignedEnumerate<slice::Iter<T>> {
399        SignedEnumerate::new(0, self.front().iter())
400    }
401    /// Enumerate the indices and values of each element in the front and back.
402    ///
403    /// The primary advantage over regular enumeration is that
404    /// it gives proper negative indices for elements that are in the back.
405    #[inline]
406    pub fn enumerate(&self) -> SignedEnumerate<slice::Iter<T>> {
407        SignedEnumerate::new(self.start(), self[..].iter())
408    }
409    /// Mutably enumerate the indices and values of each element in the front and back.
410    ///
411    /// The primary advantage over regular enumeration is that
412    /// it gives proper negative indices for elements that are in the back.
413    #[inline]
414    pub fn enumerate_mut(&mut self) -> SignedEnumerate<slice::IterMut<T>> {
415        SignedEnumerate::new(self.start(), self[..].iter_mut())
416    }
417    pub fn truncate_back(&mut self, len: usize) {
418        // Not as optimized as `truncate_front` because I'm lazy ;)
419        while self.len_back() > len {
420            drop(self.pop_back().unwrap())
421        }
422    }
423    pub fn truncate_front(&mut self, len: usize) {
424        unsafe {
425            // drop any extra elements
426            while self.len_front() > len {
427                // decrement len before the drop_in_place(), so a panic on Drop
428                // doesn't re-drop the just-failed value.
429                self.end_index -= 1;
430                ptr::drop_in_place(self.middle_ptr().offset(self.end_index));
431            }
432        }
433    }
434    pub fn retain<F: FnMut(isize, &mut T) -> bool>(&mut self, mut pred: F) {
435        self.retain_back(|index, element| pred(index, element));
436        self.retain_front(|index, element| pred(index, element));
437    }
438    pub fn retain_back<F: FnMut(isize, &mut T) -> bool>(&mut self, mut pred: F) {
439        self.drain_filter_back(|index, element| !pred(index, element));
440    }
441    pub fn retain_front<F: FnMut(isize, &mut T) -> bool>(&mut self, mut pred: F) {
442        self.drain_filter_front(|index, element| !pred(index, element));
443    }
444    pub fn drain_filter_back<F: FnMut(isize, &mut T) -> bool>(&mut self, pred: F) -> DrainFilterBack<T, F> {
445        let old_len = self.len_back();
446        self.back_mut().reverse();
447        // Guard against us getting leaked (leak amplification)
448        self.start_index = 0;
449        DrainFilterBack {
450            old_len, index: 0, del: 0, vec: self, pred
451        }
452    }
453    pub fn drain_filter_front<F: FnMut(isize, &mut T) -> bool>(&mut self, pred: F) -> DrainFilterFront<T, F> {
454        let old_len = self.end_index as usize;
455        // Guard against us getting leaked (leak amplification)
456        self.end_index = 0;
457        DrainFilterFront {
458            old_len, index: 0, del: 0, vec: self, pred
459        }
460    }
461}
462impl<T: Clone> Clone for TwoSidedVec<T> {
463    fn clone(&self) -> Self {
464        let mut result = TwoSidedVec::with_capacity(
465            self.len_back(),
466            self.len_front()
467        );
468        result.extend_back(self.back().iter().rev().cloned());
469        result.extend_front(self.front().iter().cloned());
470        result
471    }
472}
473impl<T> Default for TwoSidedVec<T> {
474    #[inline]
475    fn default() -> Self {
476        TwoSidedVec::new()
477    }
478}
479impl<T: Debug> Debug for TwoSidedVec<T> {
480    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
481        f.debug_struct("TwoSidedVec")
482            .field("back", &self.back())
483            .field("front", &self.front())
484            .finish()
485    }
486}
487unsafe impl<#[may_dangle] T> Drop for TwoSidedVec<T> {
488    fn drop(&mut self) {
489        unsafe {
490            // use drop for owned slice `[T]` just like vec
491            ptr::drop_in_place(&mut self[..])
492        }
493    }
494}
495pub trait TwoSidedIndex<T>: Sized + Debug {
496    type Output: ?Sized;
497    /// Use this as an index against the specified vec
498    ///
499    /// ## Safety
500    /// Undefined behavior if the index is out of bounds
501    unsafe fn get_unchecked(self, target: &TwoSidedVec<T>) -> &Self::Output;
502    /// Use this as an index against the specified vec
503    ///
504    /// ## Safety
505    /// Undefined behavior if the index is out of bounds
506    unsafe fn get_unchecked_mut(self, target: &mut TwoSidedVec<T>) -> &mut Self::Output;
507    fn check(&self, target: &TwoSidedVec<T>) -> bool;
508    #[inline]
509    fn get(self, target: &TwoSidedVec<T>) -> Option<&Self::Output> {
510        if self.check(target) {
511            Some(unsafe { self.get_unchecked(target) })
512        } else {
513            None
514        }
515    }
516    #[inline]
517    fn get_mut(self, target: &mut TwoSidedVec<T>) -> Option<&mut Self::Output> {
518        if self.check(target) {
519            Some(unsafe { self.get_unchecked_mut(target) })
520        } else {
521            None
522        }
523    }
524    #[inline]
525    fn index(self, target: &TwoSidedVec<T>) -> &Self::Output {
526        if self.check(target) {
527            unsafe { self.get_unchecked(target) }
528        } else {
529            self.invalid()
530        }
531    }
532    #[inline]
533    fn index_mut(self, target: &mut TwoSidedVec<T>) -> &mut Self::Output {
534        if self.check(target) {
535            unsafe { self.get_unchecked_mut(target) }
536        } else {
537            self.invalid()
538        }
539    }
540    #[cold]
541    #[inline(never)]
542    fn invalid(self) -> ! {
543        panic!("Invalid index: {:?}", self)
544    }
545}
546impl<T, I: TwoSidedIndex<T>> Index<I> for TwoSidedVec<T> {
547    type Output = I::Output;
548    #[inline]
549    fn index(&self, index: I) -> &I::Output {
550        index.index(self)
551    }
552}
553impl<T, I: TwoSidedIndex<T>> IndexMut<I> for TwoSidedVec<T> {
554    #[inline]
555    fn index_mut(&mut self, index: I) -> &mut I::Output {
556        index.index_mut(self)
557    }
558}
559impl<T> TwoSidedIndex<T> for isize {
560    type Output = T;
561
562    #[inline]
563    unsafe fn get_unchecked(self, target: &TwoSidedVec<T>) -> &Self::Output {
564        debug_assert!(self.check(target));
565        &*target.middle_ptr().offset(self)
566    }
567
568    #[inline]
569    unsafe fn get_unchecked_mut(self, target: &mut TwoSidedVec<T>) -> &mut Self::Output {
570        &mut *target.middle_ptr().offset(self)
571    }
572
573    #[inline]
574    fn check(&self, target: &TwoSidedVec<T>) -> bool {
575        *self >= target.start_index && *self < target.end_index
576    }
577}
578impl<T> TwoSidedIndex<T> for Range<isize> {
579    type Output = [T];
580
581    #[inline]
582    unsafe fn get_unchecked(self, target: &TwoSidedVec<T>) -> &Self::Output {
583        slice::from_raw_parts(
584            target.middle_ptr().offset(self.start),
585            (self.end - self.start) as usize
586        )
587    }
588
589    #[inline]
590    unsafe fn get_unchecked_mut(self, target: &mut TwoSidedVec<T>) -> &mut Self::Output {
591        slice::from_raw_parts_mut(
592            target.middle_ptr().offset(self.start),
593            (self.end - self.start) as usize
594        )
595    }
596
597    #[inline]
598    fn check(&self, target: &TwoSidedVec<T>) -> bool {
599        self.start >= target.start_index
600            && self.start <= self.end
601            && self.end <= target.end_index
602    }
603}
604
605impl<T> TwoSidedIndex<T> for RangeFull {
606    type Output = [T];
607
608    #[inline]
609    unsafe fn get_unchecked(self, target: &TwoSidedVec<T>) -> &Self::Output {
610        slice::from_raw_parts(
611            target.middle_ptr().offset(target.start_index),
612            target.len()
613        )
614    }
615
616    #[inline]
617    unsafe fn get_unchecked_mut(self, target: &mut TwoSidedVec<T>) -> &mut Self::Output {
618        slice::from_raw_parts_mut(
619            target.middle_ptr().offset(target.start_index),
620            target.len()
621        )
622    }
623
624    #[inline]
625    fn check(&self, _target: &TwoSidedVec<T>) -> bool {
626        true
627    }
628}
629impl<T> TwoSidedIndex<T> for RangeFrom<isize> {
630    type Output = [T];
631
632    #[inline]
633    unsafe fn get_unchecked(self, target: &TwoSidedVec<T>) -> &Self::Output {
634        slice::from_raw_parts(
635            target.middle_ptr().offset(self.start),
636            (target.end_index - self.start) as usize
637        )
638    }
639
640    #[inline]
641    unsafe fn get_unchecked_mut(self, target: &mut TwoSidedVec<T>) -> &mut Self::Output {
642        slice::from_raw_parts_mut(
643            target.middle_ptr().offset(self.start),
644            (target.end_index - self.start) as usize
645        )
646    }
647
648    #[inline]
649    fn check(&self, target: &TwoSidedVec<T>) -> bool {
650        self.start >= target.start_index && self.start <= target.end_index
651    }
652}
653impl<T> TwoSidedIndex<T> for RangeTo<isize> {
654    type Output = [T];
655
656    #[inline]
657    unsafe fn get_unchecked(self, target: &TwoSidedVec<T>) -> &Self::Output {
658        slice::from_raw_parts(
659            target.middle_ptr().offset(target.start_index),
660            (self.end - target.start_index) as usize
661        )
662    }
663
664    #[inline]
665    unsafe fn get_unchecked_mut(self, target: &mut TwoSidedVec<T>) -> &mut Self::Output {
666        slice::from_raw_parts_mut(
667            target.middle_ptr().offset(target.start_index),
668            (self.end - target.start_index) as usize
669        )
670    }
671
672    #[inline]
673    fn check(&self, target: &TwoSidedVec<T>) -> bool {
674        self.end >= target.start_index && self.end <= target.end_index
675    }
676}
677
678
679pub struct SignedEnumerate<I> {
680    index: isize,
681    handle: I
682}
683impl<I: Iterator> SignedEnumerate<I> {
684    #[inline]
685    pub fn new(start: isize, handle: I) -> Self {
686        debug_assert!((handle.size_hint().1.unwrap_or(0) as isize)
687                          .checked_add(start).is_some(), "Overflow!");
688        SignedEnumerate { index: start, handle }
689    }
690}
691impl<T, I: Iterator<Item=T>> Iterator for SignedEnumerate<I> {
692    type Item = (isize, T);
693
694    #[inline]
695    fn next(&mut self) -> Option<Self::Item> {
696        if let Some(value) = self.handle.next() {
697            let index = self.index;
698            self.index += 1;
699            Some((index, value))
700        } else {
701            None
702        }
703    }
704
705    #[inline]
706    fn size_hint(&self) -> (usize, Option<usize>) {
707        self.handle.size_hint()
708    }
709}
710impl<I> iter::DoubleEndedIterator for SignedEnumerate<I>
711    where I: iter::DoubleEndedIterator + iter::ExactSizeIterator {
712    #[inline]
713    fn next_back(&mut self) -> Option<Self::Item> {
714        self.handle.next_back().map(|value| {
715            let len = self.handle.len();
716            // I'm going to pretend this is the caller's responsibility
717            debug_assert!(len <= isize::max_value() as usize);
718            (self.index + (len as isize), value)
719        })
720    }
721}
722impl<I: iter::FusedIterator> iter::FusedIterator for SignedEnumerate<I> {}
723impl<I: iter::ExactSizeIterator> iter::ExactSizeIterator for SignedEnumerate<I> {}
724unsafe impl<I: iter::TrustedLen> iter::TrustedLen for SignedEnumerate<I> {}
725
726impl<T> From<Vec<T>> for TwoSidedVec<T> {
727    #[inline]
728    fn from(mut original: Vec<T>) -> Self {
729        let ptr = original.as_mut_ptr();
730        let capacity = original.capacity();
731        let len = original.len();
732        TwoSidedVec {
733            memory: unsafe { RawTwoSidedVec::from_raw_parts(
734                ptr,
735                Capacity { back: 0, front: capacity }
736            ) },
737            end_index: len as isize,
738            start_index: 0
739        }
740    }
741}
742impl<T: PartialEq<U>, U> PartialEq<TwoSidedVec<U>> for TwoSidedVec<T> {
743    fn eq(&self, other: &TwoSidedVec<U>) -> bool {
744        if self.start() == other.start() && self.end() == other.end() {
745            for (first, second) in self.back().iter().zip(other.back()) {
746                if first != second {
747                    return false
748                }
749            }
750            for (first, second) in self.front().iter().zip(other.front()) {
751                if first != second {
752                    return false
753                }
754            }
755            true
756        } else {
757            false
758        }
759    }
760}
761impl<T: Eq> Eq for TwoSidedVec<T> {}
762impl<T: Hash> Hash for TwoSidedVec<T> {
763    #[inline]
764    fn hash<H: Hasher>(&self, state: &mut H) {
765        /*
766         * NOTE: We also need to take their start into account,
767         * since otherwise [; 1, 2, 3] and [1 ; 2, 3] would hash the same.
768         */
769        state.write_isize(self.start());
770        T::hash_slice(self.back(), state);
771        T::hash_slice(self.front(), state);
772    }
773}
774
775pub struct DrainFilterBack<'a, T: 'a, F: FnMut(isize, &mut T) -> bool> {
776    vec: &'a mut TwoSidedVec<T>,
777    index: usize,
778    del: usize,
779    old_len: usize,
780    pred: F
781}
782impl<'a, T: 'a, F: FnMut(isize, &mut T) -> bool> Iterator for DrainFilterBack<'a, T, F> {
783    type Item = T;
784    fn next(&mut self) -> Option<T> {
785        // Because we reversed the memory this is almost the exact same as `DrainFilterFront`
786        unsafe {
787            while self.index != self.old_len {
788                let i = self.index;
789                self.index += 1;
790                let v = slice::from_raw_parts_mut(
791                    self.vec.middle_ptr().sub(self.old_len),
792                    self.old_len
793                );
794                let actual_index = -((i + 1) as isize);
795                if (self.pred)(actual_index, &mut v[i]) {
796                    self.del += 1;
797                    return Some(ptr::read(&v[i]));
798                } else if self.del > 0 {
799                    let del = self.del;
800                    let src: *const T = &v[i];
801                    let dst: *mut T = &mut v[i - del];
802                    // This is safe because self.vec has length 0
803                    // thus its elements will not have Drop::drop
804                    // called on them in the event of a panic.
805                    ptr::copy_nonoverlapping(src, dst, 1);
806                }
807            }
808            None
809        }
810    }
811    #[inline]
812    fn size_hint(&self) -> (usize, Option<usize>) {
813        (0, Some(self.old_len - self.index))
814    }
815}
816
817impl<'a, T, F: FnMut(isize, &mut T) -> bool> Drop for DrainFilterBack<'a, T, F> {
818    fn drop(&mut self) {
819        for _ in self.by_ref() {}
820        let target_len = self.old_len - self.del;
821        unsafe {
822            ptr::copy_nonoverlapping(
823                self.vec.middle_ptr().sub(self.old_len),
824                self.vec.middle_ptr().sub(target_len),
825                target_len
826            );
827        }
828        debug_assert!(target_len <= isize::max_value() as usize);
829        self.vec.start_index = -(target_len as isize);
830        // Reverse the order so we're back to where we started
831        self.vec.back_mut().reverse();
832    }
833}
834
835
836
837pub struct DrainFilterFront<'a, T: 'a, F: FnMut(isize, &mut T) -> bool> {
838    vec: &'a mut TwoSidedVec<T>,
839    index: usize,
840    del: usize,
841    old_len: usize,
842    pred: F
843}
844impl<'a, T: 'a, F: FnMut(isize, &mut T) -> bool> Iterator for DrainFilterFront<'a, T, F> {
845    type Item = T;
846    #[inline]
847    fn next(&mut self) -> Option<T> {
848        unsafe {
849            while self.index != self.old_len {
850                let i = self.index;
851                self.index += 1;
852                let v = slice::from_raw_parts_mut(self.vec.middle_ptr(), self.old_len);
853                if (self.pred)(i as isize, &mut v[i]) {
854                    self.del += 1;
855                    return Some(ptr::read(&v[i]));
856                } else if self.del > 0 {
857                    let del = self.del;
858                    let src: *const T = &v[i];
859                    let dst: *mut T = &mut v[i - del];
860                    // This is safe because self.vec has length 0
861                    // thus its elements will not have Drop::drop
862                    // called on them in the event of a panic.
863                    ptr::copy_nonoverlapping(src, dst, 1);
864                }
865            }
866            None
867        }
868    }
869    #[inline]
870    fn size_hint(&self) -> (usize, Option<usize>) {
871        (0, Some(self.old_len - self.index))
872    }
873}
874impl<'a, T, F: FnMut(isize, &mut T) -> bool> Drop for DrainFilterFront<'a, T, F> {
875    fn drop(&mut self) {
876        for _ in self.by_ref() {}
877        let target_len = (self.old_len - self.del) as isize;
878        assert!(target_len >= 0);
879        self.vec.end_index = target_len as isize;
880    }
881}