/
slice.rs
2348 lines (2073 loc) · 70.2 KB
/
slice.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Utilities for slice manipulation
//!
//! The `slice` module contains useful code to help work with slice values.
//! Slices are a view into a block of memory represented as a pointer and a length.
//!
//! ```rust
//! // slicing a Vec
//! let vec = vec!(1i, 2, 3);
//! let int_slice = vec.as_slice();
//! // coercing an array to a slice
//! let str_slice: &[&str] = ["one", "two", "three"];
//! ```
//!
//! Slices are either mutable or shared. The shared slice type is `&[T]`,
//! while the mutable slice type is `&mut[T]`. For example, you can mutate the
//! block of memory that a mutable slice points to:
//!
//! ```rust
//! let x: &mut[int] = [1i, 2, 3];
//! x[1] = 7;
//! assert_eq!(x[0], 1);
//! assert_eq!(x[1], 7);
//! assert_eq!(x[2], 3);
//! ```
//!
//! Here are some of the things this module contains:
//!
//! ## Structs
//!
//! There are several structs that are useful for slices, such as `Items`, which
//! represents iteration over a slice.
//!
//! ## Traits
//!
//! A number of traits add methods that allow you to accomplish tasks
//! with slices, the most important being `SlicePrelude`. Other traits
//! apply only to slices of elements satisfying certain bounds (like
//! `Ord`).
//!
//! An example is the `slice` method which enables slicing syntax `[a..b]` that
//! returns an immutable "view" into a `Vec` or another slice from the index
//! interval `[a, b)`:
//!
//! ```rust
//! #![feature(slicing_syntax)]
//! fn main() {
//! let numbers = [0i, 1i, 2i];
//! let last_numbers = numbers[1..3];
//! // last_numbers is now &[1i, 2i]
//! }
//! ```
//!
//! ## Implementations of other traits
//!
//! There are several implementations of common traits for slices. Some examples
//! include:
//!
//! * `Clone`
//! * `Eq`, `Ord` - for immutable slices whose element type are `Eq` or `Ord`.
//! * `Hash` - for slices whose element type is `Hash`
//!
//! ## Iteration
//!
//! The method `iter()` returns an iteration value for a slice. The iterator
//! yields references to the slice's elements, so if the element
//! type of the slice is `int`, the element type of the iterator is `&int`.
//!
//! ```rust
//! let numbers = [0i, 1i, 2i];
//! for &x in numbers.iter() {
//! println!("{} is a number!", x);
//! }
//! ```
//!
//! * `.iter_mut()` returns an iterator that allows modifying each value.
//! * Further iterators exist that split, chunk or permute the slice.
#![doc(primitive = "slice")]
use alloc::boxed::Box;
use core::cmp;
use core::kinds::Sized;
use core::mem::size_of;
use core::mem;
use core::prelude::{Clone, Greater, Iterator, Less, None, Option};
use core::prelude::{Ord, Ordering, RawPtr, Some, range};
use core::ptr;
use core::iter::{range_step, MultiplicativeIterator};
use vec::Vec;
pub use core::slice::{Chunks, AsSlice, SlicePrelude, PartialEqSlicePrelude};
pub use core::slice::{OrdSlicePrelude, SlicePrelude, Items, MutItems};
pub use core::slice::{ImmutableIntSlice, MutableIntSlice};
pub use core::slice::{MutSplits, MutChunks, Splits};
pub use core::slice::{bytes, mut_ref_slice, ref_slice, CloneSlicePrelude};
pub use core::slice::{Found, NotFound};
// Functional utilities
#[allow(missing_docs)]
pub trait VectorVector<T> for Sized? {
// FIXME #5898: calling these .concat and .connect conflicts with
// StrVector::con{cat,nect}, since they have generic contents.
/// Flattens a vector of vectors of `T` into a single `Vec<T>`.
fn concat_vec(&self) -> Vec<T>;
/// Concatenate a vector of vectors, placing a given separator between each.
fn connect_vec(&self, sep: &T) -> Vec<T>;
}
impl<T: Clone, V: AsSlice<T>> VectorVector<T> for [V] {
fn concat_vec(&self) -> Vec<T> {
let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
let mut result = Vec::with_capacity(size);
for v in self.iter() {
result.push_all(v.as_slice())
}
result
}
fn connect_vec(&self, sep: &T) -> Vec<T> {
let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
let mut result = Vec::with_capacity(size + self.len());
let mut first = true;
for v in self.iter() {
if first { first = false } else { result.push(sep.clone()) }
result.push_all(v.as_slice())
}
result
}
}
/// An iterator that yields the element swaps needed to produce
/// a sequence of all possible permutations for an indexed sequence of
/// elements. Each permutation is only a single swap apart.
///
/// The Steinhaus-Johnson-Trotter algorithm is used.
///
/// Generates even and odd permutations alternately.
///
/// The last generated swap is always (0, 1), and it returns the
/// sequence to its initial order.
pub struct ElementSwaps {
sdir: Vec<SizeDirection>,
/// If `true`, emit the last swap that returns the sequence to initial
/// state.
emit_reset: bool,
swaps_made : uint,
}
impl ElementSwaps {
/// Creates an `ElementSwaps` iterator for a sequence of `length` elements.
pub fn new(length: uint) -> ElementSwaps {
// Initialize `sdir` with a direction that position should move in
// (all negative at the beginning) and the `size` of the
// element (equal to the original index).
ElementSwaps{
emit_reset: true,
sdir: range(0, length).map(|i| SizeDirection{ size: i, dir: Neg }).collect(),
swaps_made: 0
}
}
}
enum Direction { Pos, Neg }
/// An `Index` and `Direction` together.
struct SizeDirection {
size: uint,
dir: Direction,
}
impl Iterator<(uint, uint)> for ElementSwaps {
#[inline]
fn next(&mut self) -> Option<(uint, uint)> {
fn new_pos(i: uint, s: Direction) -> uint {
i + match s { Pos => 1, Neg => -1 }
}
// Find the index of the largest mobile element:
// The direction should point into the vector, and the
// swap should be with a smaller `size` element.
let max = self.sdir.iter().map(|&x| x).enumerate()
.filter(|&(i, sd)|
new_pos(i, sd.dir) < self.sdir.len() &&
self.sdir[new_pos(i, sd.dir)].size < sd.size)
.max_by(|&(_, sd)| sd.size);
match max {
Some((i, sd)) => {
let j = new_pos(i, sd.dir);
self.sdir.as_mut_slice().swap(i, j);
// Swap the direction of each larger SizeDirection
for x in self.sdir.iter_mut() {
if x.size > sd.size {
x.dir = match x.dir { Pos => Neg, Neg => Pos };
}
}
self.swaps_made += 1;
Some((i, j))
},
None => if self.emit_reset {
self.emit_reset = false;
if self.sdir.len() > 1 {
// The last swap
self.swaps_made += 1;
Some((0, 1))
} else {
// Vector is of the form [] or [x], and the only permutation is itself
self.swaps_made += 1;
Some((0,0))
}
} else { None }
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
// For a vector of size n, there are exactly n! permutations.
let n = range(2, self.sdir.len() + 1).product(1);
(n - self.swaps_made, Some(n - self.swaps_made))
}
}
/// An iterator that uses `ElementSwaps` to iterate through
/// all possible permutations of a vector.
///
/// The first iteration yields a clone of the vector as it is,
/// then each successive element is the vector with one
/// swap applied.
///
/// Generates even and odd permutations alternately.
pub struct Permutations<T> {
swaps: ElementSwaps,
v: Vec<T>,
}
impl<T: Clone> Iterator<Vec<T>> for Permutations<T> {
#[inline]
fn next(&mut self) -> Option<Vec<T>> {
match self.swaps.next() {
None => None,
Some((0,0)) => Some(self.v.clone()),
Some((a, b)) => {
let elt = self.v.clone();
self.v.as_mut_slice().swap(a, b);
Some(elt)
}
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
self.swaps.size_hint()
}
}
/// Extension methods for boxed slices.
pub trait BoxedSlicePrelude<T> {
/// Convert `self` into a vector without clones or allocation.
fn into_vec(self) -> Vec<T>;
}
impl<T> BoxedSlicePrelude<T> for Box<[T]> {
#[experimental]
fn into_vec(mut self) -> Vec<T> {
unsafe {
let xs = Vec::from_raw_parts(self.as_mut_ptr(), self.len(), self.len());
mem::forget(self);
xs
}
}
}
/// Allocating extension methods for slices containing `Clone` elements.
pub trait CloneSliceAllocPrelude<T> for Sized? {
/// Copies `self` into a new `Vec`.
fn to_vec(&self) -> Vec<T>;
/// Partitions the vector into two vectors `(a, b)`, where all
/// elements of `a` satisfy `f` and all elements of `b` do not.
fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>);
/// Creates an iterator that yields every possible permutation of the
/// vector in succession.
///
/// # Example
///
/// ```rust
/// let v = [1i, 2, 3];
/// let mut perms = v.permutations();
///
/// for p in perms {
/// println!("{}", p);
/// }
/// ```
///
/// # Example 2: iterating through permutations one by one.
///
/// ```rust
/// let v = [1i, 2, 3];
/// let mut perms = v.permutations();
///
/// assert_eq!(Some(vec![1i, 2, 3]), perms.next());
/// assert_eq!(Some(vec![1i, 3, 2]), perms.next());
/// assert_eq!(Some(vec![3i, 1, 2]), perms.next());
/// ```
fn permutations(&self) -> Permutations<T>;
}
impl<T: Clone> CloneSliceAllocPrelude<T> for [T] {
/// Returns a copy of `v`.
#[inline]
fn to_vec(&self) -> Vec<T> {
let mut vector = Vec::with_capacity(self.len());
vector.push_all(self);
vector
}
#[inline]
fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
let mut lefts = Vec::new();
let mut rights = Vec::new();
for elt in self.iter() {
if f(elt) {
lefts.push((*elt).clone());
} else {
rights.push((*elt).clone());
}
}
(lefts, rights)
}
/// Returns an iterator over all permutations of a vector.
fn permutations(&self) -> Permutations<T> {
Permutations{
swaps: ElementSwaps::new(self.len()),
v: self.to_vec(),
}
}
}
fn insertion_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
let len = v.len() as int;
let buf_v = v.as_mut_ptr();
// 1 <= i < len;
for i in range(1, len) {
// j satisfies: 0 <= j <= i;
let mut j = i;
unsafe {
// `i` is in bounds.
let read_ptr = buf_v.offset(i) as *const T;
// find where to insert, we need to do strict <,
// rather than <=, to maintain stability.
// 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
while j > 0 &&
compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
j -= 1;
}
// shift everything to the right, to make space to
// insert this value.
// j + 1 could be `len` (for the last `i`), but in
// that case, `i == j` so we don't copy. The
// `.offset(j)` is always in bounds.
if i != j {
let tmp = ptr::read(read_ptr);
ptr::copy_memory(buf_v.offset(j + 1),
&*buf_v.offset(j),
(i - j) as uint);
ptr::copy_nonoverlapping_memory(buf_v.offset(j),
&tmp as *const T,
1);
mem::forget(tmp);
}
}
}
}
fn merge_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
// warning: this wildly uses unsafe.
static BASE_INSERTION: uint = 32;
static LARGE_INSERTION: uint = 16;
// FIXME #12092: smaller insertion runs seems to make sorting
// vectors of large elements a little faster on some platforms,
// but hasn't been tested/tuned extensively
let insertion = if size_of::<T>() <= 16 {
BASE_INSERTION
} else {
LARGE_INSERTION
};
let len = v.len();
// short vectors get sorted in-place via insertion sort to avoid allocations
if len <= insertion {
insertion_sort(v, compare);
return;
}
// allocate some memory to use as scratch memory, we keep the
// length 0 so we can keep shallow copies of the contents of `v`
// without risking the dtors running on an object twice if
// `compare` fails.
let mut working_space = Vec::with_capacity(2 * len);
// these both are buffers of length `len`.
let mut buf_dat = working_space.as_mut_ptr();
let mut buf_tmp = unsafe {buf_dat.offset(len as int)};
// length `len`.
let buf_v = v.as_ptr();
// step 1. sort short runs with insertion sort. This takes the
// values from `v` and sorts them into `buf_dat`, leaving that
// with sorted runs of length INSERTION.
// We could hardcode the sorting comparisons here, and we could
// manipulate/step the pointers themselves, rather than repeatedly
// .offset-ing.
for start in range_step(0, len, insertion) {
// start <= i < len;
for i in range(start, cmp::min(start + insertion, len)) {
// j satisfies: start <= j <= i;
let mut j = i as int;
unsafe {
// `i` is in bounds.
let read_ptr = buf_v.offset(i as int);
// find where to insert, we need to do strict <,
// rather than <=, to maintain stability.
// start <= j - 1 < len, so .offset(j - 1) is in
// bounds.
while j > start as int &&
compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
j -= 1;
}
// shift everything to the right, to make space to
// insert this value.
// j + 1 could be `len` (for the last `i`), but in
// that case, `i == j` so we don't copy. The
// `.offset(j)` is always in bounds.
ptr::copy_memory(buf_dat.offset(j + 1),
&*buf_dat.offset(j),
i - j as uint);
ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
}
}
}
// step 2. merge the sorted runs.
let mut width = insertion;
while width < len {
// merge the sorted runs of length `width` in `buf_dat` two at
// a time, placing the result in `buf_tmp`.
// 0 <= start <= len.
for start in range_step(0, len, 2 * width) {
// manipulate pointers directly for speed (rather than
// using a `for` loop with `range` and `.offset` inside
// that loop).
unsafe {
// the end of the first run & start of the
// second. Offset of `len` is defined, since this is
// precisely one byte past the end of the object.
let right_start = buf_dat.offset(cmp::min(start + width, len) as int);
// end of the second. Similar reasoning to the above re safety.
let right_end_idx = cmp::min(start + 2 * width, len);
let right_end = buf_dat.offset(right_end_idx as int);
// the pointers to the elements under consideration
// from the two runs.
// both of these are in bounds.
let mut left = buf_dat.offset(start as int);
let mut right = right_start;
// where we're putting the results, it is a run of
// length `2*width`, so we step it once for each step
// of either `left` or `right`. `buf_tmp` has length
// `len`, so these are in bounds.
let mut out = buf_tmp.offset(start as int);
let out_end = buf_tmp.offset(right_end_idx as int);
while out < out_end {
// Either the left or the right run are exhausted,
// so just copy the remainder from the other run
// and move on; this gives a huge speed-up (order
// of 25%) for mostly sorted vectors (the best
// case).
if left == right_start {
// the number remaining in this run.
let elems = (right_end as uint - right as uint) / mem::size_of::<T>();
ptr::copy_nonoverlapping_memory(out, &*right, elems);
break;
} else if right == right_end {
let elems = (right_start as uint - left as uint) / mem::size_of::<T>();
ptr::copy_nonoverlapping_memory(out, &*left, elems);
break;
}
// check which side is smaller, and that's the
// next element for the new run.
// `left < right_start` and `right < right_end`,
// so these are valid.
let to_copy = if compare(&*left, &*right) == Greater {
step(&mut right)
} else {
step(&mut left)
};
ptr::copy_nonoverlapping_memory(out, &*to_copy, 1);
step(&mut out);
}
}
}
mem::swap(&mut buf_dat, &mut buf_tmp);
width *= 2;
}
// write the result to `v` in one go, so that there are never two copies
// of the same object in `v`.
unsafe {
ptr::copy_nonoverlapping_memory(v.as_mut_ptr(), &*buf_dat, len);
}
// increment the pointer, returning the old pointer.
#[inline(always)]
unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
let old = *ptr;
*ptr = ptr.offset(1);
old
}
}
/// Allocating extension methods for slices on Ord values.
#[experimental = "likely to merge with other traits"]
pub trait OrdSliceAllocPrelude<T> for Sized? {
/// Sorts the slice, in place.
///
/// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
///
/// # Example
///
/// ```rust
/// let mut v = [-5i, 4, 1, -3, 2];
///
/// v.sort();
/// assert!(v == [-5i, -3, 1, 2, 4]);
/// ```
#[experimental]
fn sort(&mut self);
}
impl<T: Ord> OrdSliceAllocPrelude<T> for [T] {
#[experimental]
#[inline]
fn sort(&mut self) {
self.sort_by(|a, b| a.cmp(b))
}
}
/// Allocating extension methods for slices.
#[experimental = "likely to merge with other traits"]
pub trait SliceAllocPrelude<T> for Sized? {
/// Sorts the slice, in place, using `compare` to compare
/// elements.
///
/// This sort is `O(n log n)` worst-case and stable, but allocates
/// approximately `2 * n`, where `n` is the length of `self`.
///
/// # Example
///
/// ```rust
/// let mut v = [5i, 4, 1, 3, 2];
/// v.sort_by(|a, b| a.cmp(b));
/// assert!(v == [1, 2, 3, 4, 5]);
///
/// // reverse sorting
/// v.sort_by(|a, b| b.cmp(a));
/// assert!(v == [5, 4, 3, 2, 1]);
/// ```
fn sort_by(&mut self, compare: |&T, &T| -> Ordering);
/// Consumes `src` and moves as many elements as it can into `self`
/// from the range [start,end).
///
/// Returns the number of elements copied (the shorter of `self.len()`
/// and `end - start`).
///
/// # Arguments
///
/// * src - A mutable vector of `T`
/// * start - The index into `src` to start copying from
/// * end - The index into `src` to stop copying from
///
/// # Example
///
/// ```rust
/// let mut a = [1i, 2, 3, 4, 5];
/// let b = vec![6i, 7, 8];
/// let num_moved = a.move_from(b, 0, 3);
/// assert_eq!(num_moved, 3);
/// assert!(a == [6i, 7, 8, 4, 5]);
/// ```
fn move_from(&mut self, src: Vec<T>, start: uint, end: uint) -> uint;
}
impl<T> SliceAllocPrelude<T> for [T] {
#[inline]
fn sort_by(&mut self, compare: |&T, &T| -> Ordering) {
merge_sort(self, compare)
}
#[inline]
fn move_from(&mut self, mut src: Vec<T>, start: uint, end: uint) -> uint {
for (a, b) in self.iter_mut().zip(src[mut start..end].iter_mut()) {
mem::swap(a, b);
}
cmp::min(self.len(), end-start)
}
}
/// Unsafe operations
pub mod raw {
pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice};
pub use core::slice::raw::{shift_ptr, pop_ptr};
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use std::default::Default;
use std::mem;
use std::prelude::*;
use std::rand::{Rng, task_rng};
use std::rc::Rc;
use std::rt;
use slice::*;
use vec::Vec;
fn square(n: uint) -> uint { n * n }
fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
#[test]
fn test_from_fn() {
// Test on-stack from_fn.
let mut v = Vec::from_fn(3u, square);
{
let v = v.as_slice();
assert_eq!(v.len(), 3u);
assert_eq!(v[0], 0u);
assert_eq!(v[1], 1u);
assert_eq!(v[2], 4u);
}
// Test on-heap from_fn.
v = Vec::from_fn(5u, square);
{
let v = v.as_slice();
assert_eq!(v.len(), 5u);
assert_eq!(v[0], 0u);
assert_eq!(v[1], 1u);
assert_eq!(v[2], 4u);
assert_eq!(v[3], 9u);
assert_eq!(v[4], 16u);
}
}
#[test]
fn test_from_elem() {
// Test on-stack from_elem.
let mut v = Vec::from_elem(2u, 10u);
{
let v = v.as_slice();
assert_eq!(v.len(), 2u);
assert_eq!(v[0], 10u);
assert_eq!(v[1], 10u);
}
// Test on-heap from_elem.
v = Vec::from_elem(6u, 20u);
{
let v = v.as_slice();
assert_eq!(v[0], 20u);
assert_eq!(v[1], 20u);
assert_eq!(v[2], 20u);
assert_eq!(v[3], 20u);
assert_eq!(v[4], 20u);
assert_eq!(v[5], 20u);
}
}
#[test]
fn test_is_empty() {
let xs: [int, ..0] = [];
assert!(xs.is_empty());
assert!(![0i].is_empty());
}
#[test]
fn test_len_divzero() {
type Z = [i8, ..0];
let v0 : &[Z] = &[];
let v1 : &[Z] = &[[]];
let v2 : &[Z] = &[[], []];
assert_eq!(mem::size_of::<Z>(), 0);
assert_eq!(v0.len(), 0);
assert_eq!(v1.len(), 1);
assert_eq!(v2.len(), 2);
}
#[test]
fn test_get() {
let mut a = vec![11i];
assert_eq!(a.as_slice().get(1), None);
a = vec![11i, 12];
assert_eq!(a.as_slice().get(1).unwrap(), &12);
a = vec![11i, 12, 13];
assert_eq!(a.as_slice().get(1).unwrap(), &12);
}
#[test]
fn test_head() {
let mut a = vec![];
assert_eq!(a.as_slice().head(), None);
a = vec![11i];
assert_eq!(a.as_slice().head().unwrap(), &11);
a = vec![11i, 12];
assert_eq!(a.as_slice().head().unwrap(), &11);
}
#[test]
fn test_head_mut() {
let mut a = vec![];
assert_eq!(a.as_mut_slice().head_mut(), None);
a = vec![11i];
assert_eq!(*a.as_mut_slice().head_mut().unwrap(), 11);
a = vec![11i, 12];
assert_eq!(*a.as_mut_slice().head_mut().unwrap(), 11);
}
#[test]
fn test_tail() {
let mut a = vec![11i];
let b: &[int] = &[];
assert_eq!(a.tail(), b);
a = vec![11i, 12];
let b: &[int] = &[12];
assert_eq!(a.tail(), b);
}
#[test]
fn test_tail_mut() {
let mut a = vec![11i];
let b: &mut [int] = &mut [];
assert!(a.as_mut_slice().tail_mut() == b);
a = vec![11i, 12];
let b: &mut [int] = &mut [12];
assert!(a.as_mut_slice().tail_mut() == b);
}
#[test]
#[should_fail]
fn test_tail_empty() {
let a: Vec<int> = vec![];
a.tail();
}
#[test]
#[should_fail]
fn test_tail_mut_empty() {
let mut a: Vec<int> = vec![];
a.as_mut_slice().tail_mut();
}
#[test]
fn test_init() {
let mut a = vec![11i];
let b: &[int] = &[];
assert_eq!(a.init(), b);
a = vec![11i, 12];
let b: &[int] = &[11];
assert_eq!(a.init(), b);
}
#[test]
fn test_init_mut() {
let mut a = vec![11i];
let b: &mut [int] = &mut [];
assert!(a.as_mut_slice().init_mut() == b);
a = vec![11i, 12];
let b: &mut [int] = &mut [11];
assert!(a.as_mut_slice().init_mut() == b);
}
#[test]
#[should_fail]
fn test_init_empty() {
let a: Vec<int> = vec![];
a.init();
}
#[test]
#[should_fail]
fn test_init_mut_empty() {
let mut a: Vec<int> = vec![];
a.as_mut_slice().init_mut();
}
#[test]
fn test_last() {
let mut a = vec![];
assert_eq!(a.as_slice().last(), None);
a = vec![11i];
assert_eq!(a.as_slice().last().unwrap(), &11);
a = vec![11i, 12];
assert_eq!(a.as_slice().last().unwrap(), &12);
}
#[test]
fn test_last_mut() {
let mut a = vec![];
assert_eq!(a.as_mut_slice().last_mut(), None);
a = vec![11i];
assert_eq!(*a.as_mut_slice().last_mut().unwrap(), 11);
a = vec![11i, 12];
assert_eq!(*a.as_mut_slice().last_mut().unwrap(), 12);
}
#[test]
fn test_slice() {
// Test fixed length vector.
let vec_fixed = [1i, 2, 3, 4];
let v_a = vec_fixed[1u..vec_fixed.len()].to_vec();
assert_eq!(v_a.len(), 3u);
let v_a = v_a.as_slice();
assert_eq!(v_a[0], 2);
assert_eq!(v_a[1], 3);
assert_eq!(v_a[2], 4);
// Test on stack.
let vec_stack: &[_] = &[1i, 2, 3];
let v_b = vec_stack[1u..3u].to_vec();
assert_eq!(v_b.len(), 2u);
let v_b = v_b.as_slice();
assert_eq!(v_b[0], 2);
assert_eq!(v_b[1], 3);
// Test `Box<[T]>`
let vec_unique = vec![1i, 2, 3, 4, 5, 6];
let v_d = vec_unique[1u..6u].to_vec();
assert_eq!(v_d.len(), 5u);
let v_d = v_d.as_slice();
assert_eq!(v_d[0], 2);
assert_eq!(v_d[1], 3);
assert_eq!(v_d[2], 4);
assert_eq!(v_d[3], 5);
assert_eq!(v_d[4], 6);
}
#[test]
fn test_slice_from() {
let vec: &[int] = &[1, 2, 3, 4];
assert_eq!(vec[0..], vec);
let b: &[int] = &[3, 4];
assert_eq!(vec[2..], b);
let b: &[int] = &[];
assert_eq!(vec[4..], b);
}
#[test]
fn test_slice_to() {
let vec: &[int] = &[1, 2, 3, 4];
assert_eq!(vec[..4], vec);
let b: &[int] = &[1, 2];
assert_eq!(vec[..2], b);
let b: &[int] = &[];
assert_eq!(vec[..0], b);
}
#[test]
fn test_pop() {
let mut v = vec![5i];
let e = v.pop();
assert_eq!(v.len(), 0);
assert_eq!(e, Some(5));
let f = v.pop();
assert_eq!(f, None);
let g = v.pop();
assert_eq!(g, None);
}
#[test]
fn test_swap_remove() {
let mut v = vec![1i, 2, 3, 4, 5];
let mut e = v.swap_remove(0);
assert_eq!(e, Some(1));
assert_eq!(v, vec![5i, 2, 3, 4]);
e = v.swap_remove(3);
assert_eq!(e, Some(4));
assert_eq!(v, vec![5i, 2, 3]);
e = v.swap_remove(3);
assert_eq!(e, None);
assert_eq!(v, vec![5i, 2, 3]);
}
#[test]
fn test_swap_remove_noncopyable() {
// Tests that we don't accidentally run destructors twice.
let mut v = vec![rt::exclusive::Exclusive::new(()),
rt::exclusive::Exclusive::new(()),
rt::exclusive::Exclusive::new(())];
let mut _e = v.swap_remove(0);
assert_eq!(v.len(), 2);
_e = v.swap_remove(1);
assert_eq!(v.len(), 1);
_e = v.swap_remove(0);
assert_eq!(v.len(), 0);
}
#[test]
fn test_push() {
// Test on-stack push().
let mut v = vec![];
v.push(1i);
assert_eq!(v.len(), 1u);
assert_eq!(v.as_slice()[0], 1);
// Test on-heap push().
v.push(2i);
assert_eq!(v.len(), 2u);
assert_eq!(v.as_slice()[0], 1);
assert_eq!(v.as_slice()[1], 2);
}
#[test]
fn test_grow() {
// Test on-stack grow().
let mut v = vec![];
v.grow(2u, 1i);
{
let v = v.as_slice();
assert_eq!(v.len(), 2u);
assert_eq!(v[0], 1);
assert_eq!(v[1], 1);
}
// Test on-heap grow().
v.grow(3u, 2i);
{
let v = v.as_slice();
assert_eq!(v.len(), 5u);
assert_eq!(v[0], 1);
assert_eq!(v[1], 1);
assert_eq!(v[2], 2);
assert_eq!(v[3], 2);
assert_eq!(v[4], 2);
}
}
#[test]
fn test_grow_fn() {
let mut v = vec![];
v.grow_fn(3u, square);
let v = v.as_slice();
assert_eq!(v.len(), 3u);
assert_eq!(v[0], 0u);
assert_eq!(v[1], 1u);
assert_eq!(v[2], 4u);
}