-
Notifications
You must be signed in to change notification settings - Fork 13.2k
/
Copy pathvec.rs
4041 lines (3577 loc) · 110 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-2013 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.
//! Vectors
#[warn(non_camel_case_types)];
use cast::transmute;
use cast;
use container::{Container, Mutable};
use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Less, Equal, Greater};
use clone::Clone;
use old_iter;
use iterator::{FromIterator, Iterator, IteratorUtil};
use iter::FromIter;
use kinds::Copy;
use libc;
use num::Zero;
use option::{None, Option, Some};
use ptr::to_unsafe_ptr;
use ptr;
use ptr::RawPtr;
use sys;
use sys::size_of;
use uint;
use unstable::intrinsics;
use vec;
use util;
#[cfg(not(test))] use cmp::Equiv;
pub mod rustrt {
use libc;
use sys;
use vec::raw;
#[abi = "cdecl"]
pub extern {
// These names are terrible. reserve_shared applies
// to ~[] and reserve_shared_actual applies to @[].
#[fast_ffi]
unsafe fn vec_reserve_shared(t: *sys::TypeDesc,
v: **raw::VecRepr,
n: libc::size_t);
#[fast_ffi]
unsafe fn vec_reserve_shared_actual(t: *sys::TypeDesc,
v: **raw::VecRepr,
n: libc::size_t);
}
}
/// Returns true if two vectors have the same length
pub fn same_length<T, U>(xs: &const [T], ys: &const [U]) -> bool {
xs.len() == ys.len()
}
/**
* Reserves capacity for exactly `n` elements in the given vector.
*
* If the capacity for `v` is already equal to or greater than the requested
* capacity, then no action is taken.
*
* # Arguments
*
* * v - A vector
* * n - The number of elements to reserve space for
*/
#[inline]
pub fn reserve<T>(v: &mut ~[T], n: uint) {
// Only make the (slow) call into the runtime if we have to
use managed;
if capacity(v) < n {
unsafe {
let ptr: **raw::VecRepr = cast::transmute(v);
let td = sys::get_type_desc::<T>();
if ((**ptr).box_header.ref_count ==
managed::raw::RC_MANAGED_UNIQUE) {
rustrt::vec_reserve_shared_actual(td, ptr, n as libc::size_t);
} else {
rustrt::vec_reserve_shared(td, ptr, n as libc::size_t);
}
}
}
}
/**
* Reserves capacity for at least `n` elements in the given vector.
*
* This function will over-allocate in order to amortize the allocation costs
* in scenarios where the caller may need to repeatedly reserve additional
* space.
*
* If the capacity for `v` is already equal to or greater than the requested
* capacity, then no action is taken.
*
* # Arguments
*
* * v - A vector
* * n - The number of elements to reserve space for
*/
pub fn reserve_at_least<T>(v: &mut ~[T], n: uint) {
reserve(v, uint::next_power_of_two(n));
}
/// Returns the number of elements the vector can hold without reallocating
#[inline]
pub fn capacity<T>(v: &const ~[T]) -> uint {
unsafe {
let repr: **raw::VecRepr = transmute(v);
(**repr).unboxed.alloc / sys::nonzero_size_of::<T>()
}
}
/**
* 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: old_iter::InitOp<T>) -> ~[T] {
unsafe {
let mut v = with_capacity(n_elts);
do as_mut_buf(v) |p, _len| {
let mut i: uint = 0u;
while i < n_elts {
intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i)), op(i));
i += 1u;
}
}
raw::set_len(&mut v, n_elts);
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:Copy>(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);
do as_mut_buf(v) |p, _len| {
let mut i = 0u;
while i < n_elts {
intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i)), copy t);
i += 1u;
}
}
raw::set_len(&mut v, n_elts);
v
}
}
/// Creates a new unique vector with the same contents as the slice
pub fn to_owned<T:Copy>(t: &[T]) -> ~[T] {
from_fn(t.len(), |i| copy t[i])
}
/// Creates a new vector with a capacity of `capacity`
pub fn with_capacity<T>(capacity: uint) -> ~[T] {
let mut vec = ~[];
reserve(&mut vec, capacity);
vec
}
/**
* Builds a vector by calling a provided function with an argument
* function that pushes an element to the back of a vector.
* This version takes an initial capacity for the vector.
*
* # Arguments
*
* * size - An 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_sized<A>(size: uint, builder: &fn(push: &fn(v: A))) -> ~[A] {
let mut vec = with_capacity(size);
builder(|x| vec.push(x));
vec
}
/**
* Builds a vector by calling a provided function with an argument
* function that pushes an element to the back of a vector.
*
* # Arguments
*
* * 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>(builder: &fn(push: &fn(v: A))) -> ~[A] {
build_sized(4, builder)
}
/**
* Builds a vector by calling a provided function with an argument
* function that pushes an element to the back of a vector.
* This version takes an initial size for the vector.
*
* # 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_sized_opt<A>(size: Option<uint>,
builder: &fn(push: &fn(v: A)))
-> ~[A] {
build_sized(size.get_or_default(4), builder)
}
// Accessors
/// Returns the first element of a vector
pub fn head<'r,T>(v: &'r [T]) -> &'r T {
if v.len() == 0 { fail!("head: empty vector") }
&v[0]
}
/// Returns `Some(x)` where `x` is the first element of the slice `v`,
/// or `None` if the vector is empty.
pub fn head_opt<'r,T>(v: &'r [T]) -> Option<&'r T> {
if v.len() == 0 { None } else { Some(&v[0]) }
}
/// Returns a vector containing all but the first element of a slice
pub fn tail<'r,T>(v: &'r [T]) -> &'r [T] { slice(v, 1, v.len()) }
/// Returns a vector containing all but the first `n` elements of a slice
pub fn tailn<'r,T>(v: &'r [T], n: uint) -> &'r [T] { slice(v, n, v.len()) }
/// Returns a vector containing all but the last element of a slice
pub fn init<'r,T>(v: &'r [T]) -> &'r [T] { slice(v, 0, v.len() - 1) }
/// Returns a vector containing all but the last `n' elements of a slice
pub fn initn<'r,T>(v: &'r [T], n: uint) -> &'r [T] {
slice(v, 0, v.len() - n)
}
/// Returns the last element of the slice `v`, failing if the slice is empty.
pub fn last<'r,T>(v: &'r [T]) -> &'r T {
if v.len() == 0 { fail!("last: empty vector") }
&v[v.len() - 1]
}
/// Returns `Some(x)` where `x` is the last element of the slice `v`, or
/// `None` if the vector is empty.
pub fn last_opt<'r,T>(v: &'r [T]) -> Option<&'r T> {
if v.len() == 0 { None } else { Some(&v[v.len() - 1]) }
}
/// Return a slice that points into another slice.
#[inline]
pub fn slice<'r,T>(v: &'r [T], start: uint, end: uint) -> &'r [T] {
assert!(start <= end);
assert!(end <= v.len());
do as_imm_buf(v) |p, _len| {
unsafe {
transmute((ptr::offset(p, start),
(end - start) * sys::nonzero_size_of::<T>()))
}
}
}
/// Return a slice that points into another slice.
#[inline]
pub fn mut_slice<'r,T>(v: &'r mut [T], start: uint, end: uint)
-> &'r mut [T] {
assert!(start <= end);
assert!(end <= v.len());
do as_mut_buf(v) |p, _len| {
unsafe {
transmute((ptr::mut_offset(p, start),
(end - start) * sys::nonzero_size_of::<T>()))
}
}
}
/// Return a slice that points into another slice.
#[inline]
pub fn const_slice<'r,T>(v: &'r const [T], start: uint, end: uint)
-> &'r const [T] {
assert!(start <= end);
assert!(end <= v.len());
do as_const_buf(v) |p, _len| {
unsafe {
transmute((ptr::const_offset(p, start),
(end - start) * sys::nonzero_size_of::<T>()))
}
}
}
/// Copies
/// Split the vector `v` by applying each element against the predicate `f`.
pub fn split<T:Copy>(v: &[T], f: &fn(t: &T) -> bool) -> ~[~[T]] {
let ln = v.len();
if (ln == 0u) { return ~[] }
let mut start = 0u;
let mut result = ~[];
while start < ln {
match position_between(v, start, ln, f) {
None => break,
Some(i) => {
result.push(slice(v, start, i).to_owned());
start = i + 1u;
}
}
}
result.push(slice(v, start, ln).to_owned());
result
}
/**
* Split the vector `v` by applying each element against the predicate `f` up
* to `n` times.
*/
pub fn splitn<T:Copy>(v: &[T], n: uint, f: &fn(t: &T) -> bool) -> ~[~[T]] {
let ln = v.len();
if (ln == 0u) { return ~[] }
let mut start = 0u;
let mut count = n;
let mut result = ~[];
while start < ln && count > 0u {
match position_between(v, start, ln, f) {
None => break,
Some(i) => {
result.push(slice(v, start, i).to_owned());
// Make sure to skip the separator.
start = i + 1u;
count -= 1u;
}
}
}
result.push(slice(v, start, ln).to_owned());
result
}
/**
* Reverse split the vector `v` by applying each element against the predicate
* `f`.
*/
pub fn rsplit<T:Copy>(v: &[T], f: &fn(t: &T) -> bool) -> ~[~[T]] {
let ln = v.len();
if (ln == 0) { return ~[] }
let mut end = ln;
let mut result = ~[];
while end > 0 {
match rposition_between(v, 0, end, f) {
None => break,
Some(i) => {
result.push(slice(v, i + 1, end).to_owned());
end = i;
}
}
}
result.push(slice(v, 0u, end).to_owned());
reverse(result);
result
}
/**
* Reverse split the vector `v` by applying each element against the predicate
* `f` up to `n times.
*/
pub fn rsplitn<T:Copy>(v: &[T], n: uint, f: &fn(t: &T) -> bool) -> ~[~[T]] {
let ln = v.len();
if (ln == 0u) { return ~[] }
let mut end = ln;
let mut count = n;
let mut result = ~[];
while end > 0u && count > 0u {
match rposition_between(v, 0u, end, f) {
None => break,
Some(i) => {
result.push(slice(v, i + 1u, end).to_owned());
// Make sure to skip the separator.
end = i;
count -= 1u;
}
}
}
result.push(slice(v, 0u, end).to_owned());
reverse(result);
result
}
/**
* Partitions a vector into two new vectors: those that satisfies the
* predicate, and those that do not.
*/
pub fn partition<T>(v: ~[T], f: &fn(&T) -> bool) -> (~[T], ~[T]) {
let mut lefts = ~[];
let mut rights = ~[];
// FIXME (#4355 maybe): using v.consume here crashes
// do v.consume |_, elt| {
do consume(v) |_, elt| {
if f(&elt) {
lefts.push(elt);
} else {
rights.push(elt);
}
}
(lefts, rights)
}
/**
* Partitions a vector into two new vectors: those that satisfies the
* predicate, and those that do not.
*/
pub fn partitioned<T:Copy>(v: &[T], f: &fn(&T) -> bool) -> (~[T], ~[T]) {
let mut lefts = ~[];
let mut rights = ~[];
for each(v) |elt| {
if f(elt) {
lefts.push(copy *elt);
} else {
rights.push(copy *elt);
}
}
(lefts, rights)
}
// Mutators
/// Removes the first element from a vector and return it
pub fn shift<T>(v: &mut ~[T]) -> T {
unsafe {
assert!(!v.is_empty());
if v.len() == 1 { return v.pop() }
if v.len() == 2 {
let last = v.pop();
let first = v.pop();
v.push(last);
return first;
}
let ln = v.len();
let next_ln = v.len() - 1;
// Save the last element. We're going to overwrite its position
let work_elt = v.pop();
// We still should have room to work where what last element was
assert!(capacity(v) >= ln);
// Pretend like we have the original length so we can use
// the vector copy_memory to overwrite the hole we just made
raw::set_len(&mut *v, ln);
// Memcopy the head element (the one we want) to the location we just
// popped. For the moment it unsafely exists at both the head and last
// positions
{
let first_slice = slice(*v, 0, 1);
let last_slice = slice(*v, next_ln, ln);
raw::copy_memory(transmute(last_slice), first_slice, 1);
}
// Memcopy everything to the left one element
{
let init_slice = slice(*v, 0, next_ln);
let tail_slice = slice(*v, 1, ln);
raw::copy_memory(transmute(init_slice),
tail_slice,
next_ln);
}
// Set the new length. Now the vector is back to normal
raw::set_len(&mut *v, next_ln);
// Swap out the element we want from the end
let vp = raw::to_mut_ptr(*v);
let vp = ptr::mut_offset(vp, next_ln - 1);
ptr::replace_ptr(vp, work_elt)
}
}
/// Prepend an element to the vector
pub fn unshift<T>(v: &mut ~[T], x: T) {
let vv = util::replace(v, ~[x]);
v.push_all_move(vv);
}
/// Insert an element at position i within v, shifting all
/// elements after position i one position to the right.
pub fn insert<T>(v: &mut ~[T], i: uint, x: T) {
let len = v.len();
assert!(i <= len);
v.push(x);
let mut j = len;
while j > i {
swap(*v, j, j - 1);
j -= 1;
}
}
/// Remove and return the element at position i within v, shifting
/// all elements after position i one position to the left.
pub fn remove<T>(v: &mut ~[T], i: uint) -> T {
let len = v.len();
assert!(i < len);
let mut j = i;
while j < len - 1 {
swap(*v, j, j + 1);
j += 1;
}
v.pop()
}
/// Consumes all elements, in a vector, moving them out into the / closure
/// provided. The vector is traversed from the start to the end.
///
/// This method does not impose any requirements on the type of the vector being
/// consumed, but it prevents any usage of the vector after this function is
/// called.
///
/// # Examples
///
/// ~~~ {.rust}
/// let v = ~[~"a", ~"b"];
/// do vec::consume(v) |i, s| {
/// // s has type ~str, not &~str
/// io::println(s + fmt!(" %d", i));
/// }
/// ~~~
pub fn consume<T>(mut v: ~[T], f: &fn(uint, v: T)) {
unsafe {
do as_mut_buf(v) |p, ln| {
for uint::range(0, ln) |i| {
// NB: This unsafe operation counts on init writing 0s to the
// holes we create in the vector. That ensures that, if the
// iterator fails then we won't try to clean up the consumed
// elements during unwinding
let x = intrinsics::init();
let p = ptr::mut_offset(p, i);
f(i, ptr::replace_ptr(p, x));
}
}
raw::set_len(&mut v, 0);
}
}
/// Consumes all elements, in a vector, moving them out into the / closure
/// provided. The vectors is traversed in reverse order (from end to start).
///
/// This method does not impose any requirements on the type of the vector being
/// consumed, but it prevents any usage of the vector after this function is
/// called.
pub fn consume_reverse<T>(mut v: ~[T], f: &fn(uint, v: T)) {
unsafe {
do as_mut_buf(v) |p, ln| {
let mut i = ln;
while i > 0 {
i -= 1;
// NB: This unsafe operation counts on init writing 0s to the
// holes we create in the vector. That ensures that, if the
// iterator fails then we won't try to clean up the consumed
// elements during unwinding
let x = intrinsics::init();
let p = ptr::mut_offset(p, i);
f(i, ptr::replace_ptr(p, x));
}
}
raw::set_len(&mut v, 0);
}
}
/// Remove the last element from a vector and return it
pub fn pop<T>(v: &mut ~[T]) -> T {
let ln = v.len();
if ln == 0 {
fail!("sorry, cannot vec::pop an empty vector")
}
let valptr = ptr::to_mut_unsafe_ptr(&mut v[ln - 1u]);
unsafe {
let val = ptr::replace_ptr(valptr, intrinsics::init());
raw::set_len(v, ln - 1u);
val
}
}
/**
* Remove an element from anywhere in the vector and return it, replacing it
* with the last element. This does not preserve ordering, but is O(1).
*
* Fails if index >= length.
*/
pub fn swap_remove<T>(v: &mut ~[T], index: uint) -> T {
let ln = v.len();
if index >= ln {
fail!("vec::swap_remove - index %u >= length %u", index, ln);
}
if index < ln - 1 {
swap(*v, index, ln - 1);
}
v.pop()
}
/// Append an element to a vector
#[inline]
pub fn push<T>(v: &mut ~[T], initval: T) {
unsafe {
let repr: **raw::VecRepr = transmute(&mut *v);
let fill = (**repr).unboxed.fill;
if (**repr).unboxed.alloc > fill {
push_fast(v, initval);
}
else {
push_slow(v, initval);
}
}
}
// This doesn't bother to make sure we have space.
#[inline] // really pretty please
unsafe fn push_fast<T>(v: &mut ~[T], initval: T) {
let repr: **mut raw::VecRepr = transmute(v);
let fill = (**repr).unboxed.fill;
(**repr).unboxed.fill += sys::nonzero_size_of::<T>();
let p = to_unsafe_ptr(&((**repr).unboxed.data));
let p = ptr::offset(p, fill) as *mut T;
intrinsics::move_val_init(&mut(*p), initval);
}
#[inline(never)]
fn push_slow<T>(v: &mut ~[T], initval: T) {
let new_len = v.len() + 1;
reserve_at_least(&mut *v, new_len);
unsafe { push_fast(v, initval) }
}
/// Iterates over the slice `rhs`, copies each element, and then appends it to
/// the vector provided `v`. The `rhs` vector is traversed in-order.
///
/// # Example
///
/// ~~~ {.rust}
/// let mut a = ~[1];
/// vec::push_all(&mut a, [2, 3, 4]);
/// assert!(a == ~[1, 2, 3, 4]);
/// ~~~
#[inline]
pub fn push_all<T:Copy>(v: &mut ~[T], rhs: &const [T]) {
let new_len = v.len() + rhs.len();
reserve(&mut *v, new_len);
for uint::range(0u, rhs.len()) |i| {
push(&mut *v, unsafe { raw::get(rhs, i) })
}
}
/// Takes ownership of the vector `rhs`, moving all elements into the specified
/// vector `v`. This does not copy any elements, and it is illegal to use the
/// `rhs` vector after calling this method (because it is moved here).
///
/// # Example
///
/// ~~~ {.rust}
/// let mut a = ~[~1];
/// vec::push_all_move(&mut a, ~[~2, ~3, ~4]);
/// assert!(a == ~[~1, ~2, ~3, ~4]);
/// ~~~
#[inline]
pub fn push_all_move<T>(v: &mut ~[T], mut rhs: ~[T]) {
let new_len = v.len() + rhs.len();
reserve(&mut *v, new_len);
unsafe {
do as_mut_buf(rhs) |p, len| {
for uint::range(0, len) |i| {
let x = ptr::replace_ptr(ptr::mut_offset(p, i),
intrinsics::uninit());
push(&mut *v, x);
}
}
raw::set_len(&mut rhs, 0);
}
}
/// Shorten a vector, dropping excess elements.
pub fn truncate<T>(v: &mut ~[T], newlen: uint) {
do as_mut_buf(*v) |p, oldlen| {
assert!(newlen <= oldlen);
unsafe {
// This loop is optimized out for non-drop types.
for uint::range(newlen, oldlen) |i| {
ptr::replace_ptr(ptr::mut_offset(p, i), intrinsics::uninit());
}
}
}
unsafe { raw::set_len(&mut *v, newlen); }
}
/**
* Remove consecutive repeated elements from a vector; if the vector is
* sorted, this removes all duplicates.
*/
pub fn dedup<T:Eq>(v: &mut ~[T]) {
unsafe {
if v.len() < 1 { return; }
let mut (last_written, next_to_read) = (0, 1);
do as_const_buf(*v) |p, ln| {
// We have a mutable reference to v, so we can make arbitrary
// changes. (cf. push and pop)
let p = p as *mut T;
// last_written < next_to_read <= ln
while next_to_read < ln {
// last_written < next_to_read < ln
if *ptr::mut_offset(p, next_to_read) ==
*ptr::mut_offset(p, last_written) {
ptr::replace_ptr(ptr::mut_offset(p, next_to_read),
intrinsics::uninit());
} else {
last_written += 1;
// last_written <= next_to_read < ln
if next_to_read != last_written {
ptr::swap_ptr(ptr::mut_offset(p, last_written),
ptr::mut_offset(p, next_to_read));
}
}
// last_written <= next_to_read < ln
next_to_read += 1;
// last_written < next_to_read <= ln
}
}
// last_written < next_to_read == ln
raw::set_len(v, last_written + 1);
}
}
// 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:Copy>(lhs: ~[T], rhs: &const [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
}
/**
* Expands a vector in place, initializing the new elements to a given value
*
* # Arguments
*
* * v - The vector to grow
* * n - The number of elements to add
* * initval - The value for the new elements
*/
pub fn grow<T:Copy>(v: &mut ~[T], n: uint, initval: &T) {
let new_len = v.len() + n;
reserve_at_least(&mut *v, new_len);
let mut i: uint = 0u;
while i < n {
v.push(copy *initval);
i += 1u;
}
}
/**
* Expands a vector in place, initializing the new elements to the result of
* a function
*
* Function `init_op` is called `n` times with the values [0..`n`)
*
* # Arguments
*
* * v - The vector to grow
* * n - The number of elements to add
* * init_op - A function to call to retreive each appended element's
* value
*/
pub fn grow_fn<T>(v: &mut ~[T], n: uint, op: old_iter::InitOp<T>) {
let new_len = v.len() + n;
reserve_at_least(&mut *v, new_len);
let mut i: uint = 0u;
while i < n {
v.push(op(i));
i += 1u;
}
}
/**
* Sets the value of a vector element at a given index, growing the vector as
* needed
*
* Sets the element at position `index` to `val`. If `index` is past the end
* of the vector, expands the vector by replicating `initval` to fill the
* intervening space.
*/
pub fn grow_set<T:Copy>(v: &mut ~[T], index: uint, initval: &T, val: T) {
let l = v.len();
if index >= l { grow(&mut *v, index - l + 1u, initval); }
v[index] = val;
}
// Functional utilities
/// Apply a function to each element of a vector and return the results
pub fn map<T, U>(v: &[T], f: &fn(t: &T) -> U) -> ~[U] {
let mut result = with_capacity(v.len());
for each(v) |elem| {
result.push(f(elem));
}
result
}
/// Consumes a vector, mapping it into a different vector. This function takes
/// ownership of the supplied vector `v`, moving each element into the closure
/// provided to generate a new element. The vector of new elements is then
/// returned.
///
/// The original vector `v` cannot be used after this function call (it is moved
/// inside), but there are no restrictions on the type of the vector.
pub fn map_consume<T, U>(v: ~[T], f: &fn(v: T) -> U) -> ~[U] {
let mut result = ~[];
do consume(v) |_i, x| {
result.push(f(x));
}
result
}
/// Apply a function to each element of a vector and return the results
pub fn mapi<T, U>(v: &[T], f: &fn(uint, t: &T) -> U) -> ~[U] {
let mut i = 0;
do map(v) |e| {
i += 1;
f(i - 1, e)
}
}
/**
* 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: &fn(t: &T) -> ~[U]) -> ~[U] {
let mut result = ~[];
for each(v) |elem| { result.push_all_move(f(elem)); }
result
}
/**
* Apply a function to each pair of elements and return the results.
* Equivalent to `map(zip(v0, v1), f)`.
*/
pub fn map_zip<T:Copy,U:Copy,V>(v0: &[T], v1: &[U],
f: &fn(t: &T, v: &U) -> V) -> ~[V] {
let v0_len = v0.len();
if v0_len != v1.len() { fail!(); }
let mut u: ~[V] = ~[];
let mut i = 0u;
while i < v0_len {
u.push(f(&v0[i], &v1[i]));
i += 1u;
}
u
}
pub fn filter_map<T, U>(
v: ~[T],
f: &fn(t: T) -> Option<U>) -> ~[U]
{
/*!
*
* Apply a function to each element of a vector and return the results.
* Consumes the input vector. If function `f` returns `None` then that
* element is excluded from the resulting vector.
*/
let mut result = ~[];
do consume(v) |_, elem| {
match f(elem) {
None => {}
Some(result_elem) => { result.push(result_elem); }
}
}
result
}
pub fn filter_mapped<T, U: Copy>(
v: &[T],
f: &fn(t: &T) -> Option<U>) -> ~[U]
{
/*!
*
* Like `filter_map()`, but operates on a borrowed slice
* and does not consume the input.
*/
let mut result = ~[];
for each(v) |elem| {
match f(elem) {
None => {/* no-op */ }
Some(result_elem) => { result.push(result_elem); }
}
}
result
}
/**
* Construct a new vector from the elements of a vector for which some
* predicate holds.
*
* Apply function `f` to each element of `v` and return a vector containing
* only those elements for which `f` returned true.
*/
pub fn filter<T>(v: ~[T], f: &fn(t: &T) -> bool) -> ~[T] {
let mut result = ~[];
// FIXME (#4355 maybe): using v.consume here crashes
// do v.consume |_, elem| {
do consume(v) |_, elem| {
if f(&elem) { result.push(elem); }
}
result
}
/**
* Construct a new vector from the elements of a vector for which some
* predicate holds.
*
* Apply function `f` to each element of `v` and return a vector containing
* only those elements for which `f` returned true.
*/
pub fn filtered<T:Copy>(v: &[T], f: &fn(t: &T) -> bool) -> ~[T] {
let mut result = ~[];
for each(v) |elem| {
if f(elem) { result.push(copy *elem); }
}
result
}
/**
* Like `filter()`, but in place. Preserves order of `v`. Linear time.
*/
pub fn retain<T>(v: &mut ~[T], f: &fn(t: &T) -> bool) {
let len = v.len();
let mut deleted: uint = 0;
for uint::range(0, len) |i| {
if !f(&v[i]) {
deleted += 1;
} else if deleted > 0 {
swap(*v, i - deleted, i);
}
}
if deleted > 0 {
v.truncate(len - deleted);
}
}
/// Flattens a vector of vectors of T into a single vector of T.
pub fn concat<T:Copy>(v: &[~[T]]) -> ~[T] { v.concat_vec() }
/// Concatenate a vector of vectors, placing a given separator between each