-
Notifications
You must be signed in to change notification settings - Fork 13k
/
Copy pathvec.rs
4660 lines (4110 loc) · 133 KB
/
vec.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 vector manipulation
The `vec` module contains useful code to help work with vector values.
Vectors are Rust's list type. Vectors contain zero or more values of
homogeneous types:
```rust
let int_vector = [1,2,3];
let str_vector = ["one", "two", "three"];
```
This is a big module, but for a high-level overview:
## Structs
Several structs that are useful for vectors, such as `Items`, which
represents iteration over a vector.
## Traits
A number of traits add methods that allow you to accomplish tasks with vectors.
Traits defined for the `&[T]` type (a vector slice), have methods that can be
called on either owned vectors, denoted `~[T]`, or on vector slices themselves.
These traits include `ImmutableVector`, and `MutableVector` for the `&mut [T]`
case.
An example is the method `.slice(a, b)` that returns an immutable "view" into
a vector or a vector slice from the index interval `[a, b)`:
```rust
let numbers = [0, 1, 2];
let last_numbers = numbers.slice(1, 3);
// last_numbers is now &[1, 2]
```
Traits defined for the `~[T]` type, like `OwnedVector`, can only be called
on such vectors. These methods deal with adding elements or otherwise changing
the allocation of the vector.
An example is the method `.push(element)` that will add an element at the end
of the vector:
```rust
let mut numbers = ~[0, 1, 2];
numbers.push(7);
// numbers is now ~[0, 1, 2, 7];
```
## Implementations of other traits
Vectors are a very useful type, and so there's several implementations of
traits from other modules. Some notable examples:
* `Clone`
* `Eq`, `Ord`, `TotalEq`, `TotalOrd` -- vectors can be compared,
if the element type defines the corresponding trait.
## Iteration
The method `iter()` returns an iteration value for a vector or a vector slice.
The iterator yields references to the vector's elements, so if the element
type of the vector is `int`, the element type of the iterator is `&int`.
```rust
let numbers = [0, 1, 2];
for &x in numbers.iter() {
println!("{} is a number!", x);
}
```
* `.rev_iter()` returns an iterator with the same values as `.iter()`,
but going in the reverse order, starting with the back element.
* `.mut_iter()` returns an iterator that allows modifying each value.
* `.move_iter()` converts an owned vector into an iterator that
moves out a value from the vector each iteration.
* Further iterators exist that split, chunk or permute the vector.
## Function definitions
There are a number of free functions that create or take vectors, for example:
* Creating a vector, like `from_elem` and `from_fn`
* Creating a vector with a given size: `with_capacity`
* Modifying a vector and returning it, like `append`
* Operations on paired elements, like `unzip`.
*/
#[warn(non_camel_case_types)];
use cast;
use cast::transmute;
use ops::Drop;
use clone::{Clone, DeepClone};
use container::{Container, Mutable};
use cmp::{Eq, TotalOrd, Ordering, Less, Equal, Greater};
use cmp;
use default::Default;
use fmt;
use iter::*;
use num::{CheckedAdd, Saturating, checked_next_power_of_two, div_rem};
use option::{None, Option, Some};
use ptr;
use ptr::RawPtr;
use rt::global_heap::{malloc_raw, realloc_raw, exchange_free};
use result::{Ok, Err};
use mem;
use mem::size_of;
use kinds::marker;
use uint;
use unstable::finally::try_finally;
use raw::{Repr, Slice, Vec};
/**
* Creates and initializes an owned vector.
*
* Creates an owned vector of size `n_elts` and initializes the elements
* to the value returned by the function `op`.
*/
pub fn from_fn<T>(n_elts: uint, op: |uint| -> T) -> ~[T] {
unsafe {
let mut v = with_capacity(n_elts);
let p = v.as_mut_ptr();
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| while *i < n_elts {
mem::move_val_init(
&mut(*p.offset(*i as int)),
op(*i));
*i += 1u;
},
|i| v.set_len(*i));
v
}
}
/**
* Creates and initializes an owned vector.
*
* Creates an owned vector of size `n_elts` and initializes the elements
* to the value `t`.
*/
pub fn from_elem<T:Clone>(n_elts: uint, t: T) -> ~[T] {
// FIXME (#7136): manually inline from_fn for 2x plus speedup (sadly very
// important, from_elem is a bottleneck in borrowck!). Unfortunately it
// still is substantially slower than using the unsafe
// vec::with_capacity/ptr::set_memory for primitive types.
unsafe {
let mut v = with_capacity(n_elts);
let p = v.as_mut_ptr();
let mut i = 0u;
try_finally(
&mut i, (),
|i, ()| while *i < n_elts {
mem::move_val_init(
&mut(*p.offset(*i as int)),
t.clone());
*i += 1u;
},
|i| v.set_len(*i));
v
}
}
/// Creates a new vector with a capacity of `capacity`
#[inline]
pub fn with_capacity<T>(capacity: uint) -> ~[T] {
unsafe {
let alloc = capacity * mem::nonzero_size_of::<T>();
let size = alloc + mem::size_of::<Vec<()>>();
if alloc / mem::nonzero_size_of::<T>() != capacity || size < alloc {
fail!("vector size is too large: {}", capacity);
}
let ptr = malloc_raw(size) as *mut Vec<()>;
(*ptr).alloc = alloc;
(*ptr).fill = 0;
transmute(ptr)
}
}
/**
* Builds a vector by calling a provided function with an argument
* function that pushes an element to the back of a vector.
* The initial capacity for the vector may optionally be specified.
*
* # Arguments
*
* * size - An option, maybe containing initial size of the vector to reserve
* * builder - A function that will construct the vector. It receives
* as an argument a function that will push an element
* onto the vector being constructed.
*/
#[inline]
pub fn build<A>(size: Option<uint>, builder: |push: |v: A||) -> ~[A] {
let mut vec = with_capacity(size.unwrap_or(4));
builder(|x| vec.push(x));
vec
}
/**
* Converts a pointer to A into a slice of length 1 (without copying).
*/
pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
unsafe {
transmute(Slice { data: s, len: 1 })
}
}
/**
* Converts a pointer to A into a slice of length 1 (without copying).
*/
pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
unsafe {
let ptr: *A = transmute(s);
transmute(Slice { data: ptr, len: 1 })
}
}
/// An iterator over the slices of a vector separated by elements that
/// match a predicate function.
pub struct Splits<'a, T> {
priv v: &'a [T],
priv n: uint,
priv pred: 'a |t: &T| -> bool,
priv finished: bool
}
impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
#[inline]
fn next(&mut self) -> Option<&'a [T]> {
if self.finished { return None; }
if self.n == 0 {
self.finished = true;
return Some(self.v);
}
match self.v.iter().position(|x| (self.pred)(x)) {
None => {
self.finished = true;
Some(self.v)
}
Some(idx) => {
let ret = Some(self.v.slice(0, idx));
self.v = self.v.slice(idx + 1, self.v.len());
self.n -= 1;
ret
}
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
if self.finished {
return (0, Some(0))
}
// if the predicate doesn't match anything, we yield one slice
// if it matches every element, we yield N+1 empty slices where
// N is either the number of elements or the number of splits.
match (self.v.len(), self.n) {
(0,_) => (1, Some(1)),
(_,0) => (1, Some(1)),
(l,n) => (1, cmp::min(l,n).checked_add(&1u))
}
}
}
/// An iterator over the slices of a vector separated by elements that
/// match a predicate function, from back to front.
pub struct RevSplits<'a, T> {
priv v: &'a [T],
priv n: uint,
priv pred: 'a |t: &T| -> bool,
priv finished: bool
}
impl<'a, T> Iterator<&'a [T]> for RevSplits<'a, T> {
#[inline]
fn next(&mut self) -> Option<&'a [T]> {
if self.finished { return None; }
if self.n == 0 {
self.finished = true;
return Some(self.v);
}
let pred = &mut self.pred;
match self.v.iter().rposition(|x| (*pred)(x)) {
None => {
self.finished = true;
Some(self.v)
}
Some(idx) => {
let ret = Some(self.v.slice(idx + 1, self.v.len()));
self.v = self.v.slice(0, idx);
self.n -= 1;
ret
}
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
if self.finished {
return (0, Some(0))
}
match (self.v.len(), self.n) {
(0,_) => (1, Some(1)),
(_,0) => (1, Some(1)),
(l,n) => (1, cmp::min(l,n).checked_add(&1u))
}
}
}
// Appending
/// Iterates over the `rhs` vector, copying each element and appending it to the
/// `lhs`. Afterwards, the `lhs` is then returned for use again.
#[inline]
pub fn append<T:Clone>(lhs: ~[T], rhs: &[T]) -> ~[T] {
let mut v = lhs;
v.push_all(rhs);
v
}
/// Appends one element to the vector provided. The vector itself is then
/// returned for use again.
#[inline]
pub fn append_one<T>(lhs: ~[T], x: T) -> ~[T] {
let mut v = lhs;
v.push(x);
v
}
// Functional utilities
/**
* Apply a function to each element of a vector and return a concatenation
* of each result vector
*/
pub fn flat_map<T, U>(v: &[T], f: |t: &T| -> ~[U]) -> ~[U] {
let mut result = ~[];
for elem in v.iter() { result.push_all_move(f(elem)); }
result
}
#[allow(missing_doc)]
pub trait VectorVector<T> {
// 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 vector of T.
fn concat_vec(&self) -> ~[T];
/// Concatenate a vector of vectors, placing a given separator between each.
fn connect_vec(&self, sep: &T) -> ~[T];
}
impl<'a, T: Clone, V: Vector<T>> VectorVector<T> for &'a [V] {
fn concat_vec(&self) -> ~[T] {
let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
let mut result = with_capacity(size);
for v in self.iter() {
result.push_all(v.as_slice())
}
result
}
fn connect_vec(&self, sep: &T) -> ~[T] {
let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
let mut result = 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
}
}
/**
* Convert an iterator of pairs into a pair of vectors.
*
* Returns a tuple containing two vectors where the i-th element of the first
* vector contains the first element of the i-th tuple of the input iterator,
* and the i-th element of the second vector contains the second element
* of the i-th tuple of the input iterator.
*/
pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (~[T], ~[U]) {
let (lo, _) = iter.size_hint();
let mut ts = with_capacity(lo);
let mut us = with_capacity(lo);
for (t, u) in iter {
ts.push(t);
us.push(u);
}
(ts, us)
}
/// 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 {
priv sdir: ~[SizeDirection],
/// If true, emit the last swap that returns the sequence to initial state
priv emit_reset: bool,
}
impl ElementSwaps {
/// Create 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 })
.to_owned_vec()
}
}
}
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.swap(i, j);
// Swap the direction of each larger SizeDirection
for x in self.sdir.mut_iter() {
if x.size > sd.size {
x.dir = match x.dir { Pos => Neg, Neg => Pos };
}
}
Some((i, j))
},
None => if self.emit_reset && self.sdir.len() > 1 {
self.emit_reset = false;
Some((0, 1))
} else {
None
}
}
}
}
/// 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> {
priv swaps: ElementSwaps,
priv v: ~[T],
}
impl<T: Clone> Iterator<~[T]> for Permutations<T> {
#[inline]
fn next(&mut self) -> Option<~[T]> {
match self.swaps.next() {
None => None,
Some((a, b)) => {
let elt = self.v.clone();
self.v.swap(a, b);
Some(elt)
}
}
}
}
/// An iterator over the (overlapping) slices of length `size` within
/// a vector.
#[deriving(Clone)]
pub struct Windows<'a, T> {
priv v: &'a [T],
priv size: uint
}
impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
#[inline]
fn next(&mut self) -> Option<&'a [T]> {
if self.size > self.v.len() {
None
} else {
let ret = Some(self.v.slice(0, self.size));
self.v = self.v.slice(1, self.v.len());
ret
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
if self.size > self.v.len() {
(0, Some(0))
} else {
let x = self.v.len() - self.size;
(x.saturating_add(1), x.checked_add(&1u))
}
}
}
/// An iterator over a vector in (non-overlapping) chunks (`size`
/// elements at a time).
///
/// When the vector len is not evenly divided by the chunk size,
/// the last slice of the iteration will be the remainder.
#[deriving(Clone)]
pub struct Chunks<'a, T> {
priv v: &'a [T],
priv size: uint
}
impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
#[inline]
fn next(&mut self) -> Option<&'a [T]> {
if self.v.len() == 0 {
None
} else {
let chunksz = cmp::min(self.v.len(), self.size);
let (fst, snd) = (self.v.slice_to(chunksz),
self.v.slice_from(chunksz));
self.v = snd;
Some(fst)
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
if self.v.len() == 0 {
(0, Some(0))
} else {
let (n, rem) = div_rem(self.v.len(), self.size);
let n = if rem > 0 { n+1 } else { n };
(n, Some(n))
}
}
}
impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<&'a [T]> {
if self.v.len() == 0 {
None
} else {
let remainder = self.v.len() % self.size;
let chunksz = if remainder != 0 { remainder } else { self.size };
let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz),
self.v.slice_from(self.v.len() - chunksz));
self.v = fst;
Some(snd)
}
}
}
impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
#[inline]
fn indexable(&self) -> uint {
self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
}
#[inline]
fn idx(&self, index: uint) -> Option<&'a [T]> {
if index < self.indexable() {
let lo = index * self.size;
let mut hi = lo + self.size;
if hi < lo || hi > self.v.len() { hi = self.v.len(); }
Some(self.v.slice(lo, hi))
} else {
None
}
}
}
// Equality
#[cfg(not(test))]
#[allow(missing_doc)]
pub mod traits {
use super::*;
use container::Container;
use clone::Clone;
use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Equiv};
use iter::order;
use ops::Add;
impl<'a,T:Eq> Eq for &'a [T] {
fn eq(&self, other: & &'a [T]) -> bool {
self.len() == other.len() &&
order::eq(self.iter(), other.iter())
}
fn ne(&self, other: & &'a [T]) -> bool {
self.len() != other.len() ||
order::ne(self.iter(), other.iter())
}
}
impl<T:Eq> Eq for ~[T] {
#[inline]
fn eq(&self, other: &~[T]) -> bool { self.as_slice() == *other }
#[inline]
fn ne(&self, other: &~[T]) -> bool { !self.eq(other) }
}
impl<'a,T:TotalEq> TotalEq for &'a [T] {
fn equals(&self, other: & &'a [T]) -> bool {
self.len() == other.len() &&
order::equals(self.iter(), other.iter())
}
}
impl<T:TotalEq> TotalEq for ~[T] {
#[inline]
fn equals(&self, other: &~[T]) -> bool { self.as_slice().equals(&other.as_slice()) }
}
impl<'a,T:Eq, V: Vector<T>> Equiv<V> for &'a [T] {
#[inline]
fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
}
impl<'a,T:Eq, V: Vector<T>> Equiv<V> for ~[T] {
#[inline]
fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
}
impl<'a,T:TotalOrd> TotalOrd for &'a [T] {
fn cmp(&self, other: & &'a [T]) -> Ordering {
order::cmp(self.iter(), other.iter())
}
}
impl<T: TotalOrd> TotalOrd for ~[T] {
#[inline]
fn cmp(&self, other: &~[T]) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
}
impl<'a, T: Eq + Ord> Ord for &'a [T] {
fn lt(&self, other: & &'a [T]) -> bool {
order::lt(self.iter(), other.iter())
}
#[inline]
fn le(&self, other: & &'a [T]) -> bool {
order::le(self.iter(), other.iter())
}
#[inline]
fn ge(&self, other: & &'a [T]) -> bool {
order::ge(self.iter(), other.iter())
}
#[inline]
fn gt(&self, other: & &'a [T]) -> bool {
order::gt(self.iter(), other.iter())
}
}
impl<T: Eq + Ord> Ord for ~[T] {
#[inline]
fn lt(&self, other: &~[T]) -> bool { self.as_slice() < other.as_slice() }
#[inline]
fn le(&self, other: &~[T]) -> bool { self.as_slice() <= other.as_slice() }
#[inline]
fn ge(&self, other: &~[T]) -> bool { self.as_slice() >= other.as_slice() }
#[inline]
fn gt(&self, other: &~[T]) -> bool { self.as_slice() > other.as_slice() }
}
impl<'a,T:Clone, V: Vector<T>> Add<V, ~[T]> for &'a [T] {
#[inline]
fn add(&self, rhs: &V) -> ~[T] {
let mut res = with_capacity(self.len() + rhs.as_slice().len());
res.push_all(*self);
res.push_all(rhs.as_slice());
res
}
}
impl<T:Clone, V: Vector<T>> Add<V, ~[T]> for ~[T] {
#[inline]
fn add(&self, rhs: &V) -> ~[T] {
self.as_slice() + rhs.as_slice()
}
}
}
#[cfg(test)]
pub mod traits {}
/// Any vector that can be represented as a slice.
pub trait Vector<T> {
/// Work with `self` as a slice.
fn as_slice<'a>(&'a self) -> &'a [T];
}
impl<'a,T> Vector<T> for &'a [T] {
#[inline(always)]
fn as_slice<'a>(&'a self) -> &'a [T] { *self }
}
impl<T> Vector<T> for ~[T] {
#[inline(always)]
fn as_slice<'a>(&'a self) -> &'a [T] { let v: &'a [T] = *self; v }
}
impl<'a, T> Container for &'a [T] {
/// Returns the length of a vector
#[inline]
fn len(&self) -> uint {
self.repr().len
}
}
impl<T> Container for ~[T] {
/// Returns the length of a vector
#[inline]
fn len(&self) -> uint {
self.as_slice().len()
}
}
/// Extension methods for vector slices with cloneable elements
pub trait CloneableVector<T> {
/// Copy `self` into a new owned vector
fn to_owned(&self) -> ~[T];
/// Convert `self` into an owned vector, not making a copy if possible.
fn into_owned(self) -> ~[T];
}
/// Extension methods for vector slices
impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
/// Returns a copy of `v`.
#[inline]
fn to_owned(&self) -> ~[T] {
let mut result = with_capacity(self.len());
for e in self.iter() {
result.push((*e).clone());
}
result
}
#[inline(always)]
fn into_owned(self) -> ~[T] { self.to_owned() }
}
/// Extension methods for owned vectors
impl<T: Clone> CloneableVector<T> for ~[T] {
#[inline]
fn to_owned(&self) -> ~[T] { self.clone() }
#[inline(always)]
fn into_owned(self) -> ~[T] { self }
}
/// Extension methods for vectors
pub trait ImmutableVector<'a, T> {
/**
* Returns a slice of self between `start` and `end`.
*
* Fails when `start` or `end` point outside the bounds of self,
* or when `start` > `end`.
*/
fn slice(&self, start: uint, end: uint) -> &'a [T];
/**
* Returns a slice of self from `start` to the end of the vec.
*
* Fails when `start` points outside the bounds of self.
*/
fn slice_from(&self, start: uint) -> &'a [T];
/**
* Returns a slice of self from the start of the vec to `end`.
*
* Fails when `end` points outside the bounds of self.
*/
fn slice_to(&self, end: uint) -> &'a [T];
/// Returns an iterator over the vector
fn iter(self) -> Items<'a, T>;
/// Returns a reversed iterator over a vector
fn rev_iter(self) -> RevItems<'a, T>;
/// Returns an iterator over the subslices of the vector which are
/// separated by elements that match `pred`. The matched element
/// is not contained in the subslices.
fn split(self, pred: 'a |&T| -> bool) -> Splits<'a, T>;
/// Returns an iterator over the subslices of the vector which are
/// separated by elements that match `pred`, limited to splitting
/// at most `n` times. The matched element is not contained in
/// the subslices.
fn splitn(self, n: uint, pred: 'a |&T| -> bool) -> Splits<'a, T>;
/// Returns an iterator over the subslices of the vector which are
/// separated by elements that match `pred`. This starts at the
/// end of the vector and works backwards. The matched element is
/// not contained in the subslices.
fn rsplit(self, pred: 'a |&T| -> bool) -> RevSplits<'a, T>;
/// Returns an iterator over the subslices of the vector which are
/// separated by elements that match `pred` limited to splitting
/// at most `n` times. This starts at the end of the vector and
/// works backwards. The matched element is not contained in the
/// subslices.
fn rsplitn(self, n: uint, pred: 'a |&T| -> bool) -> RevSplits<'a, T>;
/**
* Returns an iterator over all contiguous windows of length
* `size`. The windows overlap. If the vector is shorter than
* `size`, the iterator returns no values.
*
* # Failure
*
* Fails if `size` is 0.
*
* # Example
*
* Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`,
* `[3,4]`):
*
* ```rust
* let v = &[1,2,3,4];
* for win in v.windows(2) {
* println!("{:?}", win);
* }
* ```
*
*/
fn windows(self, size: uint) -> Windows<'a, T>;
/**
*
* Returns an iterator over `size` elements of the vector at a
* time. The chunks do not overlap. If `size` does not divide the
* length of the vector, then the last chunk will not have length
* `size`.
*
* # Failure
*
* Fails if `size` is 0.
*
* # Example
*
* Print the vector two elements at a time (i.e. `[1,2]`,
* `[3,4]`, `[5]`):
*
* ```rust
* let v = &[1,2,3,4,5];
* for win in v.chunks(2) {
* println!("{:?}", win);
* }
* ```
*
*/
fn chunks(self, size: uint) -> Chunks<'a, T>;
/// Returns the element of a vector at the given index, or `None` if the
/// index is out of bounds
fn get(&self, index: uint) -> Option<&'a T>;
/// Returns the first element of a vector, or `None` if it is empty
fn head(&self) -> Option<&'a T>;
/// Returns all but the first element of a vector
fn tail(&self) -> &'a [T];
/// Returns all but the first `n' elements of a vector
fn tailn(&self, n: uint) -> &'a [T];
/// Returns all but the last element of a vector
fn init(&self) -> &'a [T];
/// Returns all but the last `n' elements of a vector
fn initn(&self, n: uint) -> &'a [T];
/// Returns the last element of a vector, or `None` if it is empty.
fn last(&self) -> Option<&'a T>;
/**
* Apply a function to each element of a vector and return a concatenation
* of each result vector
*/
fn flat_map<U>(&self, f: |t: &T| -> ~[U]) -> ~[U];
/// Returns a pointer to the element at the given index, without doing
/// bounds checking.
unsafe fn unsafe_ref(self, index: uint) -> &'a T;
/**
* Returns an unsafe pointer to the vector's buffer
*
* The caller must ensure that the vector outlives the pointer this
* function returns, or else it will end up pointing to garbage.
*
* Modifying the vector may cause its buffer to be reallocated, which
* would also make any pointers to it invalid.
*/
fn as_ptr(&self) -> *T;
/**
* Binary search a sorted vector with a comparator function.
*
* The comparator function should implement an order consistent
* with the sort order of the underlying vector, returning an
* order code that indicates whether its argument is `Less`,
* `Equal` or `Greater` the desired target.
*
* Returns the index where the comparator returned `Equal`, or `None` if
* not found.
*/
fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>;
/// Deprecated, use iterators where possible
/// (`self.iter().map(f)`). Apply a function to each element
/// of a vector and return the results.
fn map<U>(&self, |t: &T| -> U) -> ~[U];
/**
* Returns a mutable reference to the first element in this slice
* and adjusts the slice in place so that it no longer contains
* that element. O(1).
*
* Equivalent to:
*
* ```ignore
* if self.len() == 0 { return None }
* let head = &self[0];
* *self = self.slice_from(1);
* Some(head)
* ```
*
* Returns `None` if vector is empty
*/
fn shift_ref(&mut self) -> Option<&'a T>;
/**
* Returns a mutable reference to the last element in this slice
* and adjusts the slice in place so that it no longer contains
* that element. O(1).
*
* Equivalent to:
*
* ```ignore
* if self.len() == 0 { return None; }
* let tail = &self[self.len() - 1];
* *self = self.slice_to(self.len() - 1);
* Some(tail)
* ```
*
* Returns `None` if slice is empty.
*/
fn pop_ref(&mut self) -> Option<&'a T>;
}
impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
#[inline]
fn slice(&self, start: uint, end: uint) -> &'a [T] {
assert!(start <= end);
assert!(end <= self.len());
unsafe {
transmute(Slice {
data: self.as_ptr().offset(start as int),
len: (end - start)
})
}
}