]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice/mod.rs
Remove deprecated unstable attribute `#[simd]`
[rust.git] / src / libcore / slice / mod.rs
1 // Copyright 2012-2017 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 //! Slice management and manipulation
12 //!
13 //! For more details see [`std::slice`].
14 //!
15 //! [`std::slice`]: ../../std/slice/index.html
16
17 #![stable(feature = "rust1", since = "1.0.0")]
18
19 // How this module is organized.
20 //
21 // The library infrastructure for slices is fairly messy. There's
22 // a lot of stuff defined here. Let's keep it clean.
23 //
24 // Since slices don't support inherent methods; all operations
25 // on them are defined on traits, which are then reexported from
26 // the prelude for convenience. So there are a lot of traits here.
27 //
28 // The layout of this file is thus:
29 //
30 // * Slice-specific 'extension' traits and their implementations. This
31 //   is where most of the slice API resides.
32 // * Implementations of a few common traits with important slice ops.
33 // * Definitions of a bunch of iterators.
34 // * Free functions.
35 // * The `raw` and `bytes` submodules.
36 // * Boilerplate trait implementations.
37
38 use cmp::Ordering::{self, Less, Equal, Greater};
39 use cmp;
40 use fmt;
41 use intrinsics::assume;
42 use iter::*;
43 use ops::{FnMut, Try, self};
44 use option::Option;
45 use option::Option::{None, Some};
46 use result::Result;
47 use result::Result::{Ok, Err};
48 use ptr;
49 use mem;
50 use marker::{Copy, Send, Sync, Sized, self};
51 use iter_private::TrustedRandomAccess;
52
53 #[unstable(feature = "slice_internals", issue = "0",
54            reason = "exposed from core to be reused in std; use the memchr crate")]
55 /// Pure rust memchr implementation, taken from rust-memchr
56 pub mod memchr;
57
58 mod rotate;
59 mod sort;
60
61 #[repr(C)]
62 struct Repr<T> {
63     pub data: *const T,
64     pub len: usize,
65 }
66
67 //
68 // Extension traits
69 //
70
71 /// Extension methods for slices.
72 #[unstable(feature = "core_slice_ext",
73            reason = "stable interface provided by `impl [T]` in later crates",
74            issue = "32110")]
75 #[allow(missing_docs)] // documented elsewhere
76 pub trait SliceExt {
77     type Item;
78
79     #[stable(feature = "core", since = "1.6.0")]
80     fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
81
82     #[stable(feature = "core", since = "1.6.0")]
83     fn iter(&self) -> Iter<Self::Item>;
84
85     #[stable(feature = "core", since = "1.6.0")]
86     fn split<P>(&self, pred: P) -> Split<Self::Item, P>
87         where P: FnMut(&Self::Item) -> bool;
88
89     #[unstable(feature = "slice_rsplit", issue = "41020")]
90     fn rsplit<P>(&self, pred: P) -> RSplit<Self::Item, P>
91         where P: FnMut(&Self::Item) -> bool;
92
93     #[stable(feature = "core", since = "1.6.0")]
94     fn splitn<P>(&self, n: usize, pred: P) -> SplitN<Self::Item, P>
95         where P: FnMut(&Self::Item) -> bool;
96
97     #[stable(feature = "core", since = "1.6.0")]
98     fn rsplitn<P>(&self,  n: usize, pred: P) -> RSplitN<Self::Item, P>
99         where P: FnMut(&Self::Item) -> bool;
100
101     #[stable(feature = "core", since = "1.6.0")]
102     fn windows(&self, size: usize) -> Windows<Self::Item>;
103
104     #[stable(feature = "core", since = "1.6.0")]
105     fn chunks(&self, size: usize) -> Chunks<Self::Item>;
106
107     #[stable(feature = "core", since = "1.6.0")]
108     fn get<I>(&self, index: I) -> Option<&I::Output>
109         where I: SliceIndex<Self>;
110     #[stable(feature = "core", since = "1.6.0")]
111     fn first(&self) -> Option<&Self::Item>;
112
113     #[stable(feature = "core", since = "1.6.0")]
114     fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>;
115
116     #[stable(feature = "core", since = "1.6.0")]
117     fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>;
118
119     #[stable(feature = "core", since = "1.6.0")]
120     fn last(&self) -> Option<&Self::Item>;
121
122     #[stable(feature = "core", since = "1.6.0")]
123     unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
124         where I: SliceIndex<Self>;
125     #[stable(feature = "core", since = "1.6.0")]
126     fn as_ptr(&self) -> *const Self::Item;
127
128     #[stable(feature = "core", since = "1.6.0")]
129     fn binary_search(&self, x: &Self::Item) -> Result<usize, usize>
130         where Self::Item: Ord;
131
132     #[stable(feature = "core", since = "1.6.0")]
133     fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
134         where F: FnMut(&'a Self::Item) -> Ordering;
135
136     #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
137     fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
138         where F: FnMut(&'a Self::Item) -> B,
139               B: Ord;
140
141     #[stable(feature = "core", since = "1.6.0")]
142     fn len(&self) -> usize;
143
144     #[stable(feature = "core", since = "1.6.0")]
145     fn is_empty(&self) -> bool { self.len() == 0 }
146
147     #[stable(feature = "core", since = "1.6.0")]
148     fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
149         where I: SliceIndex<Self>;
150     #[stable(feature = "core", since = "1.6.0")]
151     fn iter_mut(&mut self) -> IterMut<Self::Item>;
152
153     #[stable(feature = "core", since = "1.6.0")]
154     fn first_mut(&mut self) -> Option<&mut Self::Item>;
155
156     #[stable(feature = "core", since = "1.6.0")]
157     fn split_first_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
158
159     #[stable(feature = "core", since = "1.6.0")]
160     fn split_last_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
161
162     #[stable(feature = "core", since = "1.6.0")]
163     fn last_mut(&mut self) -> Option<&mut Self::Item>;
164
165     #[stable(feature = "core", since = "1.6.0")]
166     fn split_mut<P>(&mut self, pred: P) -> SplitMut<Self::Item, P>
167         where P: FnMut(&Self::Item) -> bool;
168
169     #[unstable(feature = "slice_rsplit", issue = "41020")]
170     fn rsplit_mut<P>(&mut self, pred: P) -> RSplitMut<Self::Item, P>
171         where P: FnMut(&Self::Item) -> bool;
172
173     #[stable(feature = "core", since = "1.6.0")]
174     fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
175         where P: FnMut(&Self::Item) -> bool;
176
177     #[stable(feature = "core", since = "1.6.0")]
178     fn rsplitn_mut<P>(&mut self,  n: usize, pred: P) -> RSplitNMut<Self::Item, P>
179         where P: FnMut(&Self::Item) -> bool;
180
181     #[stable(feature = "core", since = "1.6.0")]
182     fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
183
184     #[stable(feature = "core", since = "1.6.0")]
185     fn swap(&mut self, a: usize, b: usize);
186
187     #[stable(feature = "core", since = "1.6.0")]
188     fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
189
190     #[stable(feature = "core", since = "1.6.0")]
191     fn reverse(&mut self);
192
193     #[stable(feature = "core", since = "1.6.0")]
194     unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
195         where I: SliceIndex<Self>;
196     #[stable(feature = "core", since = "1.6.0")]
197     fn as_mut_ptr(&mut self) -> *mut Self::Item;
198
199     #[stable(feature = "core", since = "1.6.0")]
200     fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
201
202     #[stable(feature = "core", since = "1.6.0")]
203     fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
204
205     #[stable(feature = "core", since = "1.6.0")]
206     fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
207
208     #[unstable(feature = "slice_rotate", issue = "41891")]
209     fn rotate(&mut self, mid: usize);
210
211     #[stable(feature = "clone_from_slice", since = "1.7.0")]
212     fn clone_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Clone;
213
214     #[stable(feature = "copy_from_slice", since = "1.9.0")]
215     fn copy_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Copy;
216
217     #[unstable(feature = "swap_with_slice", issue = "44030")]
218     fn swap_with_slice(&mut self, src: &mut [Self::Item]);
219
220     #[stable(feature = "sort_unstable", since = "1.20.0")]
221     fn sort_unstable(&mut self)
222         where Self::Item: Ord;
223
224     #[stable(feature = "sort_unstable", since = "1.20.0")]
225     fn sort_unstable_by<F>(&mut self, compare: F)
226         where F: FnMut(&Self::Item, &Self::Item) -> Ordering;
227
228     #[stable(feature = "sort_unstable", since = "1.20.0")]
229     fn sort_unstable_by_key<B, F>(&mut self, f: F)
230         where F: FnMut(&Self::Item) -> B,
231               B: Ord;
232 }
233
234 // Use macros to be generic over const/mut
235 macro_rules! slice_offset {
236     ($ptr:expr, $by:expr) => {{
237         let ptr = $ptr;
238         if size_from_ptr(ptr) == 0 {
239             (ptr as *mut i8).wrapping_offset($by) as _
240         } else {
241             ptr.offset($by)
242         }
243     }};
244 }
245
246 // make a &T from a *const T
247 macro_rules! make_ref {
248     ($ptr:expr) => {{
249         let ptr = $ptr;
250         if size_from_ptr(ptr) == 0 {
251             // Use a non-null pointer value
252             &*(1 as *mut _)
253         } else {
254             &*ptr
255         }
256     }};
257 }
258
259 // make a &mut T from a *mut T
260 macro_rules! make_ref_mut {
261     ($ptr:expr) => {{
262         let ptr = $ptr;
263         if size_from_ptr(ptr) == 0 {
264             // Use a non-null pointer value
265             &mut *(1 as *mut _)
266         } else {
267             &mut *ptr
268         }
269     }};
270 }
271
272 #[unstable(feature = "core_slice_ext",
273            reason = "stable interface provided by `impl [T]` in later crates",
274            issue = "32110")]
275 impl<T> SliceExt for [T] {
276     type Item = T;
277
278     #[inline]
279     fn split_at(&self, mid: usize) -> (&[T], &[T]) {
280         (&self[..mid], &self[mid..])
281     }
282
283     #[inline]
284     fn iter(&self) -> Iter<T> {
285         unsafe {
286             let p = if mem::size_of::<T>() == 0 {
287                 1 as *const _
288             } else {
289                 let p = self.as_ptr();
290                 assume(!p.is_null());
291                 p
292             };
293
294             Iter {
295                 ptr: p,
296                 end: slice_offset!(p, self.len() as isize),
297                 _marker: marker::PhantomData
298             }
299         }
300     }
301
302     #[inline]
303     fn split<P>(&self, pred: P) -> Split<T, P>
304         where P: FnMut(&T) -> bool
305     {
306         Split {
307             v: self,
308             pred,
309             finished: false
310         }
311     }
312
313     #[inline]
314     fn rsplit<P>(&self, pred: P) -> RSplit<T, P>
315         where P: FnMut(&T) -> bool
316     {
317         RSplit { inner: self.split(pred) }
318     }
319
320     #[inline]
321     fn splitn<P>(&self, n: usize, pred: P) -> SplitN<T, P>
322         where P: FnMut(&T) -> bool
323     {
324         SplitN {
325             inner: GenericSplitN {
326                 iter: self.split(pred),
327                 count: n
328             }
329         }
330     }
331
332     #[inline]
333     fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<T, P>
334         where P: FnMut(&T) -> bool
335     {
336         RSplitN {
337             inner: GenericSplitN {
338                 iter: self.rsplit(pred),
339                 count: n
340             }
341         }
342     }
343
344     #[inline]
345     fn windows(&self, size: usize) -> Windows<T> {
346         assert!(size != 0);
347         Windows { v: self, size: size }
348     }
349
350     #[inline]
351     fn chunks(&self, chunk_size: usize) -> Chunks<T> {
352         assert!(chunk_size != 0);
353         Chunks { v: self, chunk_size: chunk_size }
354     }
355
356     #[inline]
357     fn get<I>(&self, index: I) -> Option<&I::Output>
358         where I: SliceIndex<[T]>
359     {
360         index.get(self)
361     }
362
363     #[inline]
364     fn first(&self) -> Option<&T> {
365         if self.is_empty() { None } else { Some(&self[0]) }
366     }
367
368     #[inline]
369     fn split_first(&self) -> Option<(&T, &[T])> {
370         if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
371     }
372
373     #[inline]
374     fn split_last(&self) -> Option<(&T, &[T])> {
375         let len = self.len();
376         if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
377     }
378
379     #[inline]
380     fn last(&self) -> Option<&T> {
381         if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
382     }
383
384     #[inline]
385     unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
386         where I: SliceIndex<[T]>
387     {
388         index.get_unchecked(self)
389     }
390
391     #[inline]
392     fn as_ptr(&self) -> *const T {
393         self as *const [T] as *const T
394     }
395
396     fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
397         where F: FnMut(&'a T) -> Ordering
398     {
399         let s = self;
400         let mut size = s.len();
401         if size == 0 {
402             return Err(0);
403         }
404         let mut base = 0usize;
405         while size > 1 {
406             let half = size / 2;
407             let mid = base + half;
408             // mid is always in [0, size), that means mid is >= 0 and < size.
409             // mid >= 0: by definition
410             // mid < size: mid = size / 2 + size / 4 + size / 8 ...
411             let cmp = f(unsafe { s.get_unchecked(mid) });
412             base = if cmp == Greater { base } else { mid };
413             size -= half;
414         }
415         // base is always in [0, size) because base <= mid.
416         let cmp = f(unsafe { s.get_unchecked(base) });
417         if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
418     }
419
420     #[inline]
421     fn len(&self) -> usize {
422         unsafe {
423             mem::transmute::<&[T], Repr<T>>(self).len
424         }
425     }
426
427     #[inline]
428     fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
429         where I: SliceIndex<[T]>
430     {
431         index.get_mut(self)
432     }
433
434     #[inline]
435     fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
436         let len = self.len();
437         let ptr = self.as_mut_ptr();
438
439         unsafe {
440             assert!(mid <= len);
441
442             (from_raw_parts_mut(ptr, mid),
443              from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
444         }
445     }
446
447     #[inline]
448     fn iter_mut(&mut self) -> IterMut<T> {
449         unsafe {
450             let p = if mem::size_of::<T>() == 0 {
451                 1 as *mut _
452             } else {
453                 let p = self.as_mut_ptr();
454                 assume(!p.is_null());
455                 p
456             };
457
458             IterMut {
459                 ptr: p,
460                 end: slice_offset!(p, self.len() as isize),
461                 _marker: marker::PhantomData
462             }
463         }
464     }
465
466     #[inline]
467     fn last_mut(&mut self) -> Option<&mut T> {
468         let len = self.len();
469         if len == 0 { return None; }
470         Some(&mut self[len - 1])
471     }
472
473     #[inline]
474     fn first_mut(&mut self) -> Option<&mut T> {
475         if self.is_empty() { None } else { Some(&mut self[0]) }
476     }
477
478     #[inline]
479     fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
480         if self.is_empty() { None } else {
481             let split = self.split_at_mut(1);
482             Some((&mut split.0[0], split.1))
483         }
484     }
485
486     #[inline]
487     fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
488         let len = self.len();
489         if len == 0 { None } else {
490             let split = self.split_at_mut(len - 1);
491             Some((&mut split.1[0], split.0))
492         }
493     }
494
495     #[inline]
496     fn split_mut<P>(&mut self, pred: P) -> SplitMut<T, P>
497         where P: FnMut(&T) -> bool
498     {
499         SplitMut { v: self, pred: pred, finished: false }
500     }
501
502     #[inline]
503     fn rsplit_mut<P>(&mut self, pred: P) -> RSplitMut<T, P>
504         where P: FnMut(&T) -> bool
505     {
506         RSplitMut { inner: self.split_mut(pred) }
507     }
508
509     #[inline]
510     fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<T, P>
511         where P: FnMut(&T) -> bool
512     {
513         SplitNMut {
514             inner: GenericSplitN {
515                 iter: self.split_mut(pred),
516                 count: n
517             }
518         }
519     }
520
521     #[inline]
522     fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<T, P> where
523         P: FnMut(&T) -> bool,
524     {
525         RSplitNMut {
526             inner: GenericSplitN {
527                 iter: self.rsplit_mut(pred),
528                 count: n
529             }
530         }
531     }
532
533     #[inline]
534     fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
535         assert!(chunk_size != 0);
536         ChunksMut { v: self, chunk_size: chunk_size }
537     }
538
539     #[inline]
540     fn swap(&mut self, a: usize, b: usize) {
541         unsafe {
542             // Can't take two mutable loans from one vector, so instead just cast
543             // them to their raw pointers to do the swap
544             let pa: *mut T = &mut self[a];
545             let pb: *mut T = &mut self[b];
546             ptr::swap(pa, pb);
547         }
548     }
549
550     fn reverse(&mut self) {
551         let mut i: usize = 0;
552         let ln = self.len();
553
554         // For very small types, all the individual reads in the normal
555         // path perform poorly.  We can do better, given efficient unaligned
556         // load/store, by loading a larger chunk and reversing a register.
557
558         // Ideally LLVM would do this for us, as it knows better than we do
559         // whether unaligned reads are efficient (since that changes between
560         // different ARM versions, for example) and what the best chunk size
561         // would be.  Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
562         // the loop, so we need to do this ourselves.  (Hypothesis: reverse
563         // is troublesome because the sides can be aligned differently --
564         // will be, when the length is odd -- so there's no way of emitting
565         // pre- and postludes to use fully-aligned SIMD in the middle.)
566
567         let fast_unaligned =
568             cfg!(any(target_arch = "x86", target_arch = "x86_64"));
569
570         if fast_unaligned && mem::size_of::<T>() == 1 {
571             // Use the llvm.bswap intrinsic to reverse u8s in a usize
572             let chunk = mem::size_of::<usize>();
573             while i + chunk - 1 < ln / 2 {
574                 unsafe {
575                     let pa: *mut T = self.get_unchecked_mut(i);
576                     let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
577                     let va = ptr::read_unaligned(pa as *mut usize);
578                     let vb = ptr::read_unaligned(pb as *mut usize);
579                     ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
580                     ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
581                 }
582                 i += chunk;
583             }
584         }
585
586         if fast_unaligned && mem::size_of::<T>() == 2 {
587             // Use rotate-by-16 to reverse u16s in a u32
588             let chunk = mem::size_of::<u32>() / 2;
589             while i + chunk - 1 < ln / 2 {
590                 unsafe {
591                     let pa: *mut T = self.get_unchecked_mut(i);
592                     let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
593                     let va = ptr::read_unaligned(pa as *mut u32);
594                     let vb = ptr::read_unaligned(pb as *mut u32);
595                     ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
596                     ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
597                 }
598                 i += chunk;
599             }
600         }
601
602         while i < ln / 2 {
603             // Unsafe swap to avoid the bounds check in safe swap.
604             unsafe {
605                 let pa: *mut T = self.get_unchecked_mut(i);
606                 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
607                 ptr::swap(pa, pb);
608             }
609             i += 1;
610         }
611     }
612
613     #[inline]
614     unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
615         where I: SliceIndex<[T]>
616     {
617         index.get_unchecked_mut(self)
618     }
619
620     #[inline]
621     fn as_mut_ptr(&mut self) -> *mut T {
622         self as *mut [T] as *mut T
623     }
624
625     #[inline]
626     fn contains(&self, x: &T) -> bool where T: PartialEq {
627         x.slice_contains(self)
628     }
629
630     #[inline]
631     fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
632         let n = needle.len();
633         self.len() >= n && needle == &self[..n]
634     }
635
636     #[inline]
637     fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
638         let (m, n) = (self.len(), needle.len());
639         m >= n && needle == &self[m-n..]
640     }
641
642     fn binary_search(&self, x: &T) -> Result<usize, usize>
643         where T: Ord
644     {
645         self.binary_search_by(|p| p.cmp(x))
646     }
647
648     fn rotate(&mut self, mid: usize) {
649         assert!(mid <= self.len());
650         let k = self.len() - mid;
651
652         unsafe {
653             let p = self.as_mut_ptr();
654             rotate::ptr_rotate(mid, p.offset(mid as isize), k);
655         }
656     }
657
658     #[inline]
659     fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
660         assert!(self.len() == src.len(),
661                 "destination and source slices have different lengths");
662         // NOTE: We need to explicitly slice them to the same length
663         // for bounds checking to be elided, and the optimizer will
664         // generate memcpy for simple cases (for example T = u8).
665         let len = self.len();
666         let src = &src[..len];
667         for i in 0..len {
668             self[i].clone_from(&src[i]);
669         }
670     }
671
672     #[inline]
673     fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
674         assert!(self.len() == src.len(),
675                 "destination and source slices have different lengths");
676         unsafe {
677             ptr::copy_nonoverlapping(
678                 src.as_ptr(), self.as_mut_ptr(), self.len());
679         }
680     }
681
682     #[inline]
683     fn swap_with_slice(&mut self, src: &mut [T]) {
684         assert!(self.len() == src.len(),
685                 "destination and source slices have different lengths");
686         unsafe {
687             ptr::swap_nonoverlapping(
688                 self.as_mut_ptr(), src.as_mut_ptr(), self.len());
689         }
690     }
691
692     #[inline]
693     fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
694         where F: FnMut(&'a Self::Item) -> B,
695               B: Ord
696     {
697         self.binary_search_by(|k| f(k).cmp(b))
698     }
699
700     #[inline]
701     fn sort_unstable(&mut self)
702         where Self::Item: Ord
703     {
704         sort::quicksort(self, |a, b| a.lt(b));
705     }
706
707     #[inline]
708     fn sort_unstable_by<F>(&mut self, mut compare: F)
709         where F: FnMut(&Self::Item, &Self::Item) -> Ordering
710     {
711         sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
712     }
713
714     #[inline]
715     fn sort_unstable_by_key<B, F>(&mut self, mut f: F)
716         where F: FnMut(&Self::Item) -> B,
717               B: Ord
718     {
719         sort::quicksort(self, |a, b| f(a).lt(&f(b)));
720     }
721 }
722
723 #[stable(feature = "rust1", since = "1.0.0")]
724 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
725 impl<T, I> ops::Index<I> for [T]
726     where I: SliceIndex<[T]>
727 {
728     type Output = I::Output;
729
730     #[inline]
731     fn index(&self, index: I) -> &I::Output {
732         index.index(self)
733     }
734 }
735
736 #[stable(feature = "rust1", since = "1.0.0")]
737 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
738 impl<T, I> ops::IndexMut<I> for [T]
739     where I: SliceIndex<[T]>
740 {
741     #[inline]
742     fn index_mut(&mut self, index: I) -> &mut I::Output {
743         index.index_mut(self)
744     }
745 }
746
747 #[inline(never)]
748 #[cold]
749 fn slice_index_len_fail(index: usize, len: usize) -> ! {
750     panic!("index {} out of range for slice of length {}", index, len);
751 }
752
753 #[inline(never)]
754 #[cold]
755 fn slice_index_order_fail(index: usize, end: usize) -> ! {
756     panic!("slice index starts at {} but ends at {}", index, end);
757 }
758
759 /// A helper trait used for indexing operations.
760 #[unstable(feature = "slice_get_slice", issue = "35729")]
761 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
762 pub trait SliceIndex<T: ?Sized> {
763     /// The output type returned by methods.
764     type Output: ?Sized;
765
766     /// Returns a shared reference to the output at this location, if in
767     /// bounds.
768     fn get(self, slice: &T) -> Option<&Self::Output>;
769
770     /// Returns a mutable reference to the output at this location, if in
771     /// bounds.
772     fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
773
774     /// Returns a shared reference to the output at this location, without
775     /// performing any bounds checking.
776     unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
777
778     /// Returns a mutable reference to the output at this location, without
779     /// performing any bounds checking.
780     unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
781
782     /// Returns a shared reference to the output at this location, panicking
783     /// if out of bounds.
784     fn index(self, slice: &T) -> &Self::Output;
785
786     /// Returns a mutable reference to the output at this location, panicking
787     /// if out of bounds.
788     fn index_mut(self, slice: &mut T) -> &mut Self::Output;
789 }
790
791 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
792 impl<T> SliceIndex<[T]> for usize {
793     type Output = T;
794
795     #[inline]
796     fn get(self, slice: &[T]) -> Option<&T> {
797         if self < slice.len() {
798             unsafe {
799                 Some(self.get_unchecked(slice))
800             }
801         } else {
802             None
803         }
804     }
805
806     #[inline]
807     fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
808         if self < slice.len() {
809             unsafe {
810                 Some(self.get_unchecked_mut(slice))
811             }
812         } else {
813             None
814         }
815     }
816
817     #[inline]
818     unsafe fn get_unchecked(self, slice: &[T]) -> &T {
819         &*slice.as_ptr().offset(self as isize)
820     }
821
822     #[inline]
823     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
824         &mut *slice.as_mut_ptr().offset(self as isize)
825     }
826
827     #[inline]
828     fn index(self, slice: &[T]) -> &T {
829         // NB: use intrinsic indexing
830         &(*slice)[self]
831     }
832
833     #[inline]
834     fn index_mut(self, slice: &mut [T]) -> &mut T {
835         // NB: use intrinsic indexing
836         &mut (*slice)[self]
837     }
838 }
839
840 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
841 impl<T> SliceIndex<[T]> for  ops::Range<usize> {
842     type Output = [T];
843
844     #[inline]
845     fn get(self, slice: &[T]) -> Option<&[T]> {
846         if self.start > self.end || self.end > slice.len() {
847             None
848         } else {
849             unsafe {
850                 Some(self.get_unchecked(slice))
851             }
852         }
853     }
854
855     #[inline]
856     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
857         if self.start > self.end || self.end > slice.len() {
858             None
859         } else {
860             unsafe {
861                 Some(self.get_unchecked_mut(slice))
862             }
863         }
864     }
865
866     #[inline]
867     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
868         from_raw_parts(slice.as_ptr().offset(self.start as isize), self.end - self.start)
869     }
870
871     #[inline]
872     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
873         from_raw_parts_mut(slice.as_mut_ptr().offset(self.start as isize), self.end - self.start)
874     }
875
876     #[inline]
877     fn index(self, slice: &[T]) -> &[T] {
878         if self.start > self.end {
879             slice_index_order_fail(self.start, self.end);
880         } else if self.end > slice.len() {
881             slice_index_len_fail(self.end, slice.len());
882         }
883         unsafe {
884             self.get_unchecked(slice)
885         }
886     }
887
888     #[inline]
889     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
890         if self.start > self.end {
891             slice_index_order_fail(self.start, self.end);
892         } else if self.end > slice.len() {
893             slice_index_len_fail(self.end, slice.len());
894         }
895         unsafe {
896             self.get_unchecked_mut(slice)
897         }
898     }
899 }
900
901 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
902 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
903     type Output = [T];
904
905     #[inline]
906     fn get(self, slice: &[T]) -> Option<&[T]> {
907         (0..self.end).get(slice)
908     }
909
910     #[inline]
911     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
912         (0..self.end).get_mut(slice)
913     }
914
915     #[inline]
916     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
917         (0..self.end).get_unchecked(slice)
918     }
919
920     #[inline]
921     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
922         (0..self.end).get_unchecked_mut(slice)
923     }
924
925     #[inline]
926     fn index(self, slice: &[T]) -> &[T] {
927         (0..self.end).index(slice)
928     }
929
930     #[inline]
931     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
932         (0..self.end).index_mut(slice)
933     }
934 }
935
936 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
937 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
938     type Output = [T];
939
940     #[inline]
941     fn get(self, slice: &[T]) -> Option<&[T]> {
942         (self.start..slice.len()).get(slice)
943     }
944
945     #[inline]
946     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
947         (self.start..slice.len()).get_mut(slice)
948     }
949
950     #[inline]
951     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
952         (self.start..slice.len()).get_unchecked(slice)
953     }
954
955     #[inline]
956     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
957         (self.start..slice.len()).get_unchecked_mut(slice)
958     }
959
960     #[inline]
961     fn index(self, slice: &[T]) -> &[T] {
962         (self.start..slice.len()).index(slice)
963     }
964
965     #[inline]
966     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
967         (self.start..slice.len()).index_mut(slice)
968     }
969 }
970
971 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
972 impl<T> SliceIndex<[T]> for ops::RangeFull {
973     type Output = [T];
974
975     #[inline]
976     fn get(self, slice: &[T]) -> Option<&[T]> {
977         Some(slice)
978     }
979
980     #[inline]
981     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
982         Some(slice)
983     }
984
985     #[inline]
986     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
987         slice
988     }
989
990     #[inline]
991     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
992         slice
993     }
994
995     #[inline]
996     fn index(self, slice: &[T]) -> &[T] {
997         slice
998     }
999
1000     #[inline]
1001     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1002         slice
1003     }
1004 }
1005
1006
1007 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1008 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
1009     type Output = [T];
1010
1011     #[inline]
1012     fn get(self, slice: &[T]) -> Option<&[T]> {
1013         if self.end == usize::max_value() { None }
1014         else { (self.start..self.end + 1).get(slice) }
1015     }
1016
1017     #[inline]
1018     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1019         if self.end == usize::max_value() { None }
1020         else { (self.start..self.end + 1).get_mut(slice) }
1021     }
1022
1023     #[inline]
1024     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1025         (self.start..self.end + 1).get_unchecked(slice)
1026     }
1027
1028     #[inline]
1029     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1030         (self.start..self.end + 1).get_unchecked_mut(slice)
1031     }
1032
1033     #[inline]
1034     fn index(self, slice: &[T]) -> &[T] {
1035         assert!(self.end != usize::max_value(),
1036             "attempted to index slice up to maximum usize");
1037         (self.start..self.end + 1).index(slice)
1038     }
1039
1040     #[inline]
1041     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1042         assert!(self.end != usize::max_value(),
1043             "attempted to index slice up to maximum usize");
1044         (self.start..self.end + 1).index_mut(slice)
1045     }
1046 }
1047
1048 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1049 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
1050     type Output = [T];
1051
1052     #[inline]
1053     fn get(self, slice: &[T]) -> Option<&[T]> {
1054         (0..=self.end).get(slice)
1055     }
1056
1057     #[inline]
1058     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1059         (0..=self.end).get_mut(slice)
1060     }
1061
1062     #[inline]
1063     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1064         (0..=self.end).get_unchecked(slice)
1065     }
1066
1067     #[inline]
1068     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1069         (0..=self.end).get_unchecked_mut(slice)
1070     }
1071
1072     #[inline]
1073     fn index(self, slice: &[T]) -> &[T] {
1074         (0..=self.end).index(slice)
1075     }
1076
1077     #[inline]
1078     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1079         (0..=self.end).index_mut(slice)
1080     }
1081 }
1082
1083 ////////////////////////////////////////////////////////////////////////////////
1084 // Common traits
1085 ////////////////////////////////////////////////////////////////////////////////
1086
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 impl<'a, T> Default for &'a [T] {
1089     /// Creates an empty slice.
1090     fn default() -> &'a [T] { &[] }
1091 }
1092
1093 #[stable(feature = "mut_slice_default", since = "1.5.0")]
1094 impl<'a, T> Default for &'a mut [T] {
1095     /// Creates a mutable empty slice.
1096     fn default() -> &'a mut [T] { &mut [] }
1097 }
1098
1099 //
1100 // Iterators
1101 //
1102
1103 #[stable(feature = "rust1", since = "1.0.0")]
1104 impl<'a, T> IntoIterator for &'a [T] {
1105     type Item = &'a T;
1106     type IntoIter = Iter<'a, T>;
1107
1108     fn into_iter(self) -> Iter<'a, T> {
1109         self.iter()
1110     }
1111 }
1112
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 impl<'a, T> IntoIterator for &'a mut [T] {
1115     type Item = &'a mut T;
1116     type IntoIter = IterMut<'a, T>;
1117
1118     fn into_iter(self) -> IterMut<'a, T> {
1119         self.iter_mut()
1120     }
1121 }
1122
1123 #[inline]
1124 fn size_from_ptr<T>(_: *const T) -> usize {
1125     mem::size_of::<T>()
1126 }
1127
1128 // The shared definition of the `Iter` and `IterMut` iterators
1129 macro_rules! iterator {
1130     (struct $name:ident -> $ptr:ty, $elem:ty, $mkref:ident) => {
1131         #[stable(feature = "rust1", since = "1.0.0")]
1132         impl<'a, T> Iterator for $name<'a, T> {
1133             type Item = $elem;
1134
1135             #[inline]
1136             fn next(&mut self) -> Option<$elem> {
1137                 // could be implemented with slices, but this avoids bounds checks
1138                 unsafe {
1139                     if mem::size_of::<T>() != 0 {
1140                         assume(!self.ptr.is_null());
1141                         assume(!self.end.is_null());
1142                     }
1143                     if self.ptr == self.end {
1144                         None
1145                     } else {
1146                         Some($mkref!(self.ptr.post_inc()))
1147                     }
1148                 }
1149             }
1150
1151             #[inline]
1152             fn size_hint(&self) -> (usize, Option<usize>) {
1153                 let exact = ptrdistance(self.ptr, self.end);
1154                 (exact, Some(exact))
1155             }
1156
1157             #[inline]
1158             fn count(self) -> usize {
1159                 self.len()
1160             }
1161
1162             #[inline]
1163             fn nth(&mut self, n: usize) -> Option<$elem> {
1164                 // Call helper method. Can't put the definition here because mut versus const.
1165                 self.iter_nth(n)
1166             }
1167
1168             #[inline]
1169             fn last(mut self) -> Option<$elem> {
1170                 self.next_back()
1171             }
1172
1173             #[inline]
1174             fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1175                 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1176             {
1177                 // manual unrolling is needed when there are conditional exits from the loop
1178                 let mut accum = init;
1179                 unsafe {
1180                     while ptrdistance(self.ptr, self.end) >= 4 {
1181                         accum = f(accum, $mkref!(self.ptr.post_inc()))?;
1182                         accum = f(accum, $mkref!(self.ptr.post_inc()))?;
1183                         accum = f(accum, $mkref!(self.ptr.post_inc()))?;
1184                         accum = f(accum, $mkref!(self.ptr.post_inc()))?;
1185                     }
1186                     while self.ptr != self.end {
1187                         accum = f(accum, $mkref!(self.ptr.post_inc()))?;
1188                     }
1189                 }
1190                 Try::from_ok(accum)
1191             }
1192
1193             #[inline]
1194             fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
1195                 where Fold: FnMut(Acc, Self::Item) -> Acc,
1196             {
1197                 // Let LLVM unroll this, rather than using the default
1198                 // impl that would force the manual unrolling above
1199                 let mut accum = init;
1200                 while let Some(x) = self.next() {
1201                     accum = f(accum, x);
1202                 }
1203                 accum
1204             }
1205         }
1206
1207         #[stable(feature = "rust1", since = "1.0.0")]
1208         impl<'a, T> DoubleEndedIterator for $name<'a, T> {
1209             #[inline]
1210             fn next_back(&mut self) -> Option<$elem> {
1211                 // could be implemented with slices, but this avoids bounds checks
1212                 unsafe {
1213                     if mem::size_of::<T>() != 0 {
1214                         assume(!self.ptr.is_null());
1215                         assume(!self.end.is_null());
1216                     }
1217                     if self.end == self.ptr {
1218                         None
1219                     } else {
1220                         Some($mkref!(self.end.pre_dec()))
1221                     }
1222                 }
1223             }
1224
1225             #[inline]
1226             fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1227                 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1228             {
1229                 // manual unrolling is needed when there are conditional exits from the loop
1230                 let mut accum = init;
1231                 unsafe {
1232                     while ptrdistance(self.ptr, self.end) >= 4 {
1233                         accum = f(accum, $mkref!(self.end.pre_dec()))?;
1234                         accum = f(accum, $mkref!(self.end.pre_dec()))?;
1235                         accum = f(accum, $mkref!(self.end.pre_dec()))?;
1236                         accum = f(accum, $mkref!(self.end.pre_dec()))?;
1237                     }
1238                     while self.ptr != self.end {
1239                         accum = f(accum, $mkref!(self.end.pre_dec()))?;
1240                     }
1241                 }
1242                 Try::from_ok(accum)
1243             }
1244
1245             #[inline]
1246             fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
1247                 where Fold: FnMut(Acc, Self::Item) -> Acc,
1248             {
1249                 // Let LLVM unroll this, rather than using the default
1250                 // impl that would force the manual unrolling above
1251                 let mut accum = init;
1252                 while let Some(x) = self.next_back() {
1253                     accum = f(accum, x);
1254                 }
1255                 accum
1256             }
1257         }
1258     }
1259 }
1260
1261 macro_rules! make_slice {
1262     ($start: expr, $end: expr) => {{
1263         let start = $start;
1264         let diff = ($end as usize).wrapping_sub(start as usize);
1265         if size_from_ptr(start) == 0 {
1266             // use a non-null pointer value
1267             unsafe { from_raw_parts(1 as *const _, diff) }
1268         } else {
1269             let len = diff / size_from_ptr(start);
1270             unsafe { from_raw_parts(start, len) }
1271         }
1272     }}
1273 }
1274
1275 macro_rules! make_mut_slice {
1276     ($start: expr, $end: expr) => {{
1277         let start = $start;
1278         let diff = ($end as usize).wrapping_sub(start as usize);
1279         if size_from_ptr(start) == 0 {
1280             // use a non-null pointer value
1281             unsafe { from_raw_parts_mut(1 as *mut _, diff) }
1282         } else {
1283             let len = diff / size_from_ptr(start);
1284             unsafe { from_raw_parts_mut(start, len) }
1285         }
1286     }}
1287 }
1288
1289 /// Immutable slice iterator
1290 ///
1291 /// This struct is created by the [`iter`] method on [slices].
1292 ///
1293 /// # Examples
1294 ///
1295 /// Basic usage:
1296 ///
1297 /// ```
1298 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
1299 /// let slice = &[1, 2, 3];
1300 ///
1301 /// // Then, we iterate over it:
1302 /// for element in slice.iter() {
1303 ///     println!("{}", element);
1304 /// }
1305 /// ```
1306 ///
1307 /// [`iter`]: ../../std/primitive.slice.html#method.iter
1308 /// [slices]: ../../std/primitive.slice.html
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 pub struct Iter<'a, T: 'a> {
1311     ptr: *const T,
1312     end: *const T,
1313     _marker: marker::PhantomData<&'a T>,
1314 }
1315
1316 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1317 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
1318     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1319         f.debug_tuple("Iter")
1320             .field(&self.as_slice())
1321             .finish()
1322     }
1323 }
1324
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1329
1330 impl<'a, T> Iter<'a, T> {
1331     /// View the underlying data as a subslice of the original data.
1332     ///
1333     /// This has the same lifetime as the original slice, and so the
1334     /// iterator can continue to be used while this exists.
1335     ///
1336     /// # Examples
1337     ///
1338     /// Basic usage:
1339     ///
1340     /// ```
1341     /// // First, we declare a type which has the `iter` method to get the `Iter`
1342     /// // struct (&[usize here]):
1343     /// let slice = &[1, 2, 3];
1344     ///
1345     /// // Then, we get the iterator:
1346     /// let mut iter = slice.iter();
1347     /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
1348     /// println!("{:?}", iter.as_slice());
1349     ///
1350     /// // Next, we move to the second element of the slice:
1351     /// iter.next();
1352     /// // Now `as_slice` returns "[2, 3]":
1353     /// println!("{:?}", iter.as_slice());
1354     /// ```
1355     #[stable(feature = "iter_to_slice", since = "1.4.0")]
1356     pub fn as_slice(&self) -> &'a [T] {
1357         make_slice!(self.ptr, self.end)
1358     }
1359
1360     // Helper function for Iter::nth
1361     fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
1362         match self.as_slice().get(n) {
1363             Some(elem_ref) => unsafe {
1364                 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1365                 Some(elem_ref)
1366             },
1367             None => {
1368                 self.ptr = self.end;
1369                 None
1370             }
1371         }
1372     }
1373 }
1374
1375 iterator!{struct Iter -> *const T, &'a T, make_ref}
1376
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1379     fn is_empty(&self) -> bool {
1380         self.ptr == self.end
1381     }
1382 }
1383
1384 #[unstable(feature = "fused", issue = "35602")]
1385 impl<'a, T> FusedIterator for Iter<'a, T> {}
1386
1387 #[unstable(feature = "trusted_len", issue = "37572")]
1388 unsafe impl<'a, T> TrustedLen for Iter<'a, T> {}
1389
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 impl<'a, T> Clone for Iter<'a, T> {
1392     fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
1393 }
1394
1395 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
1396 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
1397     fn as_ref(&self) -> &[T] {
1398         self.as_slice()
1399     }
1400 }
1401
1402 /// Mutable slice iterator.
1403 ///
1404 /// This struct is created by the [`iter_mut`] method on [slices].
1405 ///
1406 /// # Examples
1407 ///
1408 /// Basic usage:
1409 ///
1410 /// ```
1411 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1412 /// // struct (&[usize here]):
1413 /// let mut slice = &mut [1, 2, 3];
1414 ///
1415 /// // Then, we iterate over it and increment each element value:
1416 /// for element in slice.iter_mut() {
1417 ///     *element += 1;
1418 /// }
1419 ///
1420 /// // We now have "[2, 3, 4]":
1421 /// println!("{:?}", slice);
1422 /// ```
1423 ///
1424 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
1425 /// [slices]: ../../std/primitive.slice.html
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 pub struct IterMut<'a, T: 'a> {
1428     ptr: *mut T,
1429     end: *mut T,
1430     _marker: marker::PhantomData<&'a mut T>,
1431 }
1432
1433 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1434 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
1435     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1436         f.debug_tuple("IterMut")
1437             .field(&make_slice!(self.ptr, self.end))
1438             .finish()
1439     }
1440 }
1441
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1446
1447 impl<'a, T> IterMut<'a, T> {
1448     /// View the underlying data as a subslice of the original data.
1449     ///
1450     /// To avoid creating `&mut` references that alias, this is forced
1451     /// to consume the iterator. Consider using the `Slice` and
1452     /// `SliceMut` implementations for obtaining slices with more
1453     /// restricted lifetimes that do not consume the iterator.
1454     ///
1455     /// # Examples
1456     ///
1457     /// Basic usage:
1458     ///
1459     /// ```
1460     /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1461     /// // struct (&[usize here]):
1462     /// let mut slice = &mut [1, 2, 3];
1463     ///
1464     /// {
1465     ///     // Then, we get the iterator:
1466     ///     let mut iter = slice.iter_mut();
1467     ///     // We move to next element:
1468     ///     iter.next();
1469     ///     // So if we print what `into_slice` method returns here, we have "[2, 3]":
1470     ///     println!("{:?}", iter.into_slice());
1471     /// }
1472     ///
1473     /// // Now let's modify a value of the slice:
1474     /// {
1475     ///     // First we get back the iterator:
1476     ///     let mut iter = slice.iter_mut();
1477     ///     // We change the value of the first element of the slice returned by the `next` method:
1478     ///     *iter.next().unwrap() += 1;
1479     /// }
1480     /// // Now slice is "[2, 2, 3]":
1481     /// println!("{:?}", slice);
1482     /// ```
1483     #[stable(feature = "iter_to_slice", since = "1.4.0")]
1484     pub fn into_slice(self) -> &'a mut [T] {
1485         make_mut_slice!(self.ptr, self.end)
1486     }
1487
1488     // Helper function for IterMut::nth
1489     fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
1490         match make_mut_slice!(self.ptr, self.end).get_mut(n) {
1491             Some(elem_ref) => unsafe {
1492                 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1493                 Some(elem_ref)
1494             },
1495             None => {
1496                 self.ptr = self.end;
1497                 None
1498             }
1499         }
1500     }
1501 }
1502
1503 iterator!{struct IterMut -> *mut T, &'a mut T, make_ref_mut}
1504
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
1507     fn is_empty(&self) -> bool {
1508         self.ptr == self.end
1509     }
1510 }
1511
1512 #[unstable(feature = "fused", issue = "35602")]
1513 impl<'a, T> FusedIterator for IterMut<'a, T> {}
1514
1515 #[unstable(feature = "trusted_len", issue = "37572")]
1516 unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {}
1517
1518
1519 // Return the number of elements of `T` from `start` to `end`.
1520 // Return the arithmetic difference if `T` is zero size.
1521 #[inline(always)]
1522 fn ptrdistance<T>(start: *const T, end: *const T) -> usize {
1523     match start.offset_to(end) {
1524         Some(x) => x as usize,
1525         None => (end as usize).wrapping_sub(start as usize),
1526     }
1527 }
1528
1529 // Extension methods for raw pointers, used by the iterators
1530 trait PointerExt : Copy {
1531     unsafe fn slice_offset(self, i: isize) -> Self;
1532
1533     /// Increments `self` by 1, but returns the old value.
1534     #[inline(always)]
1535     unsafe fn post_inc(&mut self) -> Self {
1536         let current = *self;
1537         *self = self.slice_offset(1);
1538         current
1539     }
1540
1541     /// Decrements `self` by 1, and returns the new value.
1542     #[inline(always)]
1543     unsafe fn pre_dec(&mut self) -> Self {
1544         *self = self.slice_offset(-1);
1545         *self
1546     }
1547 }
1548
1549 impl<T> PointerExt for *const T {
1550     #[inline(always)]
1551     unsafe fn slice_offset(self, i: isize) -> Self {
1552         slice_offset!(self, i)
1553     }
1554 }
1555
1556 impl<T> PointerExt for *mut T {
1557     #[inline(always)]
1558     unsafe fn slice_offset(self, i: isize) -> Self {
1559         slice_offset!(self, i)
1560     }
1561 }
1562
1563 /// An internal abstraction over the splitting iterators, so that
1564 /// splitn, splitn_mut etc can be implemented once.
1565 #[doc(hidden)]
1566 trait SplitIter: DoubleEndedIterator {
1567     /// Marks the underlying iterator as complete, extracting the remaining
1568     /// portion of the slice.
1569     fn finish(&mut self) -> Option<Self::Item>;
1570 }
1571
1572 /// An iterator over subslices separated by elements that match a predicate
1573 /// function.
1574 ///
1575 /// This struct is created by the [`split`] method on [slices].
1576 ///
1577 /// [`split`]: ../../std/primitive.slice.html#method.split
1578 /// [slices]: ../../std/primitive.slice.html
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
1581     v: &'a [T],
1582     pred: P,
1583     finished: bool
1584 }
1585
1586 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1587 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
1588     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1589         f.debug_struct("Split")
1590             .field("v", &self.v)
1591             .field("finished", &self.finished)
1592             .finish()
1593     }
1594 }
1595
1596 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
1599     fn clone(&self) -> Split<'a, T, P> {
1600         Split {
1601             v: self.v,
1602             pred: self.pred.clone(),
1603             finished: self.finished,
1604         }
1605     }
1606 }
1607
1608 #[stable(feature = "rust1", since = "1.0.0")]
1609 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1610     type Item = &'a [T];
1611
1612     #[inline]
1613     fn next(&mut self) -> Option<&'a [T]> {
1614         if self.finished { return None; }
1615
1616         match self.v.iter().position(|x| (self.pred)(x)) {
1617             None => self.finish(),
1618             Some(idx) => {
1619                 let ret = Some(&self.v[..idx]);
1620                 self.v = &self.v[idx + 1..];
1621                 ret
1622             }
1623         }
1624     }
1625
1626     #[inline]
1627     fn size_hint(&self) -> (usize, Option<usize>) {
1628         if self.finished {
1629             (0, Some(0))
1630         } else {
1631             (1, Some(self.v.len() + 1))
1632         }
1633     }
1634 }
1635
1636 #[stable(feature = "rust1", since = "1.0.0")]
1637 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1638     #[inline]
1639     fn next_back(&mut self) -> Option<&'a [T]> {
1640         if self.finished { return None; }
1641
1642         match self.v.iter().rposition(|x| (self.pred)(x)) {
1643             None => self.finish(),
1644             Some(idx) => {
1645                 let ret = Some(&self.v[idx + 1..]);
1646                 self.v = &self.v[..idx];
1647                 ret
1648             }
1649         }
1650     }
1651 }
1652
1653 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1654     #[inline]
1655     fn finish(&mut self) -> Option<&'a [T]> {
1656         if self.finished { None } else { self.finished = true; Some(self.v) }
1657     }
1658 }
1659
1660 #[unstable(feature = "fused", issue = "35602")]
1661 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
1662
1663 /// An iterator over the subslices of the vector which are separated
1664 /// by elements that match `pred`.
1665 ///
1666 /// This struct is created by the [`split_mut`] method on [slices].
1667 ///
1668 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
1669 /// [slices]: ../../std/primitive.slice.html
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1672     v: &'a mut [T],
1673     pred: P,
1674     finished: bool
1675 }
1676
1677 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1678 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1679     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1680         f.debug_struct("SplitMut")
1681             .field("v", &self.v)
1682             .field("finished", &self.finished)
1683             .finish()
1684     }
1685 }
1686
1687 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1688     #[inline]
1689     fn finish(&mut self) -> Option<&'a mut [T]> {
1690         if self.finished {
1691             None
1692         } else {
1693             self.finished = true;
1694             Some(mem::replace(&mut self.v, &mut []))
1695         }
1696     }
1697 }
1698
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1701     type Item = &'a mut [T];
1702
1703     #[inline]
1704     fn next(&mut self) -> Option<&'a mut [T]> {
1705         if self.finished { return None; }
1706
1707         let idx_opt = { // work around borrowck limitations
1708             let pred = &mut self.pred;
1709             self.v.iter().position(|x| (*pred)(x))
1710         };
1711         match idx_opt {
1712             None => self.finish(),
1713             Some(idx) => {
1714                 let tmp = mem::replace(&mut self.v, &mut []);
1715                 let (head, tail) = tmp.split_at_mut(idx);
1716                 self.v = &mut tail[1..];
1717                 Some(head)
1718             }
1719         }
1720     }
1721
1722     #[inline]
1723     fn size_hint(&self) -> (usize, Option<usize>) {
1724         if self.finished {
1725             (0, Some(0))
1726         } else {
1727             // if the predicate doesn't match anything, we yield one slice
1728             // if it matches every element, we yield len+1 empty slices.
1729             (1, Some(self.v.len() + 1))
1730         }
1731     }
1732 }
1733
1734 #[stable(feature = "rust1", since = "1.0.0")]
1735 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1736     P: FnMut(&T) -> bool,
1737 {
1738     #[inline]
1739     fn next_back(&mut self) -> Option<&'a mut [T]> {
1740         if self.finished { return None; }
1741
1742         let idx_opt = { // work around borrowck limitations
1743             let pred = &mut self.pred;
1744             self.v.iter().rposition(|x| (*pred)(x))
1745         };
1746         match idx_opt {
1747             None => self.finish(),
1748             Some(idx) => {
1749                 let tmp = mem::replace(&mut self.v, &mut []);
1750                 let (head, tail) = tmp.split_at_mut(idx);
1751                 self.v = head;
1752                 Some(&mut tail[1..])
1753             }
1754         }
1755     }
1756 }
1757
1758 #[unstable(feature = "fused", issue = "35602")]
1759 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1760
1761 /// An iterator over subslices separated by elements that match a predicate
1762 /// function, starting from the end of the slice.
1763 ///
1764 /// This struct is created by the [`rsplit`] method on [slices].
1765 ///
1766 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
1767 /// [slices]: ../../std/primitive.slice.html
1768 #[unstable(feature = "slice_rsplit", issue = "41020")]
1769 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
1770 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
1771     inner: Split<'a, T, P>
1772 }
1773
1774 #[unstable(feature = "slice_rsplit", issue = "41020")]
1775 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1776     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1777         f.debug_struct("RSplit")
1778             .field("v", &self.inner.v)
1779             .field("finished", &self.inner.finished)
1780             .finish()
1781     }
1782 }
1783
1784 #[unstable(feature = "slice_rsplit", issue = "41020")]
1785 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1786     type Item = &'a [T];
1787
1788     #[inline]
1789     fn next(&mut self) -> Option<&'a [T]> {
1790         self.inner.next_back()
1791     }
1792
1793     #[inline]
1794     fn size_hint(&self) -> (usize, Option<usize>) {
1795         self.inner.size_hint()
1796     }
1797 }
1798
1799 #[unstable(feature = "slice_rsplit", issue = "41020")]
1800 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1801     #[inline]
1802     fn next_back(&mut self) -> Option<&'a [T]> {
1803         self.inner.next()
1804     }
1805 }
1806
1807 #[unstable(feature = "slice_rsplit", issue = "41020")]
1808 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1809     #[inline]
1810     fn finish(&mut self) -> Option<&'a [T]> {
1811         self.inner.finish()
1812     }
1813 }
1814
1815 //#[unstable(feature = "fused", issue = "35602")]
1816 #[unstable(feature = "slice_rsplit", issue = "41020")]
1817 impl<'a, T, P> FusedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {}
1818
1819 /// An iterator over the subslices of the vector which are separated
1820 /// by elements that match `pred`, starting from the end of the slice.
1821 ///
1822 /// This struct is created by the [`rsplit_mut`] method on [slices].
1823 ///
1824 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
1825 /// [slices]: ../../std/primitive.slice.html
1826 #[unstable(feature = "slice_rsplit", issue = "41020")]
1827 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1828     inner: SplitMut<'a, T, P>
1829 }
1830
1831 #[unstable(feature = "slice_rsplit", issue = "41020")]
1832 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1833     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1834         f.debug_struct("RSplitMut")
1835             .field("v", &self.inner.v)
1836             .field("finished", &self.inner.finished)
1837             .finish()
1838     }
1839 }
1840
1841 #[unstable(feature = "slice_rsplit", issue = "41020")]
1842 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1843     #[inline]
1844     fn finish(&mut self) -> Option<&'a mut [T]> {
1845         self.inner.finish()
1846     }
1847 }
1848
1849 #[unstable(feature = "slice_rsplit", issue = "41020")]
1850 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1851     type Item = &'a mut [T];
1852
1853     #[inline]
1854     fn next(&mut self) -> Option<&'a mut [T]> {
1855         self.inner.next_back()
1856     }
1857
1858     #[inline]
1859     fn size_hint(&self) -> (usize, Option<usize>) {
1860         self.inner.size_hint()
1861     }
1862 }
1863
1864 #[unstable(feature = "slice_rsplit", issue = "41020")]
1865 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
1866     P: FnMut(&T) -> bool,
1867 {
1868     #[inline]
1869     fn next_back(&mut self) -> Option<&'a mut [T]> {
1870         self.inner.next()
1871     }
1872 }
1873
1874 //#[unstable(feature = "fused", issue = "35602")]
1875 #[unstable(feature = "slice_rsplit", issue = "41020")]
1876 impl<'a, T, P> FusedIterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1877
1878 /// An private iterator over subslices separated by elements that
1879 /// match a predicate function, splitting at most a fixed number of
1880 /// times.
1881 #[derive(Debug)]
1882 struct GenericSplitN<I> {
1883     iter: I,
1884     count: usize,
1885 }
1886
1887 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1888     type Item = T;
1889
1890     #[inline]
1891     fn next(&mut self) -> Option<T> {
1892         match self.count {
1893             0 => None,
1894             1 => { self.count -= 1; self.iter.finish() }
1895             _ => { self.count -= 1; self.iter.next() }
1896         }
1897     }
1898
1899     #[inline]
1900     fn size_hint(&self) -> (usize, Option<usize>) {
1901         let (lower, upper_opt) = self.iter.size_hint();
1902         (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1903     }
1904 }
1905
1906 /// An iterator over subslices separated by elements that match a predicate
1907 /// function, limited to a given number of splits.
1908 ///
1909 /// This struct is created by the [`splitn`] method on [slices].
1910 ///
1911 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
1912 /// [slices]: ../../std/primitive.slice.html
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1915     inner: GenericSplitN<Split<'a, T, P>>
1916 }
1917
1918 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1919 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
1920     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1921         f.debug_struct("SplitN")
1922             .field("inner", &self.inner)
1923             .finish()
1924     }
1925 }
1926
1927 /// An iterator over subslices separated by elements that match a
1928 /// predicate function, limited to a given number of splits, starting
1929 /// from the end of the slice.
1930 ///
1931 /// This struct is created by the [`rsplitn`] method on [slices].
1932 ///
1933 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
1934 /// [slices]: ../../std/primitive.slice.html
1935 #[stable(feature = "rust1", since = "1.0.0")]
1936 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1937     inner: GenericSplitN<RSplit<'a, T, P>>
1938 }
1939
1940 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1941 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
1942     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1943         f.debug_struct("RSplitN")
1944             .field("inner", &self.inner)
1945             .finish()
1946     }
1947 }
1948
1949 /// An iterator over subslices separated by elements that match a predicate
1950 /// function, limited to a given number of splits.
1951 ///
1952 /// This struct is created by the [`splitn_mut`] method on [slices].
1953 ///
1954 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
1955 /// [slices]: ../../std/primitive.slice.html
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1958     inner: GenericSplitN<SplitMut<'a, T, P>>
1959 }
1960
1961 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1962 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
1963     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1964         f.debug_struct("SplitNMut")
1965             .field("inner", &self.inner)
1966             .finish()
1967     }
1968 }
1969
1970 /// An iterator over subslices separated by elements that match a
1971 /// predicate function, limited to a given number of splits, starting
1972 /// from the end of the slice.
1973 ///
1974 /// This struct is created by the [`rsplitn_mut`] method on [slices].
1975 ///
1976 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
1977 /// [slices]: ../../std/primitive.slice.html
1978 #[stable(feature = "rust1", since = "1.0.0")]
1979 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1980     inner: GenericSplitN<RSplitMut<'a, T, P>>
1981 }
1982
1983 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1984 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
1985     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1986         f.debug_struct("RSplitNMut")
1987             .field("inner", &self.inner)
1988             .finish()
1989     }
1990 }
1991
1992 macro_rules! forward_iterator {
1993     ($name:ident: $elem:ident, $iter_of:ty) => {
1994         #[stable(feature = "rust1", since = "1.0.0")]
1995         impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1996             P: FnMut(&T) -> bool
1997         {
1998             type Item = $iter_of;
1999
2000             #[inline]
2001             fn next(&mut self) -> Option<$iter_of> {
2002                 self.inner.next()
2003             }
2004
2005             #[inline]
2006             fn size_hint(&self) -> (usize, Option<usize>) {
2007                 self.inner.size_hint()
2008             }
2009         }
2010
2011         #[unstable(feature = "fused", issue = "35602")]
2012         impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
2013             where P: FnMut(&T) -> bool {}
2014     }
2015 }
2016
2017 forward_iterator! { SplitN: T, &'a [T] }
2018 forward_iterator! { RSplitN: T, &'a [T] }
2019 forward_iterator! { SplitNMut: T, &'a mut [T] }
2020 forward_iterator! { RSplitNMut: T, &'a mut [T] }
2021
2022 /// An iterator over overlapping subslices of length `size`.
2023 ///
2024 /// This struct is created by the [`windows`] method on [slices].
2025 ///
2026 /// [`windows`]: ../../std/primitive.slice.html#method.windows
2027 /// [slices]: ../../std/primitive.slice.html
2028 #[derive(Debug)]
2029 #[stable(feature = "rust1", since = "1.0.0")]
2030 pub struct Windows<'a, T:'a> {
2031     v: &'a [T],
2032     size: usize
2033 }
2034
2035 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2036 #[stable(feature = "rust1", since = "1.0.0")]
2037 impl<'a, T> Clone for Windows<'a, T> {
2038     fn clone(&self) -> Windows<'a, T> {
2039         Windows {
2040             v: self.v,
2041             size: self.size,
2042         }
2043     }
2044 }
2045
2046 #[stable(feature = "rust1", since = "1.0.0")]
2047 impl<'a, T> Iterator for Windows<'a, T> {
2048     type Item = &'a [T];
2049
2050     #[inline]
2051     fn next(&mut self) -> Option<&'a [T]> {
2052         if self.size > self.v.len() {
2053             None
2054         } else {
2055             let ret = Some(&self.v[..self.size]);
2056             self.v = &self.v[1..];
2057             ret
2058         }
2059     }
2060
2061     #[inline]
2062     fn size_hint(&self) -> (usize, Option<usize>) {
2063         if self.size > self.v.len() {
2064             (0, Some(0))
2065         } else {
2066             let size = self.v.len() - self.size + 1;
2067             (size, Some(size))
2068         }
2069     }
2070
2071     #[inline]
2072     fn count(self) -> usize {
2073         self.len()
2074     }
2075
2076     #[inline]
2077     fn nth(&mut self, n: usize) -> Option<Self::Item> {
2078         let (end, overflow) = self.size.overflowing_add(n);
2079         if end > self.v.len() || overflow {
2080             self.v = &[];
2081             None
2082         } else {
2083             let nth = &self.v[n..end];
2084             self.v = &self.v[n+1..];
2085             Some(nth)
2086         }
2087     }
2088
2089     #[inline]
2090     fn last(self) -> Option<Self::Item> {
2091         if self.size > self.v.len() {
2092             None
2093         } else {
2094             let start = self.v.len() - self.size;
2095             Some(&self.v[start..])
2096         }
2097     }
2098 }
2099
2100 #[stable(feature = "rust1", since = "1.0.0")]
2101 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
2102     #[inline]
2103     fn next_back(&mut self) -> Option<&'a [T]> {
2104         if self.size > self.v.len() {
2105             None
2106         } else {
2107             let ret = Some(&self.v[self.v.len()-self.size..]);
2108             self.v = &self.v[..self.v.len()-1];
2109             ret
2110         }
2111     }
2112 }
2113
2114 #[stable(feature = "rust1", since = "1.0.0")]
2115 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
2116
2117 #[unstable(feature = "fused", issue = "35602")]
2118 impl<'a, T> FusedIterator for Windows<'a, T> {}
2119
2120 #[doc(hidden)]
2121 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
2122     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
2123         from_raw_parts(self.v.as_ptr().offset(i as isize), self.size)
2124     }
2125     fn may_have_side_effect() -> bool { false }
2126 }
2127
2128 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2129 /// time).
2130 ///
2131 /// When the slice len is not evenly divided by the chunk size, the last slice
2132 /// of the iteration will be the remainder.
2133 ///
2134 /// This struct is created by the [`chunks`] method on [slices].
2135 ///
2136 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
2137 /// [slices]: ../../std/primitive.slice.html
2138 #[derive(Debug)]
2139 #[stable(feature = "rust1", since = "1.0.0")]
2140 pub struct Chunks<'a, T:'a> {
2141     v: &'a [T],
2142     chunk_size: usize
2143 }
2144
2145 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 impl<'a, T> Clone for Chunks<'a, T> {
2148     fn clone(&self) -> Chunks<'a, T> {
2149         Chunks {
2150             v: self.v,
2151             chunk_size: self.chunk_size,
2152         }
2153     }
2154 }
2155
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 impl<'a, T> Iterator for Chunks<'a, T> {
2158     type Item = &'a [T];
2159
2160     #[inline]
2161     fn next(&mut self) -> Option<&'a [T]> {
2162         if self.v.is_empty() {
2163             None
2164         } else {
2165             let chunksz = cmp::min(self.v.len(), self.chunk_size);
2166             let (fst, snd) = self.v.split_at(chunksz);
2167             self.v = snd;
2168             Some(fst)
2169         }
2170     }
2171
2172     #[inline]
2173     fn size_hint(&self) -> (usize, Option<usize>) {
2174         if self.v.is_empty() {
2175             (0, Some(0))
2176         } else {
2177             let n = self.v.len() / self.chunk_size;
2178             let rem = self.v.len() % self.chunk_size;
2179             let n = if rem > 0 { n+1 } else { n };
2180             (n, Some(n))
2181         }
2182     }
2183
2184     #[inline]
2185     fn count(self) -> usize {
2186         self.len()
2187     }
2188
2189     #[inline]
2190     fn nth(&mut self, n: usize) -> Option<Self::Item> {
2191         let (start, overflow) = n.overflowing_mul(self.chunk_size);
2192         if start >= self.v.len() || overflow {
2193             self.v = &[];
2194             None
2195         } else {
2196             let end = match start.checked_add(self.chunk_size) {
2197                 Some(sum) => cmp::min(self.v.len(), sum),
2198                 None => self.v.len(),
2199             };
2200             let nth = &self.v[start..end];
2201             self.v = &self.v[end..];
2202             Some(nth)
2203         }
2204     }
2205
2206     #[inline]
2207     fn last(self) -> Option<Self::Item> {
2208         if self.v.is_empty() {
2209             None
2210         } else {
2211             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
2212             Some(&self.v[start..])
2213         }
2214     }
2215 }
2216
2217 #[stable(feature = "rust1", since = "1.0.0")]
2218 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
2219     #[inline]
2220     fn next_back(&mut self) -> Option<&'a [T]> {
2221         if self.v.is_empty() {
2222             None
2223         } else {
2224             let remainder = self.v.len() % self.chunk_size;
2225             let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
2226             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
2227             self.v = fst;
2228             Some(snd)
2229         }
2230     }
2231 }
2232
2233 #[stable(feature = "rust1", since = "1.0.0")]
2234 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
2235
2236 #[unstable(feature = "fused", issue = "35602")]
2237 impl<'a, T> FusedIterator for Chunks<'a, T> {}
2238
2239 #[doc(hidden)]
2240 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
2241     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
2242         let start = i * self.chunk_size;
2243         let end = match start.checked_add(self.chunk_size) {
2244             None => self.v.len(),
2245             Some(end) => cmp::min(end, self.v.len()),
2246         };
2247         from_raw_parts(self.v.as_ptr().offset(start as isize), end - start)
2248     }
2249     fn may_have_side_effect() -> bool { false }
2250 }
2251
2252 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2253 /// elements at a time). When the slice len is not evenly divided by the chunk
2254 /// size, the last slice of the iteration will be the remainder.
2255 ///
2256 /// This struct is created by the [`chunks_mut`] method on [slices].
2257 ///
2258 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
2259 /// [slices]: ../../std/primitive.slice.html
2260 #[derive(Debug)]
2261 #[stable(feature = "rust1", since = "1.0.0")]
2262 pub struct ChunksMut<'a, T:'a> {
2263     v: &'a mut [T],
2264     chunk_size: usize
2265 }
2266
2267 #[stable(feature = "rust1", since = "1.0.0")]
2268 impl<'a, T> Iterator for ChunksMut<'a, T> {
2269     type Item = &'a mut [T];
2270
2271     #[inline]
2272     fn next(&mut self) -> Option<&'a mut [T]> {
2273         if self.v.is_empty() {
2274             None
2275         } else {
2276             let sz = cmp::min(self.v.len(), self.chunk_size);
2277             let tmp = mem::replace(&mut self.v, &mut []);
2278             let (head, tail) = tmp.split_at_mut(sz);
2279             self.v = tail;
2280             Some(head)
2281         }
2282     }
2283
2284     #[inline]
2285     fn size_hint(&self) -> (usize, Option<usize>) {
2286         if self.v.is_empty() {
2287             (0, Some(0))
2288         } else {
2289             let n = self.v.len() / self.chunk_size;
2290             let rem = self.v.len() % self.chunk_size;
2291             let n = if rem > 0 { n + 1 } else { n };
2292             (n, Some(n))
2293         }
2294     }
2295
2296     #[inline]
2297     fn count(self) -> usize {
2298         self.len()
2299     }
2300
2301     #[inline]
2302     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2303         let (start, overflow) = n.overflowing_mul(self.chunk_size);
2304         if start >= self.v.len() || overflow {
2305             self.v = &mut [];
2306             None
2307         } else {
2308             let end = match start.checked_add(self.chunk_size) {
2309                 Some(sum) => cmp::min(self.v.len(), sum),
2310                 None => self.v.len(),
2311             };
2312             let tmp = mem::replace(&mut self.v, &mut []);
2313             let (head, tail) = tmp.split_at_mut(end);
2314             let (_, nth) =  head.split_at_mut(start);
2315             self.v = tail;
2316             Some(nth)
2317         }
2318     }
2319
2320     #[inline]
2321     fn last(self) -> Option<Self::Item> {
2322         if self.v.is_empty() {
2323             None
2324         } else {
2325             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
2326             Some(&mut self.v[start..])
2327         }
2328     }
2329 }
2330
2331 #[stable(feature = "rust1", since = "1.0.0")]
2332 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
2333     #[inline]
2334     fn next_back(&mut self) -> Option<&'a mut [T]> {
2335         if self.v.is_empty() {
2336             None
2337         } else {
2338             let remainder = self.v.len() % self.chunk_size;
2339             let sz = if remainder != 0 { remainder } else { self.chunk_size };
2340             let tmp = mem::replace(&mut self.v, &mut []);
2341             let tmp_len = tmp.len();
2342             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
2343             self.v = head;
2344             Some(tail)
2345         }
2346     }
2347 }
2348
2349 #[stable(feature = "rust1", since = "1.0.0")]
2350 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
2351
2352 #[unstable(feature = "fused", issue = "35602")]
2353 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
2354
2355 #[doc(hidden)]
2356 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
2357     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
2358         let start = i * self.chunk_size;
2359         let end = match start.checked_add(self.chunk_size) {
2360             None => self.v.len(),
2361             Some(end) => cmp::min(end, self.v.len()),
2362         };
2363         from_raw_parts_mut(self.v.as_mut_ptr().offset(start as isize), end - start)
2364     }
2365     fn may_have_side_effect() -> bool { false }
2366 }
2367
2368 //
2369 // Free functions
2370 //
2371
2372 /// Forms a slice from a pointer and a length.
2373 ///
2374 /// The `len` argument is the number of **elements**, not the number of bytes.
2375 ///
2376 /// # Safety
2377 ///
2378 /// This function is unsafe as there is no guarantee that the given pointer is
2379 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
2380 /// lifetime for the returned slice.
2381 ///
2382 /// `p` must be non-null, even for zero-length slices, because non-zero bits
2383 /// are required to distinguish between a zero-length slice within `Some()`
2384 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
2385 /// for zero-length slices, though.
2386 ///
2387 /// # Caveat
2388 ///
2389 /// The lifetime for the returned slice is inferred from its usage. To
2390 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
2391 /// source lifetime is safe in the context, such as by providing a helper
2392 /// function taking the lifetime of a host value for the slice, or by explicit
2393 /// annotation.
2394 ///
2395 /// # Examples
2396 ///
2397 /// ```
2398 /// use std::slice;
2399 ///
2400 /// // manifest a slice out of thin air!
2401 /// let ptr = 0x1234 as *const usize;
2402 /// let amt = 10;
2403 /// unsafe {
2404 ///     let slice = slice::from_raw_parts(ptr, amt);
2405 /// }
2406 /// ```
2407 #[inline]
2408 #[stable(feature = "rust1", since = "1.0.0")]
2409 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
2410     mem::transmute(Repr { data: p, len: len })
2411 }
2412
2413 /// Performs the same functionality as `from_raw_parts`, except that a mutable
2414 /// slice is returned.
2415 ///
2416 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
2417 /// as not being able to provide a non-aliasing guarantee of the returned
2418 /// mutable slice. `p` must be non-null even for zero-length slices as with
2419 /// `from_raw_parts`.
2420 #[inline]
2421 #[stable(feature = "rust1", since = "1.0.0")]
2422 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
2423     mem::transmute(Repr { data: p, len: len })
2424 }
2425
2426 /// Converts a reference to T into a slice of length 1 (without copying).
2427 #[unstable(feature = "from_ref", issue = "45703")]
2428 pub fn from_ref<T>(s: &T) -> &[T] {
2429     unsafe {
2430         from_raw_parts(s, 1)
2431     }
2432 }
2433
2434 /// Converts a reference to T into a slice of length 1 (without copying).
2435 #[unstable(feature = "from_ref", issue = "45703")]
2436 pub fn from_ref_mut<T>(s: &mut T) -> &mut [T] {
2437     unsafe {
2438         from_raw_parts_mut(s, 1)
2439     }
2440 }
2441
2442 // This function is public only because there is no other way to unit test heapsort.
2443 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
2444 #[doc(hidden)]
2445 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
2446     where F: FnMut(&T, &T) -> bool
2447 {
2448     sort::heapsort(v, &mut is_less);
2449 }
2450
2451 //
2452 // Comparison traits
2453 //
2454
2455 extern {
2456     /// Calls implementation provided memcmp.
2457     ///
2458     /// Interprets the data as u8.
2459     ///
2460     /// Returns 0 for equal, < 0 for less than and > 0 for greater
2461     /// than.
2462     // FIXME(#32610): Return type should be c_int
2463     fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
2464 }
2465
2466 #[stable(feature = "rust1", since = "1.0.0")]
2467 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
2468     fn eq(&self, other: &[B]) -> bool {
2469         SlicePartialEq::equal(self, other)
2470     }
2471
2472     fn ne(&self, other: &[B]) -> bool {
2473         SlicePartialEq::not_equal(self, other)
2474     }
2475 }
2476
2477 #[stable(feature = "rust1", since = "1.0.0")]
2478 impl<T: Eq> Eq for [T] {}
2479
2480 /// Implements comparison of vectors lexicographically.
2481 #[stable(feature = "rust1", since = "1.0.0")]
2482 impl<T: Ord> Ord for [T] {
2483     fn cmp(&self, other: &[T]) -> Ordering {
2484         SliceOrd::compare(self, other)
2485     }
2486 }
2487
2488 /// Implements comparison of vectors lexicographically.
2489 #[stable(feature = "rust1", since = "1.0.0")]
2490 impl<T: PartialOrd> PartialOrd for [T] {
2491     fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
2492         SlicePartialOrd::partial_compare(self, other)
2493     }
2494 }
2495
2496 #[doc(hidden)]
2497 // intermediate trait for specialization of slice's PartialEq
2498 trait SlicePartialEq<B> {
2499     fn equal(&self, other: &[B]) -> bool;
2500
2501     fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
2502 }
2503
2504 // Generic slice equality
2505 impl<A, B> SlicePartialEq<B> for [A]
2506     where A: PartialEq<B>
2507 {
2508     default fn equal(&self, other: &[B]) -> bool {
2509         if self.len() != other.len() {
2510             return false;
2511         }
2512
2513         for i in 0..self.len() {
2514             if !self[i].eq(&other[i]) {
2515                 return false;
2516             }
2517         }
2518
2519         true
2520     }
2521 }
2522
2523 // Use memcmp for bytewise equality when the types allow
2524 impl<A> SlicePartialEq<A> for [A]
2525     where A: PartialEq<A> + BytewiseEquality
2526 {
2527     fn equal(&self, other: &[A]) -> bool {
2528         if self.len() != other.len() {
2529             return false;
2530         }
2531         if self.as_ptr() == other.as_ptr() {
2532             return true;
2533         }
2534         unsafe {
2535             let size = mem::size_of_val(self);
2536             memcmp(self.as_ptr() as *const u8,
2537                    other.as_ptr() as *const u8, size) == 0
2538         }
2539     }
2540 }
2541
2542 #[doc(hidden)]
2543 // intermediate trait for specialization of slice's PartialOrd
2544 trait SlicePartialOrd<B> {
2545     fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
2546 }
2547
2548 impl<A> SlicePartialOrd<A> for [A]
2549     where A: PartialOrd
2550 {
2551     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2552         let l = cmp::min(self.len(), other.len());
2553
2554         // Slice to the loop iteration range to enable bound check
2555         // elimination in the compiler
2556         let lhs = &self[..l];
2557         let rhs = &other[..l];
2558
2559         for i in 0..l {
2560             match lhs[i].partial_cmp(&rhs[i]) {
2561                 Some(Ordering::Equal) => (),
2562                 non_eq => return non_eq,
2563             }
2564         }
2565
2566         self.len().partial_cmp(&other.len())
2567     }
2568 }
2569
2570 impl<A> SlicePartialOrd<A> for [A]
2571     where A: Ord
2572 {
2573     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2574         Some(SliceOrd::compare(self, other))
2575     }
2576 }
2577
2578 #[doc(hidden)]
2579 // intermediate trait for specialization of slice's Ord
2580 trait SliceOrd<B> {
2581     fn compare(&self, other: &[B]) -> Ordering;
2582 }
2583
2584 impl<A> SliceOrd<A> for [A]
2585     where A: Ord
2586 {
2587     default fn compare(&self, other: &[A]) -> Ordering {
2588         let l = cmp::min(self.len(), other.len());
2589
2590         // Slice to the loop iteration range to enable bound check
2591         // elimination in the compiler
2592         let lhs = &self[..l];
2593         let rhs = &other[..l];
2594
2595         for i in 0..l {
2596             match lhs[i].cmp(&rhs[i]) {
2597                 Ordering::Equal => (),
2598                 non_eq => return non_eq,
2599             }
2600         }
2601
2602         self.len().cmp(&other.len())
2603     }
2604 }
2605
2606 // memcmp compares a sequence of unsigned bytes lexicographically.
2607 // this matches the order we want for [u8], but no others (not even [i8]).
2608 impl SliceOrd<u8> for [u8] {
2609     #[inline]
2610     fn compare(&self, other: &[u8]) -> Ordering {
2611         let order = unsafe {
2612             memcmp(self.as_ptr(), other.as_ptr(),
2613                    cmp::min(self.len(), other.len()))
2614         };
2615         if order == 0 {
2616             self.len().cmp(&other.len())
2617         } else if order < 0 {
2618             Less
2619         } else {
2620             Greater
2621         }
2622     }
2623 }
2624
2625 #[doc(hidden)]
2626 /// Trait implemented for types that can be compared for equality using
2627 /// their bytewise representation
2628 trait BytewiseEquality { }
2629
2630 macro_rules! impl_marker_for {
2631     ($traitname:ident, $($ty:ty)*) => {
2632         $(
2633             impl $traitname for $ty { }
2634         )*
2635     }
2636 }
2637
2638 impl_marker_for!(BytewiseEquality,
2639                  u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
2640
2641 #[doc(hidden)]
2642 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
2643     unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
2644         &*self.ptr.offset(i as isize)
2645     }
2646     fn may_have_side_effect() -> bool { false }
2647 }
2648
2649 #[doc(hidden)]
2650 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
2651     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
2652         &mut *self.ptr.offset(i as isize)
2653     }
2654     fn may_have_side_effect() -> bool { false }
2655 }
2656
2657 trait SliceContains: Sized {
2658     fn slice_contains(&self, x: &[Self]) -> bool;
2659 }
2660
2661 impl<T> SliceContains for T where T: PartialEq {
2662     default fn slice_contains(&self, x: &[Self]) -> bool {
2663         x.iter().any(|y| *y == *self)
2664     }
2665 }
2666
2667 impl SliceContains for u8 {
2668     fn slice_contains(&self, x: &[Self]) -> bool {
2669         memchr::memchr(*self, x).is_some()
2670     }
2671 }
2672
2673 impl SliceContains for i8 {
2674     fn slice_contains(&self, x: &[Self]) -> bool {
2675         let byte = *self as u8;
2676         let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
2677         memchr::memchr(byte, bytes).is_some()
2678     }
2679 }