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