]> git.lizzy.rs Git - rust.git/blob - src/liballoc/linked_list.rs
Auto merge of #44969 - QuietMisdreavus:impls-for-everyone, r=steveklabnik
[rust.git] / src / liballoc / linked_list.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A doubly-linked list with owned nodes.
12 //!
13 //! The `LinkedList` allows pushing and popping elements at either end
14 //! in constant time.
15 //!
16 //! Almost always it is better to use `Vec` or [`VecDeque`] instead of
17 //! [`LinkedList`]. In general, array-based containers are faster,
18 //! more memory efficient and make better use of CPU cache.
19 //!
20 //! [`LinkedList`]: ../linked_list/struct.LinkedList.html
21 //! [`VecDeque`]: ../vec_deque/struct.VecDeque.html
22
23 #![stable(feature = "rust1", since = "1.0.0")]
24
25 use core::cmp::Ordering;
26 use core::fmt;
27 use core::hash::{Hasher, Hash};
28 use core::iter::{FromIterator, FusedIterator};
29 use core::marker::PhantomData;
30 use core::mem;
31 use core::ops::{BoxPlace, InPlace, Place, Placer};
32 use core::ptr::{self, Shared};
33
34 use boxed::{Box, IntermediateBox};
35 use super::SpecExtend;
36
37 /// A doubly-linked list with owned nodes.
38 ///
39 /// The `LinkedList` allows pushing and popping elements at either end
40 /// in constant time.
41 ///
42 /// Almost always it is better to use `Vec` or `VecDeque` instead of
43 /// `LinkedList`. In general, array-based containers are faster,
44 /// more memory efficient and make better use of CPU cache.
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub struct LinkedList<T> {
47     head: Option<Shared<Node<T>>>,
48     tail: Option<Shared<Node<T>>>,
49     len: usize,
50     marker: PhantomData<Box<Node<T>>>,
51 }
52
53 struct Node<T> {
54     next: Option<Shared<Node<T>>>,
55     prev: Option<Shared<Node<T>>>,
56     element: T,
57 }
58
59 /// An iterator over the elements of a `LinkedList`.
60 ///
61 /// This `struct` is created by the [`iter`] method on [`LinkedList`]. See its
62 /// documentation for more.
63 ///
64 /// [`iter`]: struct.LinkedList.html#method.iter
65 /// [`LinkedList`]: struct.LinkedList.html
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub struct Iter<'a, T: 'a> {
68     head: Option<Shared<Node<T>>>,
69     tail: Option<Shared<Node<T>>>,
70     len: usize,
71     marker: PhantomData<&'a Node<T>>,
72 }
73
74 #[stable(feature = "collection_debug", since = "1.17.0")]
75 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
76     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
77         f.debug_tuple("Iter")
78          .field(&self.len)
79          .finish()
80     }
81 }
82
83 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
84 #[stable(feature = "rust1", since = "1.0.0")]
85 impl<'a, T> Clone for Iter<'a, T> {
86     fn clone(&self) -> Self {
87         Iter { ..*self }
88     }
89 }
90
91 /// A mutable iterator over the elements of a `LinkedList`.
92 ///
93 /// This `struct` is created by the [`iter_mut`] method on [`LinkedList`]. See its
94 /// documentation for more.
95 ///
96 /// [`iter_mut`]: struct.LinkedList.html#method.iter_mut
97 /// [`LinkedList`]: struct.LinkedList.html
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub struct IterMut<'a, T: 'a> {
100     list: &'a mut LinkedList<T>,
101     head: Option<Shared<Node<T>>>,
102     tail: Option<Shared<Node<T>>>,
103     len: usize,
104 }
105
106 #[stable(feature = "collection_debug", since = "1.17.0")]
107 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
108     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109         f.debug_tuple("IterMut")
110          .field(&self.list)
111          .field(&self.len)
112          .finish()
113     }
114 }
115
116 /// An owning iterator over the elements of a `LinkedList`.
117 ///
118 /// This `struct` is created by the [`into_iter`] method on [`LinkedList`][`LinkedList`]
119 /// (provided by the `IntoIterator` trait). See its documentation for more.
120 ///
121 /// [`into_iter`]: struct.LinkedList.html#method.into_iter
122 /// [`LinkedList`]: struct.LinkedList.html
123 #[derive(Clone)]
124 #[stable(feature = "rust1", since = "1.0.0")]
125 pub struct IntoIter<T> {
126     list: LinkedList<T>,
127 }
128
129 #[stable(feature = "collection_debug", since = "1.17.0")]
130 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
131     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
132         f.debug_tuple("IntoIter")
133          .field(&self.list)
134          .finish()
135     }
136 }
137
138 impl<T> Node<T> {
139     fn new(element: T) -> Self {
140         Node {
141             next: None,
142             prev: None,
143             element,
144         }
145     }
146
147     fn into_element(self: Box<Self>) -> T {
148         self.element
149     }
150 }
151
152 // private methods
153 impl<T> LinkedList<T> {
154     /// Adds the given node to the front of the list.
155     #[inline]
156     fn push_front_node(&mut self, mut node: Box<Node<T>>) {
157         unsafe {
158             node.next = self.head;
159             node.prev = None;
160             let node = Some(Shared::from(Box::into_unique(node)));
161
162             match self.head {
163                 None => self.tail = node,
164                 Some(mut head) => head.as_mut().prev = node,
165             }
166
167             self.head = node;
168             self.len += 1;
169         }
170     }
171
172     /// Removes and returns the node at the front of the list.
173     #[inline]
174     fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
175         self.head.map(|node| unsafe {
176             let node = Box::from_raw(node.as_ptr());
177             self.head = node.next;
178
179             match self.head {
180                 None => self.tail = None,
181                 Some(mut head) => head.as_mut().prev = None,
182             }
183
184             self.len -= 1;
185             node
186         })
187     }
188
189     /// Adds the given node to the back of the list.
190     #[inline]
191     fn push_back_node(&mut self, mut node: Box<Node<T>>) {
192         unsafe {
193             node.next = None;
194             node.prev = self.tail;
195             let node = Some(Shared::from(Box::into_unique(node)));
196
197             match self.tail {
198                 None => self.head = node,
199                 Some(mut tail) => tail.as_mut().next = node,
200             }
201
202             self.tail = node;
203             self.len += 1;
204         }
205     }
206
207     /// Removes and returns the node at the back of the list.
208     #[inline]
209     fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
210         self.tail.map(|node| unsafe {
211             let node = Box::from_raw(node.as_ptr());
212             self.tail = node.prev;
213
214             match self.tail {
215                 None => self.head = None,
216                 Some(mut tail) => tail.as_mut().next = None,
217             }
218
219             self.len -= 1;
220             node
221         })
222     }
223 }
224
225 #[stable(feature = "rust1", since = "1.0.0")]
226 impl<T> Default for LinkedList<T> {
227     /// Creates an empty `LinkedList<T>`.
228     #[inline]
229     fn default() -> Self {
230         Self::new()
231     }
232 }
233
234 impl<T> LinkedList<T> {
235     /// Creates an empty `LinkedList`.
236     ///
237     /// # Examples
238     ///
239     /// ```
240     /// use std::collections::LinkedList;
241     ///
242     /// let list: LinkedList<u32> = LinkedList::new();
243     /// ```
244     #[inline]
245     #[stable(feature = "rust1", since = "1.0.0")]
246     pub fn new() -> Self {
247         LinkedList {
248             head: None,
249             tail: None,
250             len: 0,
251             marker: PhantomData,
252         }
253     }
254
255     /// Moves all elements from `other` to the end of the list.
256     ///
257     /// This reuses all the nodes from `other` and moves them into `self`. After
258     /// this operation, `other` becomes empty.
259     ///
260     /// This operation should compute in O(1) time and O(1) memory.
261     ///
262     /// # Examples
263     ///
264     /// ```
265     /// use std::collections::LinkedList;
266     ///
267     /// let mut list1 = LinkedList::new();
268     /// list1.push_back('a');
269     ///
270     /// let mut list2 = LinkedList::new();
271     /// list2.push_back('b');
272     /// list2.push_back('c');
273     ///
274     /// list1.append(&mut list2);
275     ///
276     /// let mut iter = list1.iter();
277     /// assert_eq!(iter.next(), Some(&'a'));
278     /// assert_eq!(iter.next(), Some(&'b'));
279     /// assert_eq!(iter.next(), Some(&'c'));
280     /// assert!(iter.next().is_none());
281     ///
282     /// assert!(list2.is_empty());
283     /// ```
284     #[stable(feature = "rust1", since = "1.0.0")]
285     pub fn append(&mut self, other: &mut Self) {
286         match self.tail {
287             None => mem::swap(self, other),
288             Some(mut tail) => {
289                 if let Some(mut other_head) = other.head.take() {
290                     unsafe {
291                         tail.as_mut().next = Some(other_head);
292                         other_head.as_mut().prev = Some(tail);
293                     }
294
295                     self.tail = other.tail.take();
296                     self.len += mem::replace(&mut other.len, 0);
297                 }
298             }
299         }
300     }
301
302     /// Provides a forward iterator.
303     ///
304     /// # Examples
305     ///
306     /// ```
307     /// use std::collections::LinkedList;
308     ///
309     /// let mut list: LinkedList<u32> = LinkedList::new();
310     ///
311     /// list.push_back(0);
312     /// list.push_back(1);
313     /// list.push_back(2);
314     ///
315     /// let mut iter = list.iter();
316     /// assert_eq!(iter.next(), Some(&0));
317     /// assert_eq!(iter.next(), Some(&1));
318     /// assert_eq!(iter.next(), Some(&2));
319     /// assert_eq!(iter.next(), None);
320     /// ```
321     #[inline]
322     #[stable(feature = "rust1", since = "1.0.0")]
323     pub fn iter(&self) -> Iter<T> {
324         Iter {
325             head: self.head,
326             tail: self.tail,
327             len: self.len,
328             marker: PhantomData,
329         }
330     }
331
332     /// Provides a forward iterator with mutable references.
333     ///
334     /// # Examples
335     ///
336     /// ```
337     /// use std::collections::LinkedList;
338     ///
339     /// let mut list: LinkedList<u32> = LinkedList::new();
340     ///
341     /// list.push_back(0);
342     /// list.push_back(1);
343     /// list.push_back(2);
344     ///
345     /// for element in list.iter_mut() {
346     ///     *element += 10;
347     /// }
348     ///
349     /// let mut iter = list.iter();
350     /// assert_eq!(iter.next(), Some(&10));
351     /// assert_eq!(iter.next(), Some(&11));
352     /// assert_eq!(iter.next(), Some(&12));
353     /// assert_eq!(iter.next(), None);
354     /// ```
355     #[inline]
356     #[stable(feature = "rust1", since = "1.0.0")]
357     pub fn iter_mut(&mut self) -> IterMut<T> {
358         IterMut {
359             head: self.head,
360             tail: self.tail,
361             len: self.len,
362             list: self,
363         }
364     }
365
366     /// Returns `true` if the `LinkedList` is empty.
367     ///
368     /// This operation should compute in O(1) time.
369     ///
370     /// # Examples
371     ///
372     /// ```
373     /// use std::collections::LinkedList;
374     ///
375     /// let mut dl = LinkedList::new();
376     /// assert!(dl.is_empty());
377     ///
378     /// dl.push_front("foo");
379     /// assert!(!dl.is_empty());
380     /// ```
381     #[inline]
382     #[stable(feature = "rust1", since = "1.0.0")]
383     pub fn is_empty(&self) -> bool {
384         self.head.is_none()
385     }
386
387     /// Returns the length of the `LinkedList`.
388     ///
389     /// This operation should compute in O(1) time.
390     ///
391     /// # Examples
392     ///
393     /// ```
394     /// use std::collections::LinkedList;
395     ///
396     /// let mut dl = LinkedList::new();
397     ///
398     /// dl.push_front(2);
399     /// assert_eq!(dl.len(), 1);
400     ///
401     /// dl.push_front(1);
402     /// assert_eq!(dl.len(), 2);
403     ///
404     /// dl.push_back(3);
405     /// assert_eq!(dl.len(), 3);
406     /// ```
407     #[inline]
408     #[stable(feature = "rust1", since = "1.0.0")]
409     pub fn len(&self) -> usize {
410         self.len
411     }
412
413     /// Removes all elements from the `LinkedList`.
414     ///
415     /// This operation should compute in O(n) time.
416     ///
417     /// # Examples
418     ///
419     /// ```
420     /// use std::collections::LinkedList;
421     ///
422     /// let mut dl = LinkedList::new();
423     ///
424     /// dl.push_front(2);
425     /// dl.push_front(1);
426     /// assert_eq!(dl.len(), 2);
427     /// assert_eq!(dl.front(), Some(&1));
428     ///
429     /// dl.clear();
430     /// assert_eq!(dl.len(), 0);
431     /// assert_eq!(dl.front(), None);
432     /// ```
433     #[inline]
434     #[stable(feature = "rust1", since = "1.0.0")]
435     pub fn clear(&mut self) {
436         *self = Self::new();
437     }
438
439     /// Returns `true` if the `LinkedList` contains an element equal to the
440     /// given value.
441     ///
442     /// # Examples
443     ///
444     /// ```
445     /// use std::collections::LinkedList;
446     ///
447     /// let mut list: LinkedList<u32> = LinkedList::new();
448     ///
449     /// list.push_back(0);
450     /// list.push_back(1);
451     /// list.push_back(2);
452     ///
453     /// assert_eq!(list.contains(&0), true);
454     /// assert_eq!(list.contains(&10), false);
455     /// ```
456     #[stable(feature = "linked_list_contains", since = "1.12.0")]
457     pub fn contains(&self, x: &T) -> bool
458         where T: PartialEq<T>
459     {
460         self.iter().any(|e| e == x)
461     }
462
463     /// Provides a reference to the front element, or `None` if the list is
464     /// empty.
465     ///
466     /// # Examples
467     ///
468     /// ```
469     /// use std::collections::LinkedList;
470     ///
471     /// let mut dl = LinkedList::new();
472     /// assert_eq!(dl.front(), None);
473     ///
474     /// dl.push_front(1);
475     /// assert_eq!(dl.front(), Some(&1));
476     /// ```
477     #[inline]
478     #[stable(feature = "rust1", since = "1.0.0")]
479     pub fn front(&self) -> Option<&T> {
480         unsafe {
481             self.head.as_ref().map(|node| &node.as_ref().element)
482         }
483     }
484
485     /// Provides a mutable reference to the front element, or `None` if the list
486     /// is empty.
487     ///
488     /// # Examples
489     ///
490     /// ```
491     /// use std::collections::LinkedList;
492     ///
493     /// let mut dl = LinkedList::new();
494     /// assert_eq!(dl.front(), None);
495     ///
496     /// dl.push_front(1);
497     /// assert_eq!(dl.front(), Some(&1));
498     ///
499     /// match dl.front_mut() {
500     ///     None => {},
501     ///     Some(x) => *x = 5,
502     /// }
503     /// assert_eq!(dl.front(), Some(&5));
504     /// ```
505     #[inline]
506     #[stable(feature = "rust1", since = "1.0.0")]
507     pub fn front_mut(&mut self) -> Option<&mut T> {
508         unsafe {
509             self.head.as_mut().map(|node| &mut node.as_mut().element)
510         }
511     }
512
513     /// Provides a reference to the back element, or `None` if the list is
514     /// empty.
515     ///
516     /// # Examples
517     ///
518     /// ```
519     /// use std::collections::LinkedList;
520     ///
521     /// let mut dl = LinkedList::new();
522     /// assert_eq!(dl.back(), None);
523     ///
524     /// dl.push_back(1);
525     /// assert_eq!(dl.back(), Some(&1));
526     /// ```
527     #[inline]
528     #[stable(feature = "rust1", since = "1.0.0")]
529     pub fn back(&self) -> Option<&T> {
530         unsafe {
531             self.tail.as_ref().map(|node| &node.as_ref().element)
532         }
533     }
534
535     /// Provides a mutable reference to the back element, or `None` if the list
536     /// is empty.
537     ///
538     /// # Examples
539     ///
540     /// ```
541     /// use std::collections::LinkedList;
542     ///
543     /// let mut dl = LinkedList::new();
544     /// assert_eq!(dl.back(), None);
545     ///
546     /// dl.push_back(1);
547     /// assert_eq!(dl.back(), Some(&1));
548     ///
549     /// match dl.back_mut() {
550     ///     None => {},
551     ///     Some(x) => *x = 5,
552     /// }
553     /// assert_eq!(dl.back(), Some(&5));
554     /// ```
555     #[inline]
556     #[stable(feature = "rust1", since = "1.0.0")]
557     pub fn back_mut(&mut self) -> Option<&mut T> {
558         unsafe {
559             self.tail.as_mut().map(|node| &mut node.as_mut().element)
560         }
561     }
562
563     /// Adds an element first in the list.
564     ///
565     /// This operation should compute in O(1) time.
566     ///
567     /// # Examples
568     ///
569     /// ```
570     /// use std::collections::LinkedList;
571     ///
572     /// let mut dl = LinkedList::new();
573     ///
574     /// dl.push_front(2);
575     /// assert_eq!(dl.front().unwrap(), &2);
576     ///
577     /// dl.push_front(1);
578     /// assert_eq!(dl.front().unwrap(), &1);
579     /// ```
580     #[stable(feature = "rust1", since = "1.0.0")]
581     pub fn push_front(&mut self, elt: T) {
582         self.push_front_node(box Node::new(elt));
583     }
584
585     /// Removes the first element and returns it, or `None` if the list is
586     /// empty.
587     ///
588     /// This operation should compute in O(1) time.
589     ///
590     /// # Examples
591     ///
592     /// ```
593     /// use std::collections::LinkedList;
594     ///
595     /// let mut d = LinkedList::new();
596     /// assert_eq!(d.pop_front(), None);
597     ///
598     /// d.push_front(1);
599     /// d.push_front(3);
600     /// assert_eq!(d.pop_front(), Some(3));
601     /// assert_eq!(d.pop_front(), Some(1));
602     /// assert_eq!(d.pop_front(), None);
603     /// ```
604     #[stable(feature = "rust1", since = "1.0.0")]
605     pub fn pop_front(&mut self) -> Option<T> {
606         self.pop_front_node().map(Node::into_element)
607     }
608
609     /// Appends an element to the back of a list
610     ///
611     /// # Examples
612     ///
613     /// ```
614     /// use std::collections::LinkedList;
615     ///
616     /// let mut d = LinkedList::new();
617     /// d.push_back(1);
618     /// d.push_back(3);
619     /// assert_eq!(3, *d.back().unwrap());
620     /// ```
621     #[stable(feature = "rust1", since = "1.0.0")]
622     pub fn push_back(&mut self, elt: T) {
623         self.push_back_node(box Node::new(elt));
624     }
625
626     /// Removes the last element from a list and returns it, or `None` if
627     /// it is empty.
628     ///
629     /// # Examples
630     ///
631     /// ```
632     /// use std::collections::LinkedList;
633     ///
634     /// let mut d = LinkedList::new();
635     /// assert_eq!(d.pop_back(), None);
636     /// d.push_back(1);
637     /// d.push_back(3);
638     /// assert_eq!(d.pop_back(), Some(3));
639     /// ```
640     #[stable(feature = "rust1", since = "1.0.0")]
641     pub fn pop_back(&mut self) -> Option<T> {
642         self.pop_back_node().map(Node::into_element)
643     }
644
645     /// Splits the list into two at the given index. Returns everything after the given index,
646     /// including the index.
647     ///
648     /// This operation should compute in O(n) time.
649     ///
650     /// # Panics
651     ///
652     /// Panics if `at > len`.
653     ///
654     /// # Examples
655     ///
656     /// ```
657     /// use std::collections::LinkedList;
658     ///
659     /// let mut d = LinkedList::new();
660     ///
661     /// d.push_front(1);
662     /// d.push_front(2);
663     /// d.push_front(3);
664     ///
665     /// let mut splitted = d.split_off(2);
666     ///
667     /// assert_eq!(splitted.pop_front(), Some(1));
668     /// assert_eq!(splitted.pop_front(), None);
669     /// ```
670     #[stable(feature = "rust1", since = "1.0.0")]
671     pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
672         let len = self.len();
673         assert!(at <= len, "Cannot split off at a nonexistent index");
674         if at == 0 {
675             return mem::replace(self, Self::new());
676         } else if at == len {
677             return Self::new();
678         }
679
680         // Below, we iterate towards the `i-1`th node, either from the start or the end,
681         // depending on which would be faster.
682         let split_node = if at - 1 <= len - 1 - (at - 1) {
683             let mut iter = self.iter_mut();
684             // instead of skipping using .skip() (which creates a new struct),
685             // we skip manually so we can access the head field without
686             // depending on implementation details of Skip
687             for _ in 0..at - 1 {
688                 iter.next();
689             }
690             iter.head
691         } else {
692             // better off starting from the end
693             let mut iter = self.iter_mut();
694             for _ in 0..len - 1 - (at - 1) {
695                 iter.next_back();
696             }
697             iter.tail
698         };
699
700         // The split node is the new tail node of the first part and owns
701         // the head of the second part.
702         let second_part_head;
703
704         unsafe {
705             second_part_head = split_node.unwrap().as_mut().next.take();
706             if let Some(mut head) = second_part_head {
707                 head.as_mut().prev = None;
708             }
709         }
710
711         let second_part = LinkedList {
712             head: second_part_head,
713             tail: self.tail,
714             len: len - at,
715             marker: PhantomData,
716         };
717
718         // Fix the tail ptr of the first part
719         self.tail = split_node;
720         self.len = at;
721
722         second_part
723     }
724
725     /// Returns a place for insertion at the front of the list.
726     ///
727     /// Using this method with placement syntax is equivalent to
728     /// [`push_front`](#method.push_front), but may be more efficient.
729     ///
730     /// # Examples
731     ///
732     /// ```
733     /// #![feature(collection_placement)]
734     /// #![feature(placement_in_syntax)]
735     ///
736     /// use std::collections::LinkedList;
737     ///
738     /// let mut list = LinkedList::new();
739     /// list.front_place() <- 2;
740     /// list.front_place() <- 4;
741     /// assert!(list.iter().eq(&[4, 2]));
742     /// ```
743     #[unstable(feature = "collection_placement",
744                reason = "method name and placement protocol are subject to change",
745                issue = "30172")]
746     pub fn front_place(&mut self) -> FrontPlace<T> {
747         FrontPlace {
748             list: self,
749             node: IntermediateBox::make_place(),
750         }
751     }
752
753     /// Returns a place for insertion at the back of the list.
754     ///
755     /// Using this method with placement syntax is equivalent to [`push_back`](#method.push_back),
756     /// but may be more efficient.
757     ///
758     /// # Examples
759     ///
760     /// ```
761     /// #![feature(collection_placement)]
762     /// #![feature(placement_in_syntax)]
763     ///
764     /// use std::collections::LinkedList;
765     ///
766     /// let mut list = LinkedList::new();
767     /// list.back_place() <- 2;
768     /// list.back_place() <- 4;
769     /// assert!(list.iter().eq(&[2, 4]));
770     /// ```
771     #[unstable(feature = "collection_placement",
772                reason = "method name and placement protocol are subject to change",
773                issue = "30172")]
774     pub fn back_place(&mut self) -> BackPlace<T> {
775         BackPlace {
776             list: self,
777             node: IntermediateBox::make_place(),
778         }
779     }
780 }
781
782 #[stable(feature = "rust1", since = "1.0.0")]
783 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
784     fn drop(&mut self) {
785         while let Some(_) = self.pop_front_node() {}
786     }
787 }
788
789 #[stable(feature = "rust1", since = "1.0.0")]
790 impl<'a, T> Iterator for Iter<'a, T> {
791     type Item = &'a T;
792
793     #[inline]
794     fn next(&mut self) -> Option<&'a T> {
795         if self.len == 0 {
796             None
797         } else {
798             self.head.map(|node| unsafe {
799                 // Need an unbound lifetime to get 'a
800                 let node = &*node.as_ptr();
801                 self.len -= 1;
802                 self.head = node.next;
803                 &node.element
804             })
805         }
806     }
807
808     #[inline]
809     fn size_hint(&self) -> (usize, Option<usize>) {
810         (self.len, Some(self.len))
811     }
812 }
813
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
816     #[inline]
817     fn next_back(&mut self) -> Option<&'a T> {
818         if self.len == 0 {
819             None
820         } else {
821             self.tail.map(|node| unsafe {
822                 // Need an unbound lifetime to get 'a
823                 let node = &*node.as_ptr();
824                 self.len -= 1;
825                 self.tail = node.prev;
826                 &node.element
827             })
828         }
829     }
830 }
831
832 #[stable(feature = "rust1", since = "1.0.0")]
833 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
834
835 #[unstable(feature = "fused", issue = "35602")]
836 impl<'a, T> FusedIterator for Iter<'a, T> {}
837
838 #[stable(feature = "rust1", since = "1.0.0")]
839 impl<'a, T> Iterator for IterMut<'a, T> {
840     type Item = &'a mut T;
841
842     #[inline]
843     fn next(&mut self) -> Option<&'a mut T> {
844         if self.len == 0 {
845             None
846         } else {
847             self.head.map(|node| unsafe {
848                 // Need an unbound lifetime to get 'a
849                 let node = &mut *node.as_ptr();
850                 self.len -= 1;
851                 self.head = node.next;
852                 &mut node.element
853             })
854         }
855     }
856
857     #[inline]
858     fn size_hint(&self) -> (usize, Option<usize>) {
859         (self.len, Some(self.len))
860     }
861 }
862
863 #[stable(feature = "rust1", since = "1.0.0")]
864 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
865     #[inline]
866     fn next_back(&mut self) -> Option<&'a mut T> {
867         if self.len == 0 {
868             None
869         } else {
870             self.tail.map(|node| unsafe {
871                 // Need an unbound lifetime to get 'a
872                 let node = &mut *node.as_ptr();
873                 self.len -= 1;
874                 self.tail = node.prev;
875                 &mut node.element
876             })
877         }
878     }
879 }
880
881 #[stable(feature = "rust1", since = "1.0.0")]
882 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
883
884 #[unstable(feature = "fused", issue = "35602")]
885 impl<'a, T> FusedIterator for IterMut<'a, T> {}
886
887 impl<'a, T> IterMut<'a, T> {
888     /// Inserts the given element just after the element most recently returned by `.next()`.
889     /// The inserted element does not appear in the iteration.
890     ///
891     /// # Examples
892     ///
893     /// ```
894     /// #![feature(linked_list_extras)]
895     ///
896     /// use std::collections::LinkedList;
897     ///
898     /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
899     ///
900     /// {
901     ///     let mut it = list.iter_mut();
902     ///     assert_eq!(it.next().unwrap(), &1);
903     ///     // insert `2` after `1`
904     ///     it.insert_next(2);
905     /// }
906     /// {
907     ///     let vec: Vec<_> = list.into_iter().collect();
908     ///     assert_eq!(vec, [1, 2, 3, 4]);
909     /// }
910     /// ```
911     #[inline]
912     #[unstable(feature = "linked_list_extras",
913                reason = "this is probably better handled by a cursor type -- we'll see",
914                issue = "27794")]
915     pub fn insert_next(&mut self, element: T) {
916         match self.head {
917             None => self.list.push_back(element),
918             Some(mut head) => unsafe {
919                 let mut prev = match head.as_ref().prev {
920                     None => return self.list.push_front(element),
921                     Some(prev) => prev,
922                 };
923
924                 let node = Some(Shared::from(Box::into_unique(box Node {
925                     next: Some(head),
926                     prev: Some(prev),
927                     element,
928                 })));
929
930                 prev.as_mut().next = node;
931                 head.as_mut().prev = node;
932
933                 self.list.len += 1;
934             },
935         }
936     }
937
938     /// Provides a reference to the next element, without changing the iterator.
939     ///
940     /// # Examples
941     ///
942     /// ```
943     /// #![feature(linked_list_extras)]
944     ///
945     /// use std::collections::LinkedList;
946     ///
947     /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
948     ///
949     /// let mut it = list.iter_mut();
950     /// assert_eq!(it.next().unwrap(), &1);
951     /// assert_eq!(it.peek_next().unwrap(), &2);
952     /// // We just peeked at 2, so it was not consumed from the iterator.
953     /// assert_eq!(it.next().unwrap(), &2);
954     /// ```
955     #[inline]
956     #[unstable(feature = "linked_list_extras",
957                reason = "this is probably better handled by a cursor type -- we'll see",
958                issue = "27794")]
959     pub fn peek_next(&mut self) -> Option<&mut T> {
960         if self.len == 0 {
961             None
962         } else {
963             unsafe {
964                 self.head.as_mut().map(|node| &mut node.as_mut().element)
965             }
966         }
967     }
968 }
969
970 #[stable(feature = "rust1", since = "1.0.0")]
971 impl<T> Iterator for IntoIter<T> {
972     type Item = T;
973
974     #[inline]
975     fn next(&mut self) -> Option<T> {
976         self.list.pop_front()
977     }
978
979     #[inline]
980     fn size_hint(&self) -> (usize, Option<usize>) {
981         (self.list.len, Some(self.list.len))
982     }
983 }
984
985 #[stable(feature = "rust1", since = "1.0.0")]
986 impl<T> DoubleEndedIterator for IntoIter<T> {
987     #[inline]
988     fn next_back(&mut self) -> Option<T> {
989         self.list.pop_back()
990     }
991 }
992
993 #[stable(feature = "rust1", since = "1.0.0")]
994 impl<T> ExactSizeIterator for IntoIter<T> {}
995
996 #[unstable(feature = "fused", issue = "35602")]
997 impl<T> FusedIterator for IntoIter<T> {}
998
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 impl<T> FromIterator<T> for LinkedList<T> {
1001     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1002         let mut list = Self::new();
1003         list.extend(iter);
1004         list
1005     }
1006 }
1007
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 impl<T> IntoIterator for LinkedList<T> {
1010     type Item = T;
1011     type IntoIter = IntoIter<T>;
1012
1013     /// Consumes the list into an iterator yielding elements by value.
1014     #[inline]
1015     fn into_iter(self) -> IntoIter<T> {
1016         IntoIter { list: self }
1017     }
1018 }
1019
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<'a, T> IntoIterator for &'a LinkedList<T> {
1022     type Item = &'a T;
1023     type IntoIter = Iter<'a, T>;
1024
1025     fn into_iter(self) -> Iter<'a, T> {
1026         self.iter()
1027     }
1028 }
1029
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
1032     type Item = &'a mut T;
1033     type IntoIter = IterMut<'a, T>;
1034
1035     fn into_iter(self) -> IterMut<'a, T> {
1036         self.iter_mut()
1037     }
1038 }
1039
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 impl<T> Extend<T> for LinkedList<T> {
1042     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1043         <Self as SpecExtend<I>>::spec_extend(self, iter);
1044     }
1045 }
1046
1047 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1048     default fn spec_extend(&mut self, iter: I) {
1049         for elt in iter {
1050             self.push_back(elt);
1051         }
1052     }
1053 }
1054
1055 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1056     fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1057         self.append(other);
1058     }
1059 }
1060
1061 #[stable(feature = "extend_ref", since = "1.2.0")]
1062 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1063     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1064         self.extend(iter.into_iter().cloned());
1065     }
1066 }
1067
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 impl<T: PartialEq> PartialEq for LinkedList<T> {
1070     fn eq(&self, other: &Self) -> bool {
1071         self.len() == other.len() && self.iter().eq(other)
1072     }
1073
1074     fn ne(&self, other: &Self) -> bool {
1075         self.len() != other.len() || self.iter().ne(other)
1076     }
1077 }
1078
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 impl<T: Eq> Eq for LinkedList<T> {}
1081
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1084     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1085         self.iter().partial_cmp(other)
1086     }
1087 }
1088
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 impl<T: Ord> Ord for LinkedList<T> {
1091     #[inline]
1092     fn cmp(&self, other: &Self) -> Ordering {
1093         self.iter().cmp(other)
1094     }
1095 }
1096
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 impl<T: Clone> Clone for LinkedList<T> {
1099     fn clone(&self) -> Self {
1100         self.iter().cloned().collect()
1101     }
1102 }
1103
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1106     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1107         f.debug_list().entries(self).finish()
1108     }
1109 }
1110
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 impl<T: Hash> Hash for LinkedList<T> {
1113     fn hash<H: Hasher>(&self, state: &mut H) {
1114         self.len().hash(state);
1115         for elt in self {
1116             elt.hash(state);
1117         }
1118     }
1119 }
1120
1121 unsafe fn finalize<T>(node: IntermediateBox<Node<T>>) -> Box<Node<T>> {
1122     let mut node = node.finalize();
1123     ptr::write(&mut node.next, None);
1124     ptr::write(&mut node.prev, None);
1125     node
1126 }
1127
1128 /// A place for insertion at the front of a `LinkedList`.
1129 ///
1130 /// See [`LinkedList::front_place`](struct.LinkedList.html#method.front_place) for details.
1131 #[must_use = "places do nothing unless written to with `<-` syntax"]
1132 #[unstable(feature = "collection_placement",
1133            reason = "struct name and placement protocol are subject to change",
1134            issue = "30172")]
1135 pub struct FrontPlace<'a, T: 'a> {
1136     list: &'a mut LinkedList<T>,
1137     node: IntermediateBox<Node<T>>,
1138 }
1139
1140 #[unstable(feature = "collection_placement",
1141            reason = "struct name and placement protocol are subject to change",
1142            issue = "30172")]
1143 impl<'a, T: 'a + fmt::Debug> fmt::Debug for FrontPlace<'a, T> {
1144     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1145         f.debug_tuple("FrontPlace")
1146          .field(&self.list)
1147          .finish()
1148     }
1149 }
1150
1151 #[unstable(feature = "collection_placement",
1152            reason = "placement protocol is subject to change",
1153            issue = "30172")]
1154 impl<'a, T> Placer<T> for FrontPlace<'a, T> {
1155     type Place = Self;
1156
1157     fn make_place(self) -> Self {
1158         self
1159     }
1160 }
1161
1162 #[unstable(feature = "collection_placement",
1163            reason = "placement protocol is subject to change",
1164            issue = "30172")]
1165 impl<'a, T> Place<T> for FrontPlace<'a, T> {
1166     fn pointer(&mut self) -> *mut T {
1167         unsafe { &mut (*self.node.pointer()).element }
1168     }
1169 }
1170
1171 #[unstable(feature = "collection_placement",
1172            reason = "placement protocol is subject to change",
1173            issue = "30172")]
1174 impl<'a, T> InPlace<T> for FrontPlace<'a, T> {
1175     type Owner = ();
1176
1177     unsafe fn finalize(self) {
1178         let FrontPlace { list, node } = self;
1179         list.push_front_node(finalize(node));
1180     }
1181 }
1182
1183 /// A place for insertion at the back of a `LinkedList`.
1184 ///
1185 /// See [`LinkedList::back_place`](struct.LinkedList.html#method.back_place) for details.
1186 #[must_use = "places do nothing unless written to with `<-` syntax"]
1187 #[unstable(feature = "collection_placement",
1188            reason = "struct name and placement protocol are subject to change",
1189            issue = "30172")]
1190 pub struct BackPlace<'a, T: 'a> {
1191     list: &'a mut LinkedList<T>,
1192     node: IntermediateBox<Node<T>>,
1193 }
1194
1195 #[unstable(feature = "collection_placement",
1196            reason = "struct name and placement protocol are subject to change",
1197            issue = "30172")]
1198 impl<'a, T: 'a + fmt::Debug> fmt::Debug for BackPlace<'a, T> {
1199     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1200         f.debug_tuple("BackPlace")
1201          .field(&self.list)
1202          .finish()
1203     }
1204 }
1205
1206 #[unstable(feature = "collection_placement",
1207            reason = "placement protocol is subject to change",
1208            issue = "30172")]
1209 impl<'a, T> Placer<T> for BackPlace<'a, T> {
1210     type Place = Self;
1211
1212     fn make_place(self) -> Self {
1213         self
1214     }
1215 }
1216
1217 #[unstable(feature = "collection_placement",
1218            reason = "placement protocol is subject to change",
1219            issue = "30172")]
1220 impl<'a, T> Place<T> for BackPlace<'a, T> {
1221     fn pointer(&mut self) -> *mut T {
1222         unsafe { &mut (*self.node.pointer()).element }
1223     }
1224 }
1225
1226 #[unstable(feature = "collection_placement",
1227            reason = "placement protocol is subject to change",
1228            issue = "30172")]
1229 impl<'a, T> InPlace<T> for BackPlace<'a, T> {
1230     type Owner = ();
1231
1232     unsafe fn finalize(self) {
1233         let BackPlace { list, node } = self;
1234         list.push_back_node(finalize(node));
1235     }
1236 }
1237
1238 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1239 #[allow(dead_code)]
1240 fn assert_covariance() {
1241     fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1242         x
1243     }
1244     fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1245         x
1246     }
1247     fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1248         x
1249     }
1250 }
1251
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 unsafe impl<T: Send> Send for LinkedList<T> {}
1254
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1257
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1260
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1263
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1266
1267 #[stable(feature = "rust1", since = "1.0.0")]
1268 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1269
1270 #[cfg(test)]
1271 mod tests {
1272     use std::__rand::{thread_rng, Rng};
1273     use std::thread;
1274     use std::vec::Vec;
1275
1276     use super::{LinkedList, Node};
1277
1278     #[cfg(test)]
1279     fn list_from<T: Clone>(v: &[T]) -> LinkedList<T> {
1280         v.iter().cloned().collect()
1281     }
1282
1283     pub fn check_links<T>(list: &LinkedList<T>) {
1284         unsafe {
1285             let mut len = 0;
1286             let mut last_ptr: Option<&Node<T>> = None;
1287             let mut node_ptr: &Node<T>;
1288             match list.head {
1289                 None => {
1290                     assert_eq!(0, list.len);
1291                     return;
1292                 }
1293                 Some(node) => node_ptr = &*node.as_ptr(),
1294             }
1295             loop {
1296                 match (last_ptr, node_ptr.prev) {
1297                     (None, None) => {}
1298                     (None, _) => panic!("prev link for head"),
1299                     (Some(p), Some(pptr)) => {
1300                         assert_eq!(p as *const Node<T>, pptr.as_ptr() as *const Node<T>);
1301                     }
1302                     _ => panic!("prev link is none, not good"),
1303                 }
1304                 match node_ptr.next {
1305                     Some(next) => {
1306                         last_ptr = Some(node_ptr);
1307                         node_ptr = &*next.as_ptr();
1308                         len += 1;
1309                     }
1310                     None => {
1311                         len += 1;
1312                         break;
1313                     }
1314                 }
1315             }
1316             assert_eq!(len, list.len);
1317         }
1318     }
1319
1320     #[test]
1321     fn test_append() {
1322         // Empty to empty
1323         {
1324             let mut m = LinkedList::<i32>::new();
1325             let mut n = LinkedList::new();
1326             m.append(&mut n);
1327             check_links(&m);
1328             assert_eq!(m.len(), 0);
1329             assert_eq!(n.len(), 0);
1330         }
1331         // Non-empty to empty
1332         {
1333             let mut m = LinkedList::new();
1334             let mut n = LinkedList::new();
1335             n.push_back(2);
1336             m.append(&mut n);
1337             check_links(&m);
1338             assert_eq!(m.len(), 1);
1339             assert_eq!(m.pop_back(), Some(2));
1340             assert_eq!(n.len(), 0);
1341             check_links(&m);
1342         }
1343         // Empty to non-empty
1344         {
1345             let mut m = LinkedList::new();
1346             let mut n = LinkedList::new();
1347             m.push_back(2);
1348             m.append(&mut n);
1349             check_links(&m);
1350             assert_eq!(m.len(), 1);
1351             assert_eq!(m.pop_back(), Some(2));
1352             check_links(&m);
1353         }
1354
1355         // Non-empty to non-empty
1356         let v = vec![1, 2, 3, 4, 5];
1357         let u = vec![9, 8, 1, 2, 3, 4, 5];
1358         let mut m = list_from(&v);
1359         let mut n = list_from(&u);
1360         m.append(&mut n);
1361         check_links(&m);
1362         let mut sum = v;
1363         sum.extend_from_slice(&u);
1364         assert_eq!(sum.len(), m.len());
1365         for elt in sum {
1366             assert_eq!(m.pop_front(), Some(elt))
1367         }
1368         assert_eq!(n.len(), 0);
1369         // let's make sure it's working properly, since we
1370         // did some direct changes to private members
1371         n.push_back(3);
1372         assert_eq!(n.len(), 1);
1373         assert_eq!(n.pop_front(), Some(3));
1374         check_links(&n);
1375     }
1376
1377     #[test]
1378     fn test_insert_prev() {
1379         let mut m = list_from(&[0, 2, 4, 6, 8]);
1380         let len = m.len();
1381         {
1382             let mut it = m.iter_mut();
1383             it.insert_next(-2);
1384             loop {
1385                 match it.next() {
1386                     None => break,
1387                     Some(elt) => {
1388                         it.insert_next(*elt + 1);
1389                         match it.peek_next() {
1390                             Some(x) => assert_eq!(*x, *elt + 2),
1391                             None => assert_eq!(8, *elt),
1392                         }
1393                     }
1394                 }
1395             }
1396             it.insert_next(0);
1397             it.insert_next(1);
1398         }
1399         check_links(&m);
1400         assert_eq!(m.len(), 3 + len * 2);
1401         assert_eq!(m.into_iter().collect::<Vec<_>>(),
1402                    [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]);
1403     }
1404
1405     #[test]
1406     #[cfg_attr(target_os = "emscripten", ignore)]
1407     fn test_send() {
1408         let n = list_from(&[1, 2, 3]);
1409         thread::spawn(move || {
1410                 check_links(&n);
1411                 let a: &[_] = &[&1, &2, &3];
1412                 assert_eq!(a, &*n.iter().collect::<Vec<_>>());
1413             })
1414             .join()
1415             .ok()
1416             .unwrap();
1417     }
1418
1419     #[test]
1420     fn test_fuzz() {
1421         for _ in 0..25 {
1422             fuzz_test(3);
1423             fuzz_test(16);
1424             fuzz_test(189);
1425         }
1426     }
1427
1428     #[test]
1429     fn test_26021() {
1430         // There was a bug in split_off that failed to null out the RHS's head's prev ptr.
1431         // This caused the RHS's dtor to walk up into the LHS at drop and delete all of
1432         // its nodes.
1433         //
1434         // https://github.com/rust-lang/rust/issues/26021
1435         let mut v1 = LinkedList::new();
1436         v1.push_front(1);
1437         v1.push_front(1);
1438         v1.push_front(1);
1439         v1.push_front(1);
1440         let _ = v1.split_off(3); // Dropping this now should not cause laundry consumption
1441         assert_eq!(v1.len(), 3);
1442
1443         assert_eq!(v1.iter().len(), 3);
1444         assert_eq!(v1.iter().collect::<Vec<_>>().len(), 3);
1445     }
1446
1447     #[test]
1448     fn test_split_off() {
1449         let mut v1 = LinkedList::new();
1450         v1.push_front(1);
1451         v1.push_front(1);
1452         v1.push_front(1);
1453         v1.push_front(1);
1454
1455         // test all splits
1456         for ix in 0..1 + v1.len() {
1457             let mut a = v1.clone();
1458             let b = a.split_off(ix);
1459             check_links(&a);
1460             check_links(&b);
1461             a.extend(b);
1462             assert_eq!(v1, a);
1463         }
1464     }
1465
1466     #[cfg(test)]
1467     fn fuzz_test(sz: i32) {
1468         let mut m: LinkedList<_> = LinkedList::new();
1469         let mut v = vec![];
1470         for i in 0..sz {
1471             check_links(&m);
1472             let r: u8 = thread_rng().next_u32() as u8;
1473             match r % 6 {
1474                 0 => {
1475                     m.pop_back();
1476                     v.pop();
1477                 }
1478                 1 => {
1479                     if !v.is_empty() {
1480                         m.pop_front();
1481                         v.remove(0);
1482                     }
1483                 }
1484                 2 | 4 => {
1485                     m.push_front(-i);
1486                     v.insert(0, -i);
1487                 }
1488                 3 | 5 | _ => {
1489                     m.push_back(i);
1490                     v.push(i);
1491                 }
1492             }
1493         }
1494
1495         check_links(&m);
1496
1497         let mut i = 0;
1498         for (a, &b) in m.into_iter().zip(&v) {
1499             i += 1;
1500             assert_eq!(a, b);
1501         }
1502         assert_eq!(i, v.len());
1503     }
1504 }