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