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
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A deque implemented as a hybrid linked-list-of-arrays

#![cfg_attr(all(test, feature = "nightly"), feature(test))]
#[cfg(all(test, feature = "nightly"))] extern crate test;

extern crate linked_list;
extern crate traverse;

use std::cmp::Ordering;
use std::collections::{vec_deque, VecDeque};
use std::iter::{self, IntoIterator};
use std::fmt;
use std::hash::{Hash, Hasher};
use traverse::Traversal;
use linked_list::LinkedList;

/// A skeleton implementation of a BList, based on the [Space-Efficient Linked List]
/// (http://opendatastructures.org/ods-python/3_3_SEList_Space_Efficient_.html) described in
/// Open Data Structures.
///
/// A BList is a hybrid between an array and a doubly-linked-list. It consists of arrays in a
/// doubly-linked-list. In this way we get many of the nice properties of a LinkedList, but with
/// improved cache properties and less allocations.
///
/// A BList's B-factor is analogous to the same factor in a BTree. It guarantees that all nodes
/// contain `B-1` and `B+1` elements (except the ends). Once a position has been identified to
/// perform an insertion or deletion, it will take amortized `O(B)` time to perform, with a
/// worst-case cost of `O(B^2)`. Insertion and deletion on either end will always take
/// `O(1)` time, though (assuming it takes `O(1)` time to allocate an array of size `B`).
#[derive(Clone)]
pub struct BList<T> {
    list: LinkedList<VecDeque<T>>,
    b: usize,
    len: usize,
}

// Constructors
impl<T> BList<T> {
    /// Creates a new BList with a reasonable choice for B.
    pub fn new() -> BList<T> {
        // VecDeque always has capacity = 2^k - 1, for some k;
        // b = 6 gets us max_len = b + 1 = 7 = 2^3 - 1
        BList::with_b(6)
    }

    /// Creates a new BList with the specified B.
    pub fn with_b(b: usize) -> BList<T> {
        assert!(b > 1, "B must be > 1");
        BList {
            list: LinkedList::new(),
            b: b,
            len: 0,
        }
    }
}

// Methods
impl<T> BList<T> {
    /// Inserts the element at the back of the list.
    pub fn push_back(&mut self, elem: T) {
        self.len = self.len.checked_add(1).expect("capacity overflow");
        let b = self.b;
        let max = block_max(b);
        if let Some(block) = self.list.back_mut() {
            if block.len() < max {
                block.push_back(elem);
                return;
            }
        }

        // Couldn't insert, gotta make a new back
        let mut new_block = make_block(b);
        new_block.push_back(elem);
        self.list.push_back(new_block);
    }

    /// Inserts the element at the front of the list.
    pub fn push_front(&mut self, elem: T) {
        self.len = self.len.checked_add(1).expect("capacity overflow");
        let b = self.b;
        let max = block_max(b);
        if let Some(block) = self.list.front_mut() {
            if block.len() < max {
                block.push_front(elem);
                return;
            }
        }

        // Couldn't insert, gotta make a new front
        let mut new_block = make_block(b);
        new_block.push_front(elem);
        self.list.push_front(new_block);
    }

    /// Removes and returns an element off the back of the list. Returns None if empty.
    pub fn pop_back(&mut self) -> Option<T> {
        let (result, should_pop) = match self.list.back_mut() {
            None => (None, false),
            Some(block) => (block.pop_back(), block.is_empty()),
        };

        if should_pop {
            self.list.pop_back();
        }

        if result.is_some() {
            self.len -= 1;
        }

        result
    }

    /// Removes and returns an element off the front of the list. Returns None if empty.
    pub fn pop_front(&mut self) -> Option<T> {
        let (result, should_pop) = match self.list.front_mut() {
            None => (None, false),
            Some(block) => (block.pop_front(), block.is_empty()),
        };

        if should_pop {
            self.list.pop_front();
        }

        if result.is_some() {
            self.len -= 1;
        }

        result
    }

    /// Gets an immutable reference to the first element in the list.
    pub fn front(&self) -> Option<&T> {
        self.list.front().and_then(|block| block.front())
    }

    /// Gets an immutable reference to the last element in the list.
    pub fn back(&self) -> Option<&T> {
        self.list.back().and_then(|block| block.back())
    }

    /// Gets a mutable reference to the first element in the list.
    pub fn front_mut(&mut self) -> Option<&mut T> {
        self.list.front_mut().and_then(|block| block.front_mut())
    }

    /// Gets a mutable reference to the last element in the list.
    pub fn back_mut(&mut self) -> Option<&mut T> {
        self.list.back_mut().and_then(|block| block.back_mut())
    }

    /// Gets the number of elements in the list.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if the list contains no elements, or `false` otherwise.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Drops everything in the list.
    pub fn clear(&mut self) {
        self.list.clear();
    }

    /// Gets a by-reference iterator over the elements in the list.
    pub fn iter(&self) -> Iter<T> {
        let len = self.len();
        Iter(AbsIter {
            list_iter: self.list.iter(),
            right_block_iter: None,
            left_block_iter: None,
            len: len,
        })
    }

    /// Gets a by-mutable-reference iterator over the elements in the list.
    pub fn iter_mut(&mut self) -> IterMut<T> {
        let len = self.len();
        IterMut(AbsIter {
            list_iter: self.list.iter_mut(),
            right_block_iter: None,
            left_block_iter: None,
            len: len,
        })
    }

    /// Gets a by-value iterator over the elements in the list.
    pub fn into_iter(self) -> IntoIter<T> {
        let len = self.len();
        IntoIter(AbsIter {
            list_iter: self.list.into_iter(),
            right_block_iter: None,
            left_block_iter: None,
            len: len,
        })
    }

    pub fn traversal(&self) -> Trav<T> {
        Trav { list: self }
    }

    pub fn traversal_mut(&mut self) -> TravMut<T> {
        TravMut { list: self }
    }

    pub fn into_traversal(self) -> IntoTrav<T> {
        IntoTrav { list: self }
    }

    /// Lazily moves the contents of `other` to the end of `self`, in the sense that it makes no
    /// effort to preserve the node-size lower-bound invariant. This can have negative effects
    /// on the effeciency of the resulting list, but is otherwise much faster than a proper
    /// invariant-preserving `append`.
    ///
    /// # Panics
    ///
    /// Panics if the lists have a different value of `B`.
    pub fn append_lazy(&mut self, other: &mut BList<T>) {
        assert!(self.b == other.b);
        self.list.append(&mut other.list);
        self.len += other.len;
        other.len = 0;
    }
}

impl<'a, T> IntoIterator for &'a BList<T> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;
    fn into_iter(self) -> Iter<'a, T> { self.iter() }
}

impl<'a, T> IntoIterator for &'a mut BList<T> {
    type Item = &'a mut T;
    type IntoIter = IterMut<'a, T>;
    fn into_iter(self) -> IterMut<'a, T> { self.iter_mut() }
}

impl<T> IntoIterator for BList<T> {
    type Item = T;
    type IntoIter = IntoIter<T>;
    fn into_iter(self) -> IntoIter<T> { self.into_iter() }
}

/// Makes a new block for insertion in the list.
fn make_block<T>(b: usize) -> VecDeque<T> {
     VecDeque::with_capacity(block_max(b))
}

/// Gets the largest a block is allowed to become.
fn block_max(b: usize) -> usize {
    b + 1
}

/// Gets the smallest a (non-end) block is allowed to become.
#[allow(unused)]
fn block_min(b: usize) -> usize {
    b - 1
}

/// A by-ref iterator for a BList
pub struct Iter<'a, T: 'a>
    (AbsIter<linked_list::Iter<'a, VecDeque<T>>, vec_deque::Iter<'a, T>>);
/// A by-mut-ref iterator for a BList
pub struct IterMut<'a, T: 'a>
    (AbsIter<linked_list::IterMut<'a, VecDeque<T>>, vec_deque::IterMut<'a, T>>);
/// A by-value iterator for a BList
pub struct IntoIter<T>
    (AbsIter<linked_list::IntoIter<VecDeque<T>>, vec_deque::IntoIter<T>>);

/// An iterator that abstracts over all three kinds of ownership for a BList
struct AbsIter<LinkedListIter, VecDequeIter> {
    list_iter: LinkedListIter,
    left_block_iter: Option<VecDequeIter>,
    right_block_iter: Option<VecDequeIter>,
    len: usize,
}

impl<VecDequeIter, LinkedListIter> Iterator for AbsIter<LinkedListIter, VecDequeIter> where
    VecDequeIter: Iterator,
    LinkedListIter: Iterator,
    LinkedListIter::Item: IntoIterator<IntoIter=VecDequeIter, Item=VecDequeIter::Item>
{
    type Item = VecDequeIter::Item;
    // I would like to thank all my friends and the fact that Iterator::next doesn't
    // borrow self, for this passing borrowck with minimal gymnastics
    fn next(&mut self) -> Option<VecDequeIter::Item> {
        if self.len > 0 { self.len -= 1; }
        // Keep loopin' till we hit gold
        loop {
            // Try to read off the left iterator
            let (ret, iter) = match self.left_block_iter.as_mut() {
                // No left iterator, try to get one from the list iterator
                None => match self.list_iter.next() {
                    // No blocks left in the list, use the right iterator
                    None => match self.right_block_iter.as_mut() {
                        // Truly exhausted
                        None => return None,
                        // Got right iter; don't care about fixing right_block in forward iteration
                        Some(iter) => return iter.next(),
                    },
                    // Got new block from list iterator, make it the new left iterator
                    Some(block) => {
                        let mut next_iter = block.into_iter();
                        let next = next_iter.next();
                        (next, Some(next_iter))
                    },
                },
                Some(iter) => match iter.next() {
                    // None out the iterator so we ask for a new one, or go to the right
                    None => (None, None),
                    Some(next) => return Some(next),
                },
            };

            // If we got here, we want to change what left_block_iter is, so do that
            // Also, if we got a return value, return that. Otherwise, just loop until we do.
            self.left_block_iter = iter;
            if ret.is_some() {
                return ret;
            }
        }
    }

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

impl<VecDequeIter, LinkedListIter> DoubleEndedIterator
for AbsIter<LinkedListIter, VecDequeIter> where
    VecDequeIter: DoubleEndedIterator,
    LinkedListIter: DoubleEndedIterator,
    LinkedListIter::Item: IntoIterator<IntoIter=VecDequeIter, Item=VecDequeIter::Item>
{
    // see `next` for details. This should be an exact mirror.
    fn next_back(&mut self) -> Option<VecDequeIter::Item> {
        if self.len > 0 { self.len -= 1; }
        loop {
            let (ret, iter) = match self.right_block_iter.as_mut() {
                None => match self.list_iter.next_back() {
                    None => match self.left_block_iter.as_mut() {
                        None => return None,
                        Some(iter) => return iter.next_back(),
                    },
                    Some(block) => {
                        let mut next_iter = block.into_iter();
                        let next = next_iter.next_back();
                        (next, Some(next_iter))
                    },
                },
                Some(iter) => match iter.next_back() {
                    None => (None, None),
                    Some(next) => return Some(next),
                },
            };

            self.right_block_iter = iter;
            if ret.is_some() {
                return ret;
            }
        }
    }
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;
    fn next(&mut self) -> Option<&'a T> { self.0.next() }
    fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
}
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
    fn next_back(&mut self) -> Option<&'a T> { self.0.next_back() }
}
impl<'a, T> ExactSizeIterator for Iter<'a, T> {}

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;
    fn next(&mut self) -> Option<&'a mut T> { self.0.next() }
    fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
}
impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
    fn next_back(&mut self) -> Option<&'a mut T> { self.0.next_back() }
}
impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}

impl<T> Iterator for IntoIter<T> {
    type Item = T;
    fn next(&mut self) -> Option<T> { self.0.next() }
    fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
}
impl<T> DoubleEndedIterator for IntoIter<T> {
    fn next_back(&mut self) -> Option<T> { self.0.next_back() }
}
impl<T> ExactSizeIterator for IntoIter<T> {}

pub struct Trav<'a, T: 'a> {
    list: &'a BList<T>,
}

pub struct TravMut<'a, T: 'a> {
    list: &'a mut BList<T>,
}

pub struct IntoTrav<T> {
    list: BList<T>,
}

impl<'a, T> Traversal for Trav<'a, T> {
    type Item = &'a T;

    fn foreach<F>(self, mut f: F) where F: FnMut(&'a T) -> bool {
        for node in self.list.list.iter() {
            for elem in node.iter() {
                if f(elem) { return; }
            }
        }
    }
}

impl<'a, T> Traversal for TravMut<'a, T> {
    type Item = &'a mut T;

    fn foreach<F>(self, mut f: F) where F: FnMut(&'a mut T) -> bool {
        for node in self.list.list.iter_mut() {
            for elem in node.iter_mut() {
                if f(elem) { return; }
            }
        }
    }
}

impl<T> Traversal for IntoTrav<T> {
    type Item = T;

    fn foreach<F>(self, mut f: F) where F: FnMut(T) -> bool {
        for node in self.list.list.into_iter() {
            for elem in node.into_iter() {
                if f(elem) { return; }
            }
        }
    }
}

impl<A> iter::FromIterator<A> for BList<A> {
    fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> BList<A> {
        let mut ret = BList::new();
        ret.extend(iter);
        ret
    }
}

impl<A> Extend<A> for BList<A> {
    fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T) {
        for elt in iter { self.push_back(elt); }
    }
}

impl<A: PartialEq> PartialEq for BList<A> {
    fn eq(&self, other: &Self) -> bool {
        if self.len() == other.len() {
            let mut a = self.iter();
            let mut b = other.iter();
            loop {
                match (a.next(), b.next()) {
                    (Some(x), Some(y)) => if x != y {
                        return false;
                    },
                    (None, None) => return true,
                    _ => return false
                }
            }
        } else {
            false
        }
    }
}

impl<A: Eq> Eq for BList<A> {}

impl<A: PartialOrd> PartialOrd for BList<A> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        let mut a = self.iter();
        let mut b = other.iter();
        loop {
            match (a.next(), b.next()) {
                (Some(x), Some(y)) => match x.partial_cmp(&y) {
                    Some(Ordering::Equal) => {}
                    otherwise => return otherwise,
                },
                (None, None) => return Some(Ordering::Equal),
                (None, _) => return Some(Ordering::Less),
                (_, None) => return Some(Ordering::Greater),
            }
        }
    }
}

impl<A: Ord> Ord for BList<A> {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl<A: fmt::Debug> fmt::Debug for BList<A> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "["));

        for (i, e) in self.iter().enumerate() {
            if i != 0 { try!(write!(f, ", ")); }
            try!(write!(f, "{:?}", *e));
        }

        write!(f, "]")
    }
}

impl<A: Hash> Hash for BList<A> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.len().hash(state);
        for elt in self.iter() {
            elt.hash(state);
        }
    }
}



#[cfg(test)]
mod tests {
    use super::BList;

    fn generate_test() -> BList<i32> {
        list_from(&[0,1,2,3,4,5,6])
    }

    fn list_from<T: Clone>(v: &[T]) -> BList<T> {
        v.iter().map(|x| (*x).clone()).collect()
    }

    #[test]
    fn test_basic() {
        let mut m = BList::new();
        assert_eq!(m.pop_front(), None);
        assert_eq!(m.pop_back(), None);
        assert_eq!(m.pop_front(), None);
        m.push_front(1);
        assert_eq!(m.pop_front(), Some(1));
        m.push_back(2);
        m.push_back(3);
        assert_eq!(m.len(), 2);
        assert_eq!(m.pop_front(), Some(2));
        assert_eq!(m.pop_front(), Some(3));
        assert_eq!(m.len(), 0);
        assert_eq!(m.pop_front(), None);
        m.push_back(1);
        m.push_back(3);
        m.push_back(5);
        m.push_back(7);
        assert_eq!(m.pop_front(), Some(1));

        let mut n = BList::new();
        n.push_front(2);
        n.push_front(3);
        {
            assert_eq!(n.front().unwrap(), &3);
            let x = n.front_mut().unwrap();
            assert_eq!(*x, 3);
            *x = 0;
        }
        {
            assert_eq!(n.back().unwrap(), &2);
            let y = n.back_mut().unwrap();
            assert_eq!(*y, 2);
            *y = 1;
        }
        assert_eq!(n.pop_front(), Some(0));
        assert_eq!(n.pop_front(), Some(1));
    }

    #[test]
    fn test_iterator() {
        let m = generate_test();
        for (i, elt) in m.iter().enumerate() {
            assert_eq!(i as i32, *elt);
        }
        let mut n = BList::new();
        assert_eq!(n.iter().next(), None);
        n.push_front(4);
        let mut it = n.iter();
        assert_eq!(it.size_hint(), (1, Some(1)));
        assert_eq!(it.next().unwrap(), &4);
        assert_eq!(it.size_hint(), (0, Some(0)));
        assert_eq!(it.next(), None);
    }


    #[test]
    fn test_iterator_double_end() {
        let mut n = BList::new();
        assert_eq!(n.iter().next(), None);
        n.push_front(4);
        n.push_front(5);
        n.push_front(6);
        let mut it = n.iter();
        assert_eq!(it.size_hint(), (3, Some(3)));
        assert_eq!(it.next().unwrap(), &6);
        assert_eq!(it.size_hint(), (2, Some(2)));
        assert_eq!(it.next_back().unwrap(), &4);
        assert_eq!(it.size_hint(), (1, Some(1)));
        assert_eq!(it.next_back().unwrap(), &5);
        assert_eq!(it.next_back(), None);
        assert_eq!(it.next(), None);
    }

    #[test]
    fn test_rev_iter() {
        let m = generate_test();
        for (i, elt) in m.iter().rev().enumerate() {
            assert_eq!(6 - i as i32, *elt);
        }
        let mut n = BList::new();
        assert_eq!(n.iter().rev().next(), None);
        n.push_front(4);
        let mut it = n.iter().rev();
        assert_eq!(it.size_hint(), (1, Some(1)));
        assert_eq!(it.next().unwrap(), &4);
        assert_eq!(it.size_hint(), (0, Some(0)));
        assert_eq!(it.next(), None);
    }

    #[test]
    fn test_mut_iter() {
        let mut m = generate_test();
        let mut len = m.len();
        for (i, elt) in m.iter_mut().enumerate() {
            assert_eq!(i as i32, *elt);
            len -= 1;
        }
        assert_eq!(len, 0);
        let mut n = BList::new();
        assert!(n.iter_mut().next().is_none());
        n.push_front(4);
        n.push_back(5);
        let mut it = n.iter_mut();
        assert_eq!(it.size_hint(), (2, Some(2)));
        assert!(it.next().is_some());
        assert!(it.next().is_some());
        assert_eq!(it.size_hint(), (0, Some(0)));
        assert!(it.next().is_none());
    }

    #[test]
    fn test_iterator_mut_double_end() {
        let mut n = BList::new();
        assert!(n.iter_mut().next_back().is_none());
        n.push_front(4);
        n.push_front(5);
        n.push_front(6);
        let mut it = n.iter_mut();
        assert_eq!(it.size_hint(), (3, Some(3)));
        assert_eq!(*it.next().unwrap(), 6);
        assert_eq!(it.size_hint(), (2, Some(2)));
        assert_eq!(*it.next_back().unwrap(), 4);
        assert_eq!(it.size_hint(), (1, Some(1)));
        assert_eq!(*it.next_back().unwrap(), 5);
        assert!(it.next_back().is_none());
        assert!(it.next().is_none());
    }

    #[test]
    fn test_eq() {
        let mut n: BList<u8> = list_from(&[]);
        let mut m = list_from(&[]);
        assert!(n == m);
        n.push_front(1);
        assert!(n != m);
        m.push_back(1);
        assert!(n == m);

        let n = list_from(&[2,3,4]);
        let m = list_from(&[1,2,3]);
        assert!(n != m);
    }
/* unstable
    #[test]
    fn test_hash() {
      let mut x = BList::new();
      let mut y = BList::new();

      assert!(hash::hash::<_, hash::SipHasher>(&x) == hash::hash::<_, hash::SipHasher>(&y));

      x.push_back(1);
      x.push_back(2);
      x.push_back(3);

      y.push_front(3);
      y.push_front(2);
      y.push_front(1);

      assert!(hash::hash::<_, hash::SipHasher>(&x) == hash::hash::<_, hash::SipHasher>(&y));
    }
*/
    #[test]
    fn test_ord() {
        let n = list_from(&[]);
        let m = list_from(&[1,2,3]);
        assert!(n < m);
        assert!(m > n);
        assert!(n <= n);
        assert!(n >= n);
    }

    #[test]
    fn test_ord_nan() {
        let nan = 0.0f64/0.0;
        let n = list_from(&[nan]);
        let m = list_from(&[nan]);
        assert!(!(n < m));
        assert!(!(n > m));
        assert!(!(n <= m));
        assert!(!(n >= m));

        let n = list_from(&[nan]);
        let one = list_from(&[1.0f64]);
        assert!(!(n < one));
        assert!(!(n > one));
        assert!(!(n <= one));
        assert!(!(n >= one));

        let u = list_from(&[1.0f64,2.0,nan]);
        let v = list_from(&[1.0f64,2.0,3.0]);
        assert!(!(u < v));
        assert!(!(u > v));
        assert!(!(u <= v));
        assert!(!(u >= v));

        let s = list_from(&[1.0f64,2.0,4.0,2.0]);
        let t = list_from(&[1.0f64,2.0,3.0,2.0]);
        assert!(!(s < t));
        assert!(s > one);
        assert!(!(s <= one));
        assert!(s >= one);
    }

    #[test]
    fn test_debug() {
        let list: BList<i32> = (0..10).collect();
        assert_eq!(format!("{:?}", list), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");

        let list: BList<&str> = vec!["just", "one", "test", "more"].iter()
                                                                   .map(|&s| s)
                                                                   .collect();
        assert_eq!(format!("{:?}", list), r#"["just", "one", "test", "more"]"#);
    }

    #[test]
    fn test_append_lazy() {
        let mut u = list_from(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
        let mut v = list_from(&[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]);
        let w = list_from(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
                            10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]);
        let x = list_from(&[]);

        // Normal append
        u.append_lazy(&mut v);
        assert_eq!(u.len(), 22);
        assert_eq!(v.len(), 0);
        assert_eq!(u, w);
        assert_eq!(v, x);

        // no-op append
        u.append_lazy(&mut v);
        assert_eq!(u.len(), 22);
        assert_eq!(v.len(), 0);
        assert_eq!(u, w);
        assert_eq!(v, x);

        // append into empty
        v.append_lazy(&mut u);
        assert_eq!(v.len(), 22);
        assert_eq!(u.len(), 0);
        assert_eq!(v, w);
        assert_eq!(u, x);
    }
}

#[cfg(all(test, feature = "nightly"))]
mod bench{
    use test;
    use super::BList;
    use traverse::Traversal;

    #[bench]
    fn bench_collect_into(b: &mut test::Bencher) {
        let v = &[0i32; 64];
        b.iter(|| {
            let _: BList<i32> = v.iter().map(|x| *x).collect();
        })
    }

    #[bench]
    fn bench_push_front(b: &mut test::Bencher) {
        let mut m: BList<i32> = BList::new();
        b.iter(|| {
            m.push_front(0);
        })
    }

    #[bench]
    fn bench_push_back(b: &mut test::Bencher) {
        let mut m: BList<i32> = BList::new();
        b.iter(|| {
            m.push_back(0);
        })
    }

    #[bench]
    fn bench_push_back_pop_back(b: &mut test::Bencher) {
        let mut m: BList<i32> = BList::new();
        b.iter(|| {
            m.push_back(0);
            m.pop_back();
        })
    }

    #[bench]
    fn bench_push_front_pop_front(b: &mut test::Bencher) {
        let mut m: BList<i32> = BList::new();
        b.iter(|| {
            m.push_front(0);
            m.pop_front();
        })
    }

    #[bench]
    fn bench_iter(b: &mut test::Bencher) {
        let v = &[0; 128];
        let m: BList<i32> = v.iter().map(|&x|x).collect();
        b.iter(|| {
            assert!(m.iter().count() == 128);
        })
    }
    #[bench]
    fn bench_iter_mut(b: &mut test::Bencher) {
        let v = &[0; 128];
        let mut m: BList<i32> = v.iter().map(|&x|x).collect();
        b.iter(|| {
            assert!(m.iter_mut().count() == 128);
        })
    }

    #[bench]
    fn bench_iter_rev(b: &mut test::Bencher) {
        let v = &[0; 128];
        let m: BList<i32> = v.iter().map(|&x|x).collect();
        b.iter(|| {
            assert!(m.iter().rev().count() == 128);
        })
    }
    #[bench]
    fn bench_iter_mut_rev(b: &mut test::Bencher) {
        let v = &[0; 128];
        let mut m: BList<i32> = v.iter().map(|&x|x).collect();
        b.iter(|| {
            assert!(m.iter_mut().rev().count() == 128);
        })
    }

    #[bench]
    fn bench_trav(b: &mut test::Bencher) {
        let v = &[0; 128];
        let m: BList<i32> = v.iter().map(|&x|x).collect();
        b.iter(|| {
            assert!(m.traversal().count() == 128);
        })
    }
}