vec.rs 122.8 KB
Newer Older
1
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// 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.

11
//! Vectors
B
Brian Anderson 已提交
12

N
Niko Matsakis 已提交
13 14
#[warn(non_camel_case_types)];

15
use cast::transmute;
16
use cast;
17
use container::{Container, Mutable};
A
Alex Crichton 已提交
18
use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Less, Equal, Greater};
B
Ben Striegel 已提交
19
use clone::Clone;
D
Daniel Micay 已提交
20 21
use old_iter::BaseIter;
use old_iter;
D
Daniel Micay 已提交
22
use iterator::Iterator;
23
use kinds::Copy;
24
use libc;
25
use old_iter::CopyableIter;
26
use option::{None, Option, Some};
27
use ptr::to_unsafe_ptr;
28
use ptr;
29
use ptr::Ptr;
30 31
use sys;
use uint;
32
use unstable::intrinsics;
33
use vec;
A
Alex Crichton 已提交
34
use util;
35

36
#[cfg(not(test))] use cmp::Equiv;
A
Alex Crichton 已提交
37

38 39 40 41 42 43 44 45 46
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 @[].
47
        #[fast_ffi]
48 49 50
        unsafe fn vec_reserve_shared(t: *sys::TypeDesc,
                                     v: **raw::VecRepr,
                                     n: libc::size_t);
51
        #[fast_ffi]
52 53 54
        unsafe fn vec_reserve_shared_actual(t: *sys::TypeDesc,
                                            v: **raw::VecRepr,
                                            n: libc::size_t);
55
    }
56 57
}

58
/// Returns true if a vector contains no elements
59
pub fn is_empty<T>(v: &const [T]) -> bool {
60
    as_const_buf(v, |_p, len| len == 0u)
61 62
}

63
/// Returns true if two vectors have the same length
64
pub fn same_length<T, U>(xs: &const [T], ys: &const [U]) -> bool {
D
Daniel Micay 已提交
65
    xs.len() == ys.len()
66 67
}

68 69 70 71 72 73 74 75 76 77 78
/**
 * 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
 */
79
#[inline]
T
Tim Chevalier 已提交
80
pub fn reserve<T>(v: &mut ~[T], n: uint) {
81
    // Only make the (slow) call into the runtime if we have to
82
    use managed;
N
Niko Matsakis 已提交
83
    if capacity(v) < n {
84 85
        unsafe {
            let ptr: **raw::VecRepr = cast::transmute(v);
86 87 88
            let td = sys::get_type_desc::<T>();
            if ((**ptr).box_header.ref_count ==
                managed::raw::RC_MANAGED_UNIQUE) {
I
ILyoan 已提交
89
                rustrt::vec_reserve_shared_actual(td, ptr, n as libc::size_t);
90
            } else {
I
ILyoan 已提交
91
                rustrt::vec_reserve_shared(td, ptr, n as libc::size_t);
92
            }
93
        }
94
    }
95 96
}

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
/**
 * 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
 */
G
Graydon Hoare 已提交
112
pub fn reserve_at_least<T>(v: &mut ~[T], n: uint) {
113 114 115
    reserve(v, uint::next_power_of_two(n));
}

116
/// Returns the number of elements the vector can hold without reallocating
117
#[inline(always)]
118
pub fn capacity<T>(v: &const ~[T]) -> uint {
119
    unsafe {
120
        let repr: **raw::VecRepr = transmute(v);
121
        (**repr).unboxed.alloc / sys::nonzero_size_of::<T>()
122
    }
B
Brian Anderson 已提交
123 124
}

125
/// Returns the length of a vector
126
#[inline(always)]
127
pub fn len<T>(v: &const [T]) -> uint {
128
    as_const_buf(v, |_p, len| len)
129
}
130

131
// A botch to tide us over until core and std are fully demuted.
132
pub fn uniq_len<T>(v: &const ~[T]) -> uint {
133
    unsafe {
134
        let v: &~[T] = transmute(v);
135 136 137 138
        as_const_buf(*v, |_p, len| len)
    }
}

139
/**
140
 * Creates and initializes an owned vector.
141
 *
142
 * Creates an owned vector of size `n_elts` and initializes the elements
143 144
 * to the value returned by the function `op`.
 */
D
Daniel Micay 已提交
145
pub fn from_fn<T>(n_elts: uint, op: old_iter::InitOp<T>) -> ~[T] {
146 147 148 149 150
    unsafe {
        let mut v = with_capacity(n_elts);
        do as_mut_buf(v) |p, _len| {
            let mut i: uint = 0u;
            while i < n_elts {
151 152
                intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i)),
                                          op(i));
153 154 155 156
                i += 1u;
            }
        }
        raw::set_len(&mut v, n_elts);
D
Daniel Micay 已提交
157
        v
158 159
    }
}
160

161
/**
162
 * Creates and initializes an owned vector.
163
 *
164
 * Creates an owned vector of size `n_elts` and initializes the elements
165 166
 * to the value `t`.
 */
167
pub fn from_elem<T:Copy>(n_elts: uint, t: T) -> ~[T] {
N
Niko Matsakis 已提交
168
    from_fn(n_elts, |_i| copy t)
169 170
}

171
/// Creates a new unique vector with the same contents as the slice
172
pub fn to_owned<T:Copy>(t: &[T]) -> ~[T] {
173 174 175
    from_fn(t.len(), |i| t[i])
}

176
/// Creates a new vector with a capacity of `capacity`
177
pub fn with_capacity<T>(capacity: uint) -> ~[T] {
178
    let mut vec = ~[];
179
    reserve(&mut vec, capacity);
D
Daniel Micay 已提交
180
    vec
181 182
}

183 184 185
/**
 * Builds a vector by calling a provided function with an argument
 * function that pushes an element to the back of a vector.
186
 * This version takes an initial capacity for the vector.
187 188 189 190
 *
 * # Arguments
 *
 * * size - An initial size of the vector to reserve
191
 * * builder - A function that will construct the vector. It receives
192 193 194 195
 *             as an argument a function that will push an element
 *             onto the vector being constructed.
 */
#[inline(always)]
196
pub fn build_sized<A>(size: uint, builder: &fn(push: &fn(v: A))) -> ~[A] {
197
    let mut vec = with_capacity(size);
198
    builder(|x| vec.push(x));
B
Brian Anderson 已提交
199
    vec
200 201 202 203 204 205 206 207
}

/**
 * Builds a vector by calling a provided function with an argument
 * function that pushes an element to the back of a vector.
 *
 * # Arguments
 *
208
 * * builder - A function that will construct the vector. It receives
209 210 211 212
 *             as an argument a function that will push an element
 *             onto the vector being constructed.
 */
#[inline(always)]
213
pub fn build<A>(builder: &fn(push: &fn(v: A))) -> ~[A] {
214 215 216
    build_sized(4, builder)
}

217 218 219 220 221 222 223 224
/**
 * 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
S
Sean Moon 已提交
225
 * * builder - A function that will construct the vector. It receives
226 227 228 229
 *             as an argument a function that will push an element
 *             onto the vector being constructed.
 */
#[inline(always)]
230 231 232
pub fn build_sized_opt<A>(size: Option<uint>,
                          builder: &fn(push: &fn(v: A)))
                       -> ~[A] {
233
    build_sized(size.get_or_default(4), builder)
234 235
}

236 237
// Accessors

238
/// Returns the first element of a vector
239
pub fn head<'r,T>(v: &'r [T]) -> &'r T {
240
    if v.len() == 0 { fail!("head: empty vector") }
241 242 243 244 245
    &v[0]
}

/// Returns `Some(x)` where `x` is the first element of the slice `v`,
/// or `None` if the vector is empty.
246
pub fn head_opt<'r,T>(v: &'r [T]) -> Option<&'r T> {
247 248
    if v.len() == 0 { None } else { Some(&v[0]) }
}
249

250
/// Returns a vector containing all but the first element of a slice
251
pub fn tail<'r,T>(v: &'r [T]) -> &'r [T] { slice(v, 1, v.len()) }
252

253
/// Returns a vector containing all but the first `n` elements of a slice
254
pub fn tailn<'r,T>(v: &'r [T], n: uint) -> &'r [T] { slice(v, n, v.len()) }
255

256
/// Returns a vector containing all but the last element of a slice
257
pub fn init<'r,T>(v: &'r [T]) -> &'r [T] { slice(v, 0, v.len() - 1) }
258 259

/// Returns a vector containing all but the last `n' elements of a slice
260
pub fn initn<'r,T>(v: &'r [T], n: uint) -> &'r [T] {
261
    slice(v, 0, v.len() - n)
262 263
}

264
/// Returns the last element of the slice `v`, failing if the slice is empty.
265
pub fn last<'r,T>(v: &'r [T]) -> &'r T {
266
    if v.len() == 0 { fail!("last: empty vector") }
267
    &v[v.len() - 1]
268 269
}

270 271
/// Returns `Some(x)` where `x` is the last element of the slice `v`, or
/// `None` if the vector is empty.
272
pub fn last_opt<'r,T>(v: &'r [T]) -> Option<&'r T> {
273
    if v.len() == 0 { None } else { Some(&v[v.len() - 1]) }
T
Tim Chevalier 已提交
274
}
275

E
Erick Tryzelaar 已提交
276
/// Return a slice that points into another slice.
277
#[inline(always)]
278
pub fn slice<'r,T>(v: &'r [T], start: uint, end: uint) -> &'r [T] {
P
Patrick Walton 已提交
279 280
    assert!(start <= end);
    assert!(end <= len(v));
281
    do as_imm_buf(v) |p, _len| {
282
        unsafe {
283 284
            transmute((ptr::offset(p, start),
                       (end - start) * sys::nonzero_size_of::<T>()))
285 286 287 288
        }
    }
}

289
/// Return a slice that points into another slice.
290
#[inline(always)]
291 292
pub fn mut_slice<'r,T>(v: &'r mut [T], start: uint, end: uint)
                    -> &'r mut [T] {
P
Patrick Walton 已提交
293 294
    assert!(start <= end);
    assert!(end <= v.len());
295
    do as_mut_buf(v) |p, _len| {
296
        unsafe {
297 298
            transmute((ptr::mut_offset(p, start),
                       (end - start) * sys::nonzero_size_of::<T>()))
299 300 301 302 303
        }
    }
}

/// Return a slice that points into another slice.
304
#[inline(always)]
305 306
pub fn const_slice<'r,T>(v: &'r const [T], start: uint, end: uint)
                      -> &'r const [T] {
P
Patrick Walton 已提交
307 308
    assert!(start <= end);
    assert!(end <= len(v));
309
    do as_const_buf(v) |p, _len| {
310
        unsafe {
311 312
            transmute((ptr::const_offset(p, start),
                       (end - start) * sys::nonzero_size_of::<T>()))
313 314 315 316
        }
    }
}

317
/// Copies
318

319
/// Split the vector `v` by applying each element against the predicate `f`.
320
pub fn split<T:Copy>(v: &[T], f: &fn(t: &T) -> bool) -> ~[~[T]] {
321
    let ln = len(v);
B
Brian Anderson 已提交
322
    if (ln == 0u) { return ~[] }
323

324
    let mut start = 0u;
325
    let mut result = ~[];
326
    while start < ln {
327
        match position_between(v, start, ln, f) {
328 329
            None => break,
            Some(i) => {
330
                result.push(slice(v, start, i).to_vec());
331 332
                start = i + 1u;
            }
333 334
        }
    }
335
    result.push(slice(v, start, ln).to_vec());
B
Brian Anderson 已提交
336
    result
337 338
}

339 340 341 342
/**
 * Split the vector `v` by applying each element against the predicate `f` up
 * to `n` times.
 */
343
pub fn splitn<T:Copy>(v: &[T], n: uint, f: &fn(t: &T) -> bool) -> ~[~[T]] {
344
    let ln = len(v);
B
Brian Anderson 已提交
345
    if (ln == 0u) { return ~[] }
346

347 348
    let mut start = 0u;
    let mut count = n;
349
    let mut result = ~[];
350
    while start < ln && count > 0u {
351
        match position_between(v, start, ln, f) {
352 353
            None => break,
            Some(i) => {
354
                result.push(slice(v, start, i).to_vec());
355 356 357 358
                // Make sure to skip the separator.
                start = i + 1u;
                count -= 1u;
            }
359 360
        }
    }
361
    result.push(slice(v, start, ln).to_vec());
B
Brian Anderson 已提交
362
    result
363 364
}

365 366 367 368
/**
 * Reverse split the vector `v` by applying each element against the predicate
 * `f`.
 */
369
pub fn rsplit<T:Copy>(v: &[T], f: &fn(t: &T) -> bool) -> ~[~[T]] {
370
    let ln = len(v);
T
Tim Chevalier 已提交
371
    if (ln == 0) { return ~[] }
372

373
    let mut end = ln;
374
    let mut result = ~[];
T
Tim Chevalier 已提交
375 376
    while end > 0 {
        match rposition_between(v, 0, end, f) {
377 378
            None => break,
            Some(i) => {
379
                result.push(slice(v, i + 1, end).to_vec());
380 381
                end = i;
            }
382 383
        }
    }
384
    result.push(slice(v, 0u, end).to_vec());
385
    reverse(result);
D
Daniel Micay 已提交
386
    result
387 388
}

389 390 391 392
/**
 * Reverse split the vector `v` by applying each element against the predicate
 * `f` up to `n times.
 */
393
pub fn rsplitn<T:Copy>(v: &[T], n: uint, f: &fn(t: &T) -> bool) -> ~[~[T]] {
394
    let ln = len(v);
B
Brian Anderson 已提交
395
    if (ln == 0u) { return ~[] }
396

397 398
    let mut end = ln;
    let mut count = n;
399
    let mut result = ~[];
400
    while end > 0u && count > 0u {
401
        match rposition_between(v, 0u, end, f) {
402 403
            None => break,
            Some(i) => {
404
                result.push(slice(v, i + 1u, end).to_vec());
405 406 407 408
                // Make sure to skip the separator.
                end = i;
                count -= 1u;
            }
409 410
        }
    }
411
    result.push(slice(v, 0u, end).to_vec());
412
    reverse(result);
B
Brian Anderson 已提交
413
    result
414
}
415

416 417 418 419
/**
 * Partitions a vector into two new vectors: those that satisfies the
 * predicate, and those that do not.
 */
420
pub fn partition<T>(v: ~[T], f: &fn(&T) -> bool) -> (~[T], ~[T]) {
421 422 423
    let mut lefts  = ~[];
    let mut rights = ~[];

424 425 426
    // FIXME (#4355 maybe): using v.consume here crashes
    // do v.consume |_, elt| {
    do consume(v) |_, elt| {
427 428 429 430 431 432 433 434 435 436 437 438 439 440
        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.
 */
441
pub fn partitioned<T:Copy>(v: &[T], f: &fn(&T) -> bool) -> (~[T], ~[T]) {
442 443 444 445
    let mut lefts  = ~[];
    let mut rights = ~[];

    for each(v) |elt| {
446 447 448 449
        if f(elt) {
            lefts.push(*elt);
        } else {
            rights.push(*elt);
450 451 452 453 454 455
        }
    }

    (lefts, rights)
}

456 457
// Mutators

458
/// Removes the first element from a vector and return it
459 460
pub fn shift<T>(v: &mut ~[T]) -> T {
    unsafe {
P
Patrick Walton 已提交
461
        assert!(!v.is_empty());
462

463
        if v.len() == 1 { return v.pop() }
464

465 466 467 468 469 470
        if v.len() == 2 {
            let last = v.pop();
            let first = v.pop();
            v.push(last);
            return first;
        }
471

472 473
        let ln = v.len();
        let next_ln = v.len() - 1;
474

475
        // Save the last element. We're going to overwrite its position
A
Alex Crichton 已提交
476
        let work_elt = v.pop();
477
        // We still should have room to work where what last element was
P
Patrick Walton 已提交
478
        assert!(capacity(v) >= ln);
479 480 481
        // 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);
482

483 484 485
        // 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
486
        {
487 488
            let first_slice = slice(*v, 0, 1);
            let last_slice = slice(*v, next_ln, ln);
489
            raw::copy_memory(transmute(last_slice), first_slice, 1);
490
        }
491

492
        // Memcopy everything to the left one element
493
        {
494 495
            let init_slice = slice(*v, 0, next_ln);
            let tail_slice = slice(*v, 1, ln);
496
            raw::copy_memory(transmute(init_slice),
497 498 499
                             tail_slice,
                             next_ln);
        }
500

501 502
        // Set the new length. Now the vector is back to normal
        raw::set_len(&mut *v, next_ln);
503

504 505 506
        // 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);
507

A
Alex Crichton 已提交
508
        util::replace_ptr(vp, work_elt)
509
    }
B
Brian Anderson 已提交
510 511
}

512
/// Prepend an element to the vector
T
Tim Chevalier 已提交
513
pub fn unshift<T>(v: &mut ~[T], x: T) {
A
Alex Crichton 已提交
514
    let vv = util::replace(v, ~[x]);
B
Brian Anderson 已提交
515
    v.push_all_move(vv);
E
Eric Holk 已提交
516 517
}

518 519 520 521
/// 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();
P
Patrick Walton 已提交
522
    assert!(i <= len);
523

B
Brian Anderson 已提交
524
    v.push(x);
525 526
    let mut j = len;
    while j > i {
A
Alex Crichton 已提交
527
        swap(*v, j, j - 1);
528 529 530 531 532 533 534 535
        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();
P
Patrick Walton 已提交
536
    assert!(i < len);
537 538 539

    let mut j = i;
    while j < len - 1 {
A
Alex Crichton 已提交
540
        swap(*v, j, j + 1);
541 542
        j += 1;
    }
B
Brian Anderson 已提交
543
    v.pop()
544 545
}

546
pub fn consume<T>(mut v: ~[T], f: &fn(uint, v: T)) {
547 548 549 550 551 552 553
    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
A
Alex Crichton 已提交
554
                let x = intrinsics::init();
555
                let p = ptr::mut_offset(p, i);
A
Alex Crichton 已提交
556
                f(i, util::replace_ptr(p, x));
557
            }
E
Eric Holk 已提交
558 559
        }

560 561
        raw::set_len(&mut v, 0);
    }
E
Eric Holk 已提交
562 563
}

E
Erick Tryzelaar 已提交
564 565 566 567 568 569 570 571 572 573 574
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
A
Alex Crichton 已提交
575
                let x = intrinsics::init();
E
Erick Tryzelaar 已提交
576
                let p = ptr::mut_offset(p, i);
A
Alex Crichton 已提交
577
                f(i, util::replace_ptr(p, x));
E
Erick Tryzelaar 已提交
578 579 580 581 582 583 584
            }
        }

        raw::set_len(&mut v, 0);
    }
}

585
/// Remove the last element from a vector and return it
G
Graydon Hoare 已提交
586
pub fn pop<T>(v: &mut ~[T]) -> T {
N
Niko Matsakis 已提交
587
    let ln = v.len();
B
Ben Blum 已提交
588
    if ln == 0 {
589
        fail!("sorry, cannot vec::pop an empty vector")
B
Ben Blum 已提交
590
    }
N
Niko Matsakis 已提交
591
    let valptr = ptr::to_mut_unsafe_ptr(&mut v[ln - 1u]);
592
    unsafe {
A
Alex Crichton 已提交
593
        let val = util::replace_ptr(valptr, intrinsics::init());
B
Brian Anderson 已提交
594
        raw::set_len(v, ln - 1u);
B
Brian Anderson 已提交
595
        val
596
    }
597 598
}

B
Ben Blum 已提交
599 600 601 602 603 604
/**
 * 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.
 */
G
Graydon Hoare 已提交
605
pub fn swap_remove<T>(v: &mut ~[T], index: uint) -> T {
N
Niko Matsakis 已提交
606
    let ln = v.len();
B
Ben Blum 已提交
607
    if index >= ln {
608
        fail!("vec::swap_remove - index %u >= length %u", index, ln);
B
Ben Blum 已提交
609
    }
N
Niko Matsakis 已提交
610
    if index < ln - 1 {
A
Alex Crichton 已提交
611
        swap(*v, index, ln - 1);
B
Ben Blum 已提交
612
    }
D
Daniel Micay 已提交
613
    v.pop()
B
Ben Blum 已提交
614 615
}

616
/// Append an element to a vector
617
#[inline(always)]
T
Tim Chevalier 已提交
618
pub fn push<T>(v: &mut ~[T], initval: T) {
619
    unsafe {
620
        let repr: **raw::VecRepr = transmute(&mut *v);
621 622
        let fill = (**repr).unboxed.fill;
        if (**repr).unboxed.alloc > fill {
B
Brian Anderson 已提交
623
            push_fast(v, initval);
E
Eric Holk 已提交
624 625
        }
        else {
B
Brian Anderson 已提交
626
            push_slow(v, initval);
E
Eric Holk 已提交
627 628 629 630
        }
    }
}

631 632 633
// This doesn't bother to make sure we have space.
#[inline(always)] // really pretty please
unsafe fn push_fast<T>(v: &mut ~[T], initval: T) {
634
    let repr: **mut raw::VecRepr = transmute(v);
635
    let fill = (**repr).unboxed.fill;
636
    (**repr).unboxed.fill += sys::nonzero_size_of::<T>();
637
    let p = to_unsafe_ptr(&((**repr).unboxed.data));
638
    let p = ptr::offset(p, fill) as *mut T;
639
    intrinsics::move_val_init(&mut(*p), initval);
640
}
641 642

#[inline(never)]
T
Tim Chevalier 已提交
643
fn push_slow<T>(v: &mut ~[T], initval: T) {
644 645
    let new_len = v.len() + 1;
    reserve_at_least(&mut *v, new_len);
B
Brian Anderson 已提交
646
    unsafe { push_fast(v, initval) }
E
Erick Tryzelaar 已提交
647 648
}

649
#[inline(always)]
650
pub fn push_all<T:Copy>(v: &mut ~[T], rhs: &const [T]) {
651 652
    let new_len = v.len() + rhs.len();
    reserve(&mut *v, new_len);
653

B
Brian Anderson 已提交
654
    for uint::range(0u, rhs.len()) |i| {
655
        push(&mut *v, unsafe { raw::get(rhs, i) })
656 657
    }
}
658

659
#[inline(always)]
S
Seo Sanghyeon 已提交
660
pub fn push_all_move<T>(v: &mut ~[T], mut rhs: ~[T]) {
661 662
    let new_len = v.len() + rhs.len();
    reserve(&mut *v, new_len);
663
    unsafe {
664
        do as_mut_buf(rhs) |p, len| {
B
Brian Anderson 已提交
665
            for uint::range(0, len) |i| {
A
Alex Crichton 已提交
666 667
                let x = util::replace_ptr(ptr::mut_offset(p, i),
                                          intrinsics::uninit());
668
                push(&mut *v, x);
669 670
            }
        }
N
Niko Matsakis 已提交
671
        raw::set_len(&mut rhs, 0);
672 673 674
    }
}

675
/// Shorten a vector, dropping excess elements.
G
Graydon Hoare 已提交
676
pub fn truncate<T>(v: &mut ~[T], newlen: uint) {
677
    do as_mut_buf(*v) |p, oldlen| {
P
Patrick Walton 已提交
678
        assert!(newlen <= oldlen);
679 680 681
        unsafe {
            // This loop is optimized out for non-drop types.
            for uint::range(newlen, oldlen) |i| {
A
Alex Crichton 已提交
682
                util::replace_ptr(ptr::mut_offset(p, i), intrinsics::uninit());
683 684 685
            }
        }
    }
686
    unsafe { raw::set_len(&mut *v, newlen); }
687 688
}

689 690 691 692
/**
 * Remove consecutive repeated elements from a vector; if the vector is
 * sorted, this removes all duplicates.
 */
693
pub fn dedup<T:Eq>(v: &mut ~[T]) {
694 695 696 697 698 699 700 701 702 703 704 705
    unsafe {
        if v.len() < 1 { return; }
        let mut last_written = 0, next_to_read = 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) {
A
Alex Crichton 已提交
706 707
                    util::replace_ptr(ptr::mut_offset(p, next_to_read),
                                      intrinsics::uninit());
708 709
                } else {
                    last_written += 1;
710 711
                    // last_written <= next_to_read < ln
                    if next_to_read != last_written {
A
Alex Crichton 已提交
712 713
                        util::swap_ptr(ptr::mut_offset(p, last_written),
                                       ptr::mut_offset(p, next_to_read));
714 715 716 717 718 719 720 721 722 723 724 725
                    }
                }
                // 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);
    }
}

726
// Appending
727
#[inline(always)]
728
pub fn append<T:Copy>(lhs: ~[T], rhs: &const [T]) -> ~[T] {
B
Brian Anderson 已提交
729
    let mut v = lhs;
730
    v.push_all(rhs);
B
Brian Anderson 已提交
731
    v
732 733
}

E
Eric Holk 已提交
734
#[inline(always)]
735
pub fn append_one<T>(lhs: ~[T], x: T) -> ~[T] {
B
Brian Anderson 已提交
736
    let mut v = lhs;
737
    v.push(x);
B
Brian Anderson 已提交
738
    v
E
Eric Holk 已提交
739 740
}

741 742 743 744 745 746 747 748 749
/**
 * 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
 */
750
pub fn grow<T:Copy>(v: &mut ~[T], n: uint, initval: &T) {
751 752
    let new_len = v.len() + n;
    reserve_at_least(&mut *v, new_len);
753
    let mut i: uint = 0u;
754

755
    while i < n {
N
Niko Matsakis 已提交
756
        v.push(*initval);
757 758
        i += 1u;
    }
759 760
}

761 762 763 764 765 766 767 768 769 770 771 772 773
/**
 * 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
 */
D
Daniel Micay 已提交
774
pub fn grow_fn<T>(v: &mut ~[T], n: uint, op: old_iter::InitOp<T>) {
775 776
    let new_len = v.len() + n;
    reserve_at_least(&mut *v, new_len);
777
    let mut i: uint = 0u;
778 779 780 781
    while i < n {
        v.push(op(i));
        i += 1u;
    }
782 783
}

784 785 786 787 788 789 790 791
/**
 * 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.
 */
792
pub fn grow_set<T:Copy>(v: &mut ~[T], index: uint, initval: &T, val: T) {
N
Niko Matsakis 已提交
793
    let l = v.len();
794
    if index >= l { grow(&mut *v, index - l + 1u, initval); }
B
Brian Anderson 已提交
795
    v[index] = val;
796 797 798 799
}

// Functional utilities

800
/// Apply a function to each element of a vector and return the results
801
pub fn map<T, U>(v: &[T], f: &fn(t: &T) -> U) -> ~[U] {
802
    let mut result = with_capacity(len(v));
803
    for each(v) |elem| {
804
        result.push(f(elem));
805
    }
B
Brian Anderson 已提交
806
    result
807 808
}

809
pub fn map_consume<T, U>(v: ~[T], f: &fn(v: T) -> U) -> ~[U] {
E
Eric Holk 已提交
810
    let mut result = ~[];
B
Brian Anderson 已提交
811 812
    do consume(v) |_i, x| {
        result.push(f(x));
E
Eric Holk 已提交
813
    }
B
Brian Anderson 已提交
814
    result
E
Eric Holk 已提交
815 816
}

817
/// Apply a function to each element of a vector and return the results
818
pub fn mapi<T, U>(v: &[T], f: &fn(uint, t: &T) -> U) -> ~[U] {
819 820 821 822 823
    let mut i = 0;
    do map(v) |e| {
        i += 1;
        f(i - 1, e)
    }
824 825
}

826 827 828 829
/**
 * Apply a function to each element of a vector and return a concatenation
 * of each result vector
 */
830
pub fn flat_map<T, U>(v: &[T], f: &fn(t: &T) -> ~[U]) -> ~[U] {
831
    let mut result = ~[];
832
    for each(v) |elem| { result.push_all_move(f(elem)); }
B
Brian Anderson 已提交
833
    result
834 835
}

836 837 838 839 840
/**
 * 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],
841
                                  f: &fn(t: &T, v: &U) -> V) -> ~[V] {
842
    let v0_len = len(v0);
843
    if v0_len != len(v1) { fail!(); }
844
    let mut u: ~[V] = ~[];
845
    let mut i = 0u;
846
    while i < v0_len {
847
        u.push(f(&v0[i], &v1[i]));
848 849
        i += 1u;
    }
B
Brian Anderson 已提交
850
    u
851 852
}

853 854
pub fn filter_map<T, U>(
    v: ~[T],
855
    f: &fn(t: T) -> Option<U>) -> ~[U]
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
{
    /*!
     *
     * 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
}

874
pub fn filter_mapped<T, U: Copy>(
875
    v: &[T],
876
    f: &fn(t: &T) -> Option<U>) -> ~[U]
877 878 879 880 881 882 883
{
    /*!
     *
     * Like `filter_map()`, but operates on a borrowed slice
     * and does not consume the input.
     */

884
    let mut result = ~[];
B
Brian Anderson 已提交
885
    for each(v) |elem| {
N
Niko Matsakis 已提交
886
        match f(elem) {
B
Brian Anderson 已提交
887
          None => {/* no-op */ }
888
          Some(result_elem) => { result.push(result_elem); }
889 890
        }
    }
B
Brian Anderson 已提交
891
    result
892 893
}

894 895 896 897 898 899 900
/**
 * 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.
 */
901
pub fn filter<T>(v: ~[T], f: &fn(t: &T) -> bool) -> ~[T] {
902
    let mut result = ~[];
903 904 905
    // FIXME (#4355 maybe): using v.consume here crashes
    // do v.consume |_, elem| {
    do consume(v) |_, elem| {
906 907 908 909 910
        if f(&elem) { result.push(elem); }
    }
    result
}

911 912 913 914 915 916 917
/**
 * 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.
 */
918
pub fn filtered<T:Copy>(v: &[T], f: &fn(t: &T) -> bool) -> ~[T] {
919
    let mut result = ~[];
B
Brian Anderson 已提交
920
    for each(v) |elem| {
921
        if f(elem) { result.push(*elem); }
922
    }
B
Brian Anderson 已提交
923
    result
924 925
}

926 927 928
/**
 * Like `filter()`, but in place.  Preserves order of `v`.  Linear time.
 */
929
pub fn retain<T>(v: &mut ~[T], f: &fn(t: &T) -> bool) {
930 931 932 933 934 935 936
    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 {
A
Alex Crichton 已提交
937
            swap(*v, i - deleted, i);
938 939 940
        }
    }

941 942
    if deleted > 0 {
        v.truncate(len - deleted);
943 944 945
    }
}

946 947 948 949 950
/**
 * Concatenate a vector of vectors.
 *
 * Flattens a vector of vectors of T into a single vector of T.
 */
951
pub fn concat<T:Copy>(v: &[~[T]]) -> ~[T] {
952
    let mut r = ~[];
953
    for each(v) |inner| { r.push_all(*inner); }
B
Brian Anderson 已提交
954
    r
955 956
}

957
/// Concatenate a vector of vectors, placing a given separator between each
958
pub fn connect<T:Copy>(v: &[~[T]], sep: &T) -> ~[T] {
959
    let mut r: ~[T] = ~[];
960
    let mut first = true;
B
Brian Anderson 已提交
961
    for each(v) |inner| {
962 963
        if first { first = false; } else { r.push(*sep); }
        r.push_all(*inner);
964
    }
B
Brian Anderson 已提交
965
    r
966 967
}

968 969 970 971 972 973
/**
 * Reduces a vector from left to right.
 *
 * # Arguments
 * * `z` - initial accumulator value
 * * `v` - vector to iterate over
T
Tim Chevalier 已提交
974
 * * `p` - a closure to operate on vector elements
975 976 977 978 979 980 981 982 983 984
 *
 * # Examples
 *
 * Sum all values in the vector [1, 2, 3]:
 *
 * ~~~
 * vec::foldl(0, [1, 2, 3], |a, b| a + *b);
 * ~~~
 *
 */
985
pub fn foldl<'a, T, U>(z: T, v: &'a [U], p: &fn(t: T, u: &'a U) -> T) -> T {
B
Brian Anderson 已提交
986
    let mut accum = z;
987 988 989 990 991
    let mut i = 0;
    let l = v.len();
    while i < l {
        // Use a while loop so that liveness analysis can handle moving
        // the accumulator.
B
Brian Anderson 已提交
992
        accum = p(accum, &v[i]);
993
        i += 1;
994
    }
D
Daniel Micay 已提交
995
    accum
996 997
}

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
/**
 * Reduces a vector from right to left. Note that the argument order is
 * reversed compared to `foldl` to reflect the order they are provided to
 * the closure.
 *
 * # Arguments
 * * `v` - vector to iterate over
 * * `z` - initial accumulator value
 * * `p` - a closure to do operate on vector elements
 *
 * # Examples
 *
 * Sum all values in the vector [1, 2, 3]:
 *
 * ~~~
 * vec::foldr([1, 2, 3], 0, |a, b| a + *b);
 * ~~~
 *
 */
1017 1018 1019 1020 1021
pub fn foldr<'a, T, U>(v: &'a [T], mut z: U, p: &fn(t: &'a T, u: U) -> U) -> U {
    let mut i = v.len();
    while i > 0 {
        i -= 1;
        z = p(&v[i], z);
1022
    }
1023
    return z;
1024 1025
}

1026 1027 1028 1029 1030
/**
 * Return true if a predicate matches any elements
 *
 * If the vector contains no elements then false is returned.
 */
1031
pub fn any<T>(v: &[T], f: &fn(t: &T) -> bool) -> bool {
N
Niko Matsakis 已提交
1032
    for each(v) |elem| { if f(elem) { return true; } }
D
Daniel Micay 已提交
1033
    false
1034 1035
}

1036 1037 1038 1039 1040
/**
 * Return true if a predicate matches any elements in both vectors.
 *
 * If the vectors contains no elements then false is returned.
 */
1041
pub fn any2<T, U>(v0: &[T], v1: &[U],
1042
                   f: &fn(a: &T, b: &U) -> bool) -> bool {
1043 1044
    let v0_len = len(v0);
    let v1_len = len(v1);
1045
    let mut i = 0u;
1046
    while i < v0_len && i < v1_len {
N
Niko Matsakis 已提交
1047
        if f(&v0[i], &v1[i]) { return true; };
1048 1049
        i += 1u;
    }
D
Daniel Micay 已提交
1050
    false
1051 1052
}

1053 1054 1055 1056 1057
/**
 * Return true if a predicate matches all elements
 *
 * If the vector contains no elements then true is returned.
 */
1058
pub fn all<T>(v: &[T], f: &fn(t: &T) -> bool) -> bool {
N
Niko Matsakis 已提交
1059
    for each(v) |elem| { if !f(elem) { return false; } }
D
Daniel Micay 已提交
1060
    true
1061 1062
}

1063 1064 1065 1066 1067
/**
 * Return true if a predicate matches all elements
 *
 * If the vector contains no elements then true is returned.
 */
1068
pub fn alli<T>(v: &[T], f: &fn(uint, t: &T) -> bool) -> bool {
N
Niko Matsakis 已提交
1069
    for eachi(v) |i, elem| { if !f(i, elem) { return false; } }
D
Daniel Micay 已提交
1070
    true
1071 1072
}

1073 1074 1075 1076 1077
/**
 * Return true if a predicate matches all elements in both vectors.
 *
 * If the vectors are not the same size then false is returned.
 */
1078
pub fn all2<T, U>(v0: &[T], v1: &[U],
1079
                   f: &fn(t: &T, u: &U) -> bool) -> bool {
1080
    let v0_len = len(v0);
B
Brian Anderson 已提交
1081
    if v0_len != len(v1) { return false; }
1082
    let mut i = 0u;
N
Niko Matsakis 已提交
1083
    while i < v0_len { if !f(&v0[i], &v1[i]) { return false; }; i += 1u; }
D
Daniel Micay 已提交
1084
    true
1085 1086
}

1087
/// Return true if a vector contains an element with the given value
1088
pub fn contains<T:Eq>(v: &[T], x: &T) -> bool {
N
Niko Matsakis 已提交
1089
    for each(v) |elt| { if *x == *elt { return true; } }
D
Daniel Micay 已提交
1090
    false
1091 1092
}

1093
/// Returns the number of elements that are equal to a given value
1094
pub fn count<T:Eq>(v: &[T], x: &T) -> uint {
1095
    let mut cnt = 0u;
N
Niko Matsakis 已提交
1096
    for each(v) |elt| { if *x == *elt { cnt += 1u; } }
D
Daniel Micay 已提交
1097
    cnt
1098 1099
}

1100 1101 1102 1103 1104 1105 1106
/**
 * Search for the first element that matches a given predicate
 *
 * Apply function `f` to each element of `v`, starting from the first.
 * When function `f` returns true then an option containing the element
 * is returned. If `f` matches no elements then none is returned.
 */
1107
pub fn find<T:Copy>(v: &[T], f: &fn(t: &T) -> bool) -> Option<T> {
1108
    find_between(v, 0u, len(v), f)
1109 1110
}

1111 1112 1113 1114 1115 1116 1117
/**
 * Search for the first element that matches a given predicate within a range
 *
 * Apply function `f` to each element of `v` within the range
 * [`start`, `end`). When function `f` returns true then an option containing
 * the element is returned. If `f` matches no elements then none is returned.
 */
1118
pub fn find_between<T:Copy>(v: &[T], start: uint, end: uint,
1119
                      f: &fn(t: &T) -> bool) -> Option<T> {
1120
    position_between(v, start, end, f).map(|i| v[*i])
1121 1122
}

1123 1124 1125 1126 1127 1128 1129
/**
 * Search for the last element that matches a given predicate
 *
 * Apply function `f` to each element of `v` in reverse order. When function
 * `f` returns true then an option containing the element is returned. If `f`
 * matches no elements then none is returned.
 */
1130
pub fn rfind<T:Copy>(v: &[T], f: &fn(t: &T) -> bool) -> Option<T> {
1131
    rfind_between(v, 0u, len(v), f)
1132 1133
}

1134 1135 1136 1137 1138
/**
 * Search for the last element that matches a given predicate within a range
 *
 * Apply function `f` to each element of `v` in reverse order within the range
 * [`start`, `end`). When function `f` returns true then an option containing
N
Niko Matsakis 已提交
1139
 * the element is returned. If `f` matches no elements then none is return.
1140
 */
1141 1142 1143 1144 1145
pub fn rfind_between<T:Copy>(v: &[T],
                             start: uint,
                             end: uint,
                             f: &fn(t: &T) -> bool)
                          -> Option<T> {
1146
    rposition_between(v, start, end, f).map(|i| v[*i])
1147 1148
}

1149
/// Find the first index containing a matching value
1150
pub fn position_elem<T:Eq>(v: &[T], x: &T) -> Option<uint> {
N
Niko Matsakis 已提交
1151
    position(v, |y| *x == *y)
1152 1153
}

1154 1155 1156 1157 1158 1159 1160
/**
 * Find the first index matching some predicate
 *
 * Apply function `f` to each element of `v`.  When function `f` returns true
 * then an option containing the index is returned. If `f` matches no elements
 * then none is returned.
 */
1161
pub fn position<T>(v: &[T], f: &fn(t: &T) -> bool) -> Option<uint> {
1162
    position_between(v, 0u, len(v), f)
1163 1164
}

1165 1166 1167 1168 1169 1170 1171
/**
 * Find the first index matching some predicate within a range
 *
 * Apply function `f` to each element of `v` between the range
 * [`start`, `end`). When function `f` returns true then an option containing
 * the index is returned. If `f` matches no elements then none is returned.
 */
1172 1173 1174 1175 1176
pub fn position_between<T>(v: &[T],
                           start: uint,
                           end: uint,
                           f: &fn(t: &T) -> bool)
                        -> Option<uint> {
P
Patrick Walton 已提交
1177 1178
    assert!(start <= end);
    assert!(end <= len(v));
1179
    let mut i = start;
N
Niko Matsakis 已提交
1180
    while i < end { if f(&v[i]) { return Some::<uint>(i); } i += 1u; }
D
Daniel Micay 已提交
1181
    None
1182 1183
}

1184
/// Find the last index containing a matching value
1185
pub fn rposition_elem<T:Eq>(v: &[T], x: &T) -> Option<uint> {
N
Niko Matsakis 已提交
1186
    rposition(v, |y| *x == *y)
1187 1188
}

1189 1190 1191 1192 1193 1194 1195
/**
 * Find the last index matching some predicate
 *
 * Apply function `f` to each element of `v` in reverse order.  When function
 * `f` returns true then an option containing the index is returned. If `f`
 * matches no elements then none is returned.
 */
1196
pub fn rposition<T>(v: &[T], f: &fn(t: &T) -> bool) -> Option<uint> {
1197
    rposition_between(v, 0u, len(v), f)
1198 1199
}

1200 1201 1202 1203 1204 1205 1206 1207
/**
 * Find the last index matching some predicate within a range
 *
 * Apply function `f` to each element of `v` in reverse order between the
 * range [`start`, `end`). When function `f` returns true then an option
 * containing the index is returned. If `f` matches no elements then none is
 * returned.
 */
1208
pub fn rposition_between<T>(v: &[T], start: uint, end: uint,
1209
                             f: &fn(t: &T) -> bool) -> Option<uint> {
P
Patrick Walton 已提交
1210 1211
    assert!(start <= end);
    assert!(end <= len(v));
1212
    let mut i = end;
1213
    while i > start {
N
Niko Matsakis 已提交
1214
        if f(&v[i - 1u]) { return Some::<uint>(i - 1u); }
1215 1216
        i -= 1u;
    }
D
Daniel Micay 已提交
1217
    None
1218 1219
}

G
Graydon Hoare 已提交
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231


/**
 * Binary search a sorted vector with a comparator function.
 *
 * The comparator 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.
 */
1232
pub fn bsearch<T>(v: &[T], f: &fn(&T) -> Ordering) -> Option<uint> {
G
Graydon Hoare 已提交
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
    let mut base : uint = 0;
    let mut lim : uint = v.len();

    while lim != 0 {
        let ix = base + (lim >> 1);
        match f(&v[ix]) {
            Equal => return Some(ix),
            Less => {
                base = ix + 1;
                lim -= 1;
            }
            Greater => ()
        }
        lim >>= 1;
    }
    return None;
}

/**
 * Binary search a sorted vector for a given element.
 *
 * Returns the index of the element or None if not found.
 */
1256
pub fn bsearch_elem<T:TotalOrd>(v: &[T], x: &T) -> Option<uint> {
G
Graydon Hoare 已提交
1257 1258 1259
    bsearch(v, |p| p.cmp(x))
}

1260 1261 1262 1263
// FIXME: if issue #586 gets implemented, could have a postcondition
// saying the two result lists have the same length -- or, could
// return a nominal record with a constraint saying that, instead of
// returning a tuple (contingent on issue #869)
1264
/**
1265
 * Convert a vector of pairs into a pair of vectors, by reference. As unzip().
1266
 */
1267
pub fn unzip_slice<T:Copy,U:Copy>(v: &[(T, U)]) -> (~[T], ~[U]) {
1268
    let mut ts = ~[], us = ~[];
B
Brian Anderson 已提交
1269
    for each(v) |p| {
1270
        let (t, u) = *p;
1271 1272
        ts.push(t);
        us.push(u);
1273
    }
D
Daniel Micay 已提交
1274
    (ts, us)
1275 1276
}

1277
/**
1278
 * Convert a vector of pairs into a pair of vectors.
1279
 *
1280 1281 1282 1283 1284
 * 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 vector,
 * and the i-th element of the second vector contains the second element
 * of the i-th tuple of the input vector.
 */
1285
pub fn unzip<T,U>(v: ~[(T, U)]) -> (~[T], ~[U]) {
1286
    let mut ts = ~[], us = ~[];
1287 1288 1289 1290
    do consume(v) |_i, p| {
        let (t, u) = p;
        ts.push(t);
        us.push(u);
1291
    }
B
Brian Anderson 已提交
1292
    (ts, us)
1293 1294 1295 1296
}

/**
 * Convert two vectors to a vector of pairs, by reference. As zip().
1297
 */
1298
pub fn zip_slice<T:Copy,U:Copy>(v: &const [T], u: &const [U])
1299
        -> ~[(T, U)] {
1300
    let mut zipped = ~[];
1301 1302
    let sz = len(v);
    let mut i = 0u;
1303
    assert_eq!(sz, len(u));
1304
    while i < sz {
1305 1306
        zipped.push((v[i], u[i]));
        i += 1u;
1307
    }
B
Brian Anderson 已提交
1308
    zipped
1309 1310
}

1311 1312 1313 1314 1315 1316
/**
 * Convert two vectors to a vector of pairs.
 *
 * Returns a vector of tuples, where the i-th tuple contains contains the
 * i-th elements from each of the input vectors.
 */
1317
pub fn zip<T, U>(mut v: ~[T], mut u: ~[U]) -> ~[(T, U)] {
N
Niko Matsakis 已提交
1318
    let mut i = len(v);
1319
    assert_eq!(i, len(u));
1320
    let mut w = with_capacity(i);
1321
    while i > 0 {
1322
        w.push((v.pop(),u.pop()));
1323 1324
        i -= 1;
    }
1325
    reverse(w);
B
Brian Anderson 已提交
1326
    w
1327 1328
}

1329 1330 1331 1332 1333 1334 1335 1336 1337
/**
 * Swaps two elements in a vector
 *
 * # Arguments
 *
 * * v  The input vector
 * * a - The index of the first element
 * * b - The index of the second element
 */
A
Alex Crichton 已提交
1338
#[inline(always)]
B
Ben Striegel 已提交
1339
pub fn swap<T>(v: &mut [T], a: uint, b: uint) {
A
Alex Crichton 已提交
1340 1341 1342 1343 1344 1345 1346
    unsafe {
        // Can't take two mutable loans from one vector, so instead just cast
        // them to their raw pointers to do the swap
        let pa: *mut T = ptr::to_mut_unsafe_ptr(&mut v[a]);
        let pb: *mut T = ptr::to_mut_unsafe_ptr(&mut v[b]);
        util::swap_ptr(pa, pb);
    }
1347 1348
}

1349
/// Reverse the order of elements in a vector, in place
B
Ben Striegel 已提交
1350
pub fn reverse<T>(v: &mut [T]) {
1351
    let mut i: uint = 0;
1352
    let ln = len::<T>(v);
A
Alex Crichton 已提交
1353 1354 1355 1356
    while i < ln / 2 {
        swap(v, i, ln - i - 1);
        i += 1;
    }
1357 1358
}

1359 1360 1361 1362 1363
/**
 * Reverse part of a vector in place.
 *
 * Reverse the elements in the vector between `start` and `end - 1`.
 *
1364 1365 1366
 * If either start or end do not represent valid positions in the vector, the
 * vector is returned unchanged.
 *
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
 * # Arguments
 *
 * * `v` - The mutable vector to be modified
 *
 * * `start` - Index of the first element of the slice
 *
 * * `end` - Index one past the final element to be reversed.
 *
 * # Example
 *
 * Assume a mutable vector `v` contains `[1,2,3,4,5]`. After the call:
 *
 * ~~~
 *
 * reverse_part(v, 1, 4);
 *
 * ~~~
 *
 * `v` now contains `[1,4,3,2,5]`.
 */
pub fn reverse_part<T>(v: &mut [T], start: uint, end : uint) {
1388 1389
    let sz = v.len();
    if start >= sz || end > sz { return; }
1390 1391 1392
    let mut i = start;
    let mut j = end - 1;
    while i < j {
C
Corey Richardson 已提交
1393
        vec::swap(v, i, j);
1394 1395 1396 1397 1398
        i += 1;
        j -= 1;
    }
}

1399
/// Returns a vector with the order of elements reversed
1400
pub fn reversed<T:Copy>(v: &const [T]) -> ~[T] {
1401
    let mut rs: ~[T] = ~[];
1402
    let mut i = len::<T>(v);
B
Brian Anderson 已提交
1403
    if i == 0 { return (rs); } else { i -= 1; }
1404 1405
    while i != 0 { rs.push(v[i]); i -= 1; }
    rs.push(v[0]);
B
Brian Anderson 已提交
1406
    rs
1407 1408
}

1409
/**
S
Steve Klabnik 已提交
1410
 * Iterates over a vector, yielding each element to a closure.
1411
 *
S
Steve Klabnik 已提交
1412 1413 1414
 * # Arguments
 *
 * * `v` - A vector, to be iterated over
T
Tim Chevalier 已提交
1415 1416
 * * `f` - A closure to do the iterating. Within this closure, return true to
 * * continue iterating, false to break.
S
Steve Klabnik 已提交
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
 *
 * # Examples
 * ~~~
 * [1,2,3].each(|&i| {
 *     io::println(int::str(i));
 *     true
 * });
 * ~~~
 *
 * ~~~
 * [1,2,3,4,5].each(|&i| {
 *     if i < 4 {
 *         io::println(int::str(i));
 *         true
 *     }
 *     else {
 *         false
 *     }
 * });
 * ~~~
 *
 * You probably will want to use each with a `for`/`do` expression, depending
 * on your iteration needs:
 *
 * ~~~
 * for [1,2,3].each |&i| {
 *     io::println(int::str(i));
 * }
 * ~~~
1446
 */
1447
#[inline(always)]
A
Alex Crichton 已提交
1448
pub fn _each<'r,T>(v: &'r [T], f: &fn(&'r T) -> bool) -> bool {
1449
    //             ^^^^
1450
    // NB---this CANNOT be &const [T]!  The reason
1451 1452 1453
    // is that you are passing it to `f()` using
    // an immutable.

A
Alex Crichton 已提交
1454 1455
    let mut broke = false;
    do as_imm_buf(v) |p, n| {
1456 1457 1458
        let mut n = n;
        let mut p = p;
        while n > 0u {
1459
            unsafe {
1460 1461
                let q = cast::copy_lifetime_vec(v, &*p);
                if !f(q) { break; }
1462 1463
                p = ptr::offset(p, 1u);
            }
1464 1465
            n -= 1u;
        }
A
Alex Crichton 已提交
1466
        broke = n > 0;
1467
    }
A
Alex Crichton 已提交
1468
    return true;
1469 1470
}

A
Alex Crichton 已提交
1471 1472
pub fn each<'r,T>(v: &'r [T], f: &fn(&'r T) -> bool) -> bool { _each(v, f) }

1473 1474 1475 1476
/// Like `each()`, but for the case where you have
/// a vector with mutable contents and you would like
/// to mutate the contents as you iterate.
#[inline(always)]
A
Alex Crichton 已提交
1477 1478 1479
pub fn _each_mut<'r,T>(v: &'r mut [T], f: &fn(elem: &'r mut T) -> bool) -> bool {
    let mut broke = false;
    do as_mut_buf(v) |p, n| {
1480 1481 1482 1483 1484
        let mut n = n;
        let mut p = p;
        while n > 0 {
            unsafe {
                let q: &'r mut T = cast::transmute_mut_region(&mut *p);
A
Alex Crichton 已提交
1485
                if !f(q) { break; }
1486 1487 1488
                p = p.offset(1);
            }
            n -= 1;
1489
        }
A
Alex Crichton 已提交
1490
        broke = n > 0;
1491
    }
A
Alex Crichton 已提交
1492 1493 1494 1495 1496
    return broke;
}

pub fn each_mut<'r,T>(v: &'r mut [T], f: &fn(elem: &'r mut T) -> bool) -> bool {
    _each_mut(v, f)
1497 1498
}

1499 1500
/// Like `each()`, but for the case where you have a vector that *may or may
/// not* have mutable contents.
1501
#[inline(always)]
A
Alex Crichton 已提交
1502
pub fn _each_const<T>(v: &const [T], f: &fn(elem: &const T) -> bool) -> bool {
1503 1504 1505 1506
    let mut i = 0;
    let n = v.len();
    while i < n {
        if !f(&const v[i]) {
A
Alex Crichton 已提交
1507
            return false;
1508
        }
1509
        i += 1;
1510
    }
A
Alex Crichton 已提交
1511 1512 1513 1514 1515
    return true;
}

pub fn each_const<t>(v: &const [t], f: &fn(elem: &const t) -> bool) -> bool {
    _each_const(v, f)
1516 1517
}

1518 1519 1520 1521 1522
/**
 * Iterates over a vector's elements and indices
 *
 * Return true to continue, false to break.
 */
1523
#[inline(always)]
A
Alex Crichton 已提交
1524
pub fn _eachi<'r,T>(v: &'r [T], f: &fn(uint, v: &'r T) -> bool) -> bool {
1525 1526
    let mut i = 0;
    for each(v) |p| {
A
Alex Crichton 已提交
1527
        if !f(i, p) { return false; }
1528
        i += 1;
1529
    }
A
Alex Crichton 已提交
1530 1531 1532 1533 1534
    return true;
}

pub fn eachi<'r,T>(v: &'r [T], f: &fn(uint, v: &'r T) -> bool) -> bool {
    _eachi(v, f)
1535 1536
}

1537 1538 1539 1540 1541 1542
/**
 * Iterates over a mutable vector's elements and indices
 *
 * Return true to continue, false to break.
 */
#[inline(always)]
A
Alex Crichton 已提交
1543 1544
pub fn _eachi_mut<'r,T>(v: &'r mut [T],
                        f: &fn(uint, v: &'r mut T) -> bool) -> bool {
1545 1546 1547
    let mut i = 0;
    for each_mut(v) |p| {
        if !f(i, p) {
A
Alex Crichton 已提交
1548
            return false;
1549 1550 1551
        }
        i += 1;
    }
A
Alex Crichton 已提交
1552 1553 1554 1555 1556 1557
    return true;
}

pub fn eachi_mut<'r,T>(v: &'r mut [T],
                       f: &fn(uint, v: &'r mut T) -> bool) -> bool {
    _eachi_mut(v, f)
1558 1559
}

1560 1561 1562 1563 1564 1565
/**
 * Iterates over a vector's elements in reverse
 *
 * Return true to continue, false to break.
 */
#[inline(always)]
A
Alex Crichton 已提交
1566 1567 1568 1569 1570 1571
pub fn _each_reverse<'r,T>(v: &'r [T], blk: &fn(v: &'r T) -> bool) -> bool {
    _eachi_reverse(v, |_i, v| blk(v))
}

pub fn each_reverse<'r,T>(v: &'r [T], blk: &fn(v: &'r T) -> bool) -> bool {
    _each_reverse(v, blk)
1572 1573 1574 1575 1576 1577 1578 1579
}

/**
 * Iterates over a vector's elements and indices in reverse
 *
 * Return true to continue, false to break.
 */
#[inline(always)]
A
Alex Crichton 已提交
1580 1581
pub fn _eachi_reverse<'r,T>(v: &'r [T],
                            blk: &fn(i: uint, v: &'r T) -> bool) -> bool {
1582 1583 1584 1585
    let mut i = v.len();
    while i > 0 {
        i -= 1;
        if !blk(i, &v[i]) {
A
Alex Crichton 已提交
1586
            return false;
1587 1588
        }
    }
A
Alex Crichton 已提交
1589 1590 1591 1592 1593 1594
    return true;
}

pub fn eachi_reverse<'r,T>(v: &'r [T],
                           blk: &fn(i: uint, v: &'r T) -> bool) -> bool {
    _eachi_reverse(v, blk)
1595 1596
}

1597 1598 1599 1600 1601 1602 1603
/**
 * Iterates over two vectors simultaneously
 *
 * # Failure
 *
 * Both vectors must have the same length
 */
1604
#[inline]
A
Alex Crichton 已提交
1605
pub fn _each2<U, T>(v1: &[U], v2: &[T], f: &fn(u: &U, t: &T) -> bool) -> bool {
1606
    assert_eq!(v1.len(), v2.len());
Y
Youngmin Yoo 已提交
1607
    for uint::range(0u, v1.len()) |i| {
1608
        if !f(&v1[i], &v2[i]) {
A
Alex Crichton 已提交
1609
            return false;
1610
        }
1611
    }
A
Alex Crichton 已提交
1612 1613 1614 1615 1616
    return true;
}

pub fn each2<U, T>(v1: &[U], v2: &[T], f: &fn(u: &U, t: &T) -> bool) -> bool {
    _each2(v1, v2, f)
1617 1618
}

Y
Youngmin Yoo 已提交
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
/**
 *
 * Iterates over two vector with mutable.
 *
 * # Failure
 *
 * Both vectors must have the same length
 */
#[inline]
pub fn _each2_mut<U, T>(v1: &mut [U], v2: &mut [T], f: &fn(u: &mut U, t: &mut T) -> bool) -> bool {
1629
    assert_eq!(v1.len(), v2.len());
Y
Youngmin Yoo 已提交
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
    for uint::range(0u, v1.len()) |i| {
        if !f(&mut v1[i], &mut v2[i]) {
            return false;
        }
    }
    return true;
}

pub fn each2_mut<U, T>(v1: &mut [U], v2: &mut [T], f: &fn(u: &mut U, t: &mut T) -> bool) -> bool {
    _each2_mut(v1, v2, f)
}

1642 1643 1644 1645 1646 1647 1648 1649 1650
/**
 * Iterate over all permutations of vector `v`.
 *
 * Permutations are produced in lexicographic order with respect to the order
 * of elements in `v` (so if `v` is sorted then the permutations are
 * lexicographically sorted).
 *
 * The total number of permutations produced is `len(v)!`.  If `v` contains
 * repeated elements, then some permutations are repeated.
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
 *
 * See [Algorithms to generate
 * permutations](http://en.wikipedia.org/wiki/Permutation).
 *
 *  # Arguments
 *
 *  * `values` - A vector of values from which the permutations are
 *  chosen
 *
 *  * `fun` - The function to iterate over the combinations
1661
 */
1662
pub fn each_permutation<T:Copy>(values: &[T], fun: &fn(perm : &[T]) -> bool) -> bool {
1663 1664 1665 1666
    let length = values.len();
    let mut permutation = vec::from_fn(length, |i| values[i]);
    if length <= 1 {
        fun(permutation);
1667
        return true;
1668 1669 1670
    }
    let mut indices = vec::from_fn(length, |i| i);
    loop {
1671
        if !fun(permutation) { return true; }
1672 1673 1674 1675 1676 1677
        // find largest k such that indices[k] < indices[k+1]
        // if no such k exists, all permutations have been generated
        let mut k = length - 2;
        while k > 0 && indices[k] >= indices[k+1] {
            k -= 1;
        }
1678
        if k == 0 && indices[0] > indices[1] { return true; }
1679 1680 1681 1682 1683 1684 1685 1686
        // find largest l such that indices[k] < indices[l]
        // k+1 is guaranteed to be such
        let mut l = length - 1;
        while indices[k] >= indices[l] {
            l -= 1;
        }
        // swap indices[k] and indices[l]; sort indices[k+1..]
        // (they're just reversed)
C
Corey Richardson 已提交
1687 1688
        vec::swap(indices, k, l);
        reverse_part(indices, k+1, length);
1689 1690 1691
        // fixup permutation based on indices
        for uint::range(k, length) |i| {
            permutation[i] = values[indices[i]];
1692
        }
1693 1694 1695
    }
}

1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
/**
 * Iterate over all contiguous windows of length `n` of the vector `v`.
 *
 * # Example
 *
 * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`, `[3,4]`)
 *
 * ~~~
 * for windowed(2, &[1,2,3,4]) |v| {
 *     io::println(fmt!("%?", v));
 * }
 * ~~~
 *
 */
A
Alex Crichton 已提交
1710 1711 1712 1713 1714 1715 1716 1717
pub fn windowed<'r, T>(n: uint, v: &'r [T], it: &fn(&'r [T]) -> bool) -> bool {
    assert!(1u <= n);
    if n > v.len() { return true; }
    for uint::range(0, v.len() - n + 1) |i| {
        if !it(v.slice(i, i + n)) { return false; }
    }
    return true;
}
1718

1719 1720 1721 1722 1723 1724
/**
 * Work with the buffer of a vector.
 *
 * Allows for unsafe manipulation of vector contents, which is useful for
 * foreign interop.
 */
1725
#[inline(always)]
1726 1727 1728
pub fn as_imm_buf<T,U>(s: &[T],
                       /* NB---this CANNOT be const, see below */
                       f: &fn(*T, uint) -> U) -> U {
1729

1730
    // NB---Do not change the type of s to `&const [T]`.  This is
1731 1732 1733 1734 1735
    // unsound.  The reason is that we are going to create immutable pointers
    // into `s` and pass them to `f()`, but in fact they are potentially
    // pointing at *mutable memory*.  Use `as_const_buf` or `as_mut_buf`
    // instead!

1736
    unsafe {
1737
        let v : *(*T,uint) = transmute(&s);
1738
        let (buf,len) = *v;
1739
        f(buf, len / sys::nonzero_size_of::<T>())
1740
    }
1741 1742
}

1743
/// Similar to `as_imm_buf` but passing a `*const T`
1744
#[inline(always)]
1745
pub fn as_const_buf<T,U>(s: &const [T], f: &fn(*const T, uint) -> U) -> U {
1746
    unsafe {
1747
        let v : *(*const T,uint) = transmute(&s);
1748
        let (buf,len) = *v;
1749
        f(buf, len / sys::nonzero_size_of::<T>())
1750
    }
1751 1752
}

1753
/// Similar to `as_imm_buf` but passing a `*mut T`
1754
#[inline(always)]
1755
pub fn as_mut_buf<T,U>(s: &mut [T], f: &fn(*mut T, uint) -> U) -> U {
1756
    unsafe {
1757
        let v : *(*mut T,uint) = transmute(&s);
1758
        let (buf,len) = *v;
1759
        f(buf, len / sys::nonzero_size_of::<T>())
1760
    }
1761 1762
}

1763 1764
// Equality

D
Daniel Micay 已提交
1765
fn eq<T: Eq>(a: &[T], b: &[T]) -> bool {
1766 1767 1768 1769 1770 1771 1772 1773
    let (a_len, b_len) = (a.len(), b.len());
    if a_len != b_len { return false; }

    let mut i = 0;
    while i < a_len {
        if a[i] != b[i] { return false; }
        i += 1;
    }
D
Daniel Micay 已提交
1774 1775 1776 1777 1778 1779
    true
}

fn equals<T: TotalEq>(a: &[T], b: &[T]) -> bool {
    let (a_len, b_len) = (a.len(), b.len());
    if a_len != b_len { return false; }
1780

D
Daniel Micay 已提交
1781 1782 1783 1784 1785
    let mut i = 0;
    while i < a_len {
        if !a[i].equals(&b[i]) { return false; }
        i += 1;
    }
D
Daniel Micay 已提交
1786
    true
1787 1788
}

1789
#[cfg(not(test))]
1790
impl<'self,T:Eq> Eq for &'self [T] {
1791
    #[inline(always)]
D
Daniel Micay 已提交
1792
    fn eq(&self, other: & &'self [T]) -> bool { eq(*self, *other) }
1793
    #[inline(always)]
D
Daniel Micay 已提交
1794
    fn ne(&self, other: & &'self [T]) -> bool { !self.eq(other) }
1795 1796
}

1797
#[cfg(not(test))]
1798
impl<T:Eq> Eq for ~[T] {
1799
    #[inline(always)]
D
Daniel Micay 已提交
1800
    fn eq(&self, other: &~[T]) -> bool { eq(*self, *other) }
1801
    #[inline(always)]
D
Daniel Micay 已提交
1802
    fn ne(&self, other: &~[T]) -> bool { !self.eq(other) }
1803
}
1804

1805
#[cfg(not(test))]
1806
impl<T:Eq> Eq for @[T] {
1807
    #[inline(always)]
D
Daniel Micay 已提交
1808 1809 1810 1811 1812
    fn eq(&self, other: &@[T]) -> bool { eq(*self, *other) }
    #[inline(always)]
    fn ne(&self, other: &@[T]) -> bool { !self.eq(other) }
}

1813
#[cfg(not(test))]
D
Daniel Micay 已提交
1814 1815 1816 1817 1818
impl<'self,T:TotalEq> TotalEq for &'self [T] {
    #[inline(always)]
    fn equals(&self, other: & &'self [T]) -> bool { equals(*self, *other) }
}

1819
#[cfg(not(test))]
D
Daniel Micay 已提交
1820 1821 1822 1823 1824
impl<T:TotalEq> TotalEq for ~[T] {
    #[inline(always)]
    fn equals(&self, other: &~[T]) -> bool { equals(*self, *other) }
}

1825
#[cfg(not(test))]
D
Daniel Micay 已提交
1826
impl<T:TotalEq> TotalEq for @[T] {
1827
    #[inline(always)]
D
Daniel Micay 已提交
1828
    fn equals(&self, other: &@[T]) -> bool { equals(*self, *other) }
1829
}
1830

1831
#[cfg(not(test))]
1832
impl<'self,T:Eq> Equiv<~[T]> for &'self [T] {
1833
    #[inline(always)]
1834
    fn equiv(&self, other: &~[T]) -> bool { eq(*self, *other) }
1835 1836
}

1837 1838
// Lexicographical comparison

1839
fn cmp<T: TotalOrd>(a: &[T], b: &[T]) -> Ordering {
D
Daniel Micay 已提交
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
    let low = uint::min(a.len(), b.len());

    for uint::range(0, low) |idx| {
        match a[idx].cmp(&b[idx]) {
          Greater => return Greater,
          Less => return Less,
          Equal => ()
        }
    }

    a.len().cmp(&b.len())
}

1853
#[cfg(not(test))]
1854
impl<'self,T:TotalOrd> TotalOrd for &'self [T] {
D
Daniel Micay 已提交
1855
    #[inline(always)]
1856
    fn cmp(&self, other: & &'self [T]) -> Ordering { cmp(*self, *other) }
D
Daniel Micay 已提交
1857 1858
}

1859
#[cfg(not(test))]
D
Daniel Micay 已提交
1860 1861
impl<T: TotalOrd> TotalOrd for ~[T] {
    #[inline(always)]
1862
    fn cmp(&self, other: &~[T]) -> Ordering { cmp(*self, *other) }
D
Daniel Micay 已提交
1863 1864
}

1865
#[cfg(not(test))]
D
Daniel Micay 已提交
1866 1867
impl<T: TotalOrd> TotalOrd for @[T] {
    #[inline(always)]
1868
    fn cmp(&self, other: &@[T]) -> Ordering { cmp(*self, *other) }
D
Daniel Micay 已提交
1869 1870
}

1871
fn lt<T:Ord>(a: &[T], b: &[T]) -> bool {
1872
    let (a_len, b_len) = (a.len(), b.len());
1873
    let end = uint::min(a_len, b_len);
1874 1875 1876 1877 1878 1879 1880 1881 1882

    let mut i = 0;
    while i < end {
        let (c_a, c_b) = (&a[i], &b[i]);
        if *c_a < *c_b { return true; }
        if *c_a > *c_b { return false; }
        i += 1;
    }

D
Daniel Micay 已提交
1883
    a_len < b_len
1884 1885
}

1886 1887 1888
fn le<T:Ord>(a: &[T], b: &[T]) -> bool { !lt(b, a) }
fn ge<T:Ord>(a: &[T], b: &[T]) -> bool { !lt(a, b) }
fn gt<T:Ord>(a: &[T], b: &[T]) -> bool { lt(b, a)  }
1889

1890
#[cfg(not(test))]
1891
impl<'self,T:Ord> Ord for &'self [T] {
1892
    #[inline(always)]
1893
    fn lt(&self, other: & &'self [T]) -> bool { lt((*self), (*other)) }
1894
    #[inline(always)]
1895
    fn le(&self, other: & &'self [T]) -> bool { le((*self), (*other)) }
1896
    #[inline(always)]
1897
    fn ge(&self, other: & &'self [T]) -> bool { ge((*self), (*other)) }
1898
    #[inline(always)]
1899
    fn gt(&self, other: & &'self [T]) -> bool { gt((*self), (*other)) }
1900 1901
}

1902
#[cfg(not(test))]
1903
impl<T:Ord> Ord for ~[T] {
1904
    #[inline(always)]
1905
    fn lt(&self, other: &~[T]) -> bool { lt((*self), (*other)) }
1906
    #[inline(always)]
1907
    fn le(&self, other: &~[T]) -> bool { le((*self), (*other)) }
1908
    #[inline(always)]
1909
    fn ge(&self, other: &~[T]) -> bool { ge((*self), (*other)) }
1910
    #[inline(always)]
1911
    fn gt(&self, other: &~[T]) -> bool { gt((*self), (*other)) }
1912
}
1913

1914
#[cfg(not(test))]
1915
impl<T:Ord> Ord for @[T] {
1916
    #[inline(always)]
1917
    fn lt(&self, other: &@[T]) -> bool { lt((*self), (*other)) }
1918
    #[inline(always)]
1919
    fn le(&self, other: &@[T]) -> bool { le((*self), (*other)) }
1920
    #[inline(always)]
1921
    fn ge(&self, other: &@[T]) -> bool { ge((*self), (*other)) }
1922
    #[inline(always)]
1923
    fn gt(&self, other: &@[T]) -> bool { gt((*self), (*other)) }
1924
}
1925

1926
#[cfg(not(test))]
1927
pub mod traits {
1928 1929
    use kinds::Copy;
    use ops::Add;
B
Ben Striegel 已提交
1930
    use vec::append;
1931

1932
    impl<'self,T:Copy> Add<&'self const [T],~[T]> for ~[T] {
1933
        #[inline(always)]
1934
        fn add(&self, rhs: & &'self const [T]) -> ~[T] {
1935 1936
            append(copy *self, (*rhs))
        }
1937
    }
1938 1939
}

1940
impl<'self,T> Container for &'self const [T] {
1941
    /// Returns true if a vector contains no elements
1942
    #[inline]
1943
    fn is_empty(&const self) -> bool { is_empty(*self) }
1944

1945
    /// Returns the length of a vector
1946
    #[inline]
1947
    fn len(&const self) -> uint { len(*self) }
1948 1949
}

G
Graydon Hoare 已提交
1950
pub trait CopyableVector<T> {
1951
    fn to_owned(&self) -> ~[T];
1952 1953
}

1954
/// Extension methods for vectors
N
Niko Matsakis 已提交
1955
impl<'self,T:Copy> CopyableVector<T> for &'self [T] {
1956
    /// Returns a copy of `v`.
1957
    #[inline]
1958
    fn to_owned(&self) -> ~[T] {
1959
        let mut result = ~[];
1960 1961 1962
        reserve(&mut result, self.len());
        for self.each |e| {
            result.push(copy *e);
1963
        }
1964 1965
        result

1966
    }
1967 1968
}

1969 1970
pub trait ImmutableVector<'self, T> {
    fn slice(&self, start: uint, end: uint) -> &'self [T];
D
Daniel Micay 已提交
1971
    fn iter(self) -> VecIterator<'self, T>;
1972 1973 1974 1975 1976 1977 1978 1979
    fn head(&self) -> &'self T;
    fn head_opt(&self) -> Option<&'self T>;
    fn tail(&self) -> &'self [T];
    fn tailn(&self, n: uint) -> &'self [T];
    fn init(&self) -> &'self [T];
    fn initn(&self, n: uint) -> &'self [T];
    fn last(&self) -> &'self T;
    fn last_opt(&self) -> Option<&'self T>;
1980 1981
    fn position(&self, f: &fn(t: &T) -> bool) -> Option<uint>;
    fn rposition(&self, f: &fn(t: &T) -> bool) -> Option<uint>;
A
Alex Crichton 已提交
1982 1983
    fn each_reverse(&self, blk: &fn(&T) -> bool) -> bool;
    fn eachi_reverse(&self, blk: &fn(uint, &T) -> bool) -> bool;
1984
    fn foldr<'a, U>(&'a self, z: U, p: &fn(t: &'a T, u: U) -> U) -> U;
1985 1986 1987 1988 1989 1990
    fn map<U>(&self, f: &fn(t: &T) -> U) -> ~[U];
    fn mapi<U>(&self, f: &fn(uint, t: &T) -> U) -> ~[U];
    fn map_r<U>(&self, f: &fn(x: &T) -> U) -> ~[U];
    fn alli(&self, f: &fn(uint, t: &T) -> bool) -> bool;
    fn flat_map<U>(&self, f: &fn(t: &T) -> ~[U]) -> ~[U];
    fn filter_mapped<U:Copy>(&self, f: &fn(t: &T) -> Option<U>) -> ~[U];
1991
    unsafe fn unsafe_ref(&self, index: uint) -> *T;
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
}

/// Extension methods for vectors
impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
    /// Return a slice that points into another slice.
    #[inline]
    fn slice(&self, start: uint, end: uint) -> &'self [T] {
        slice(*self, start, end)
    }

D
Daniel Micay 已提交
2002 2003 2004 2005 2006 2007 2008 2009 2010
    #[inline]
    fn iter(self) -> VecIterator<'self, T> {
        unsafe {
            let p = vec::raw::to_ptr(self);
            VecIterator{ptr: p, end: p.offset(self.len()),
                        lifetime: cast::transmute(p)}
        }
    }

2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
    /// Returns the first element of a vector, failing if the vector is empty.
    #[inline]
    fn head(&self) -> &'self T { head(*self) }

    /// Returns the first element of a vector
    #[inline]
    fn head_opt(&self) -> Option<&'self T> { head_opt(*self) }

    /// Returns all but the first element of a vector
    #[inline]
    fn tail(&self) -> &'self [T] { tail(*self) }

    /// Returns all but the first `n' elements of a vector
    #[inline]
    fn tailn(&self, n: uint) -> &'self [T] { tailn(*self, n) }

    /// Returns all but the last elemnt of a vector
    #[inline]
    fn init(&self) -> &'self [T] { init(*self) }

    /// Returns all but the last `n' elemnts of a vector
    #[inline]
    fn initn(&self, n: uint) -> &'self [T] { initn(*self, n) }

    /// Returns the last element of a `v`, failing if the vector is empty.
    #[inline]
    fn last(&self) -> &'self T { last(*self) }

    /// Returns the last element of a `v`, failing if the vector is empty.
    #[inline]
    fn last_opt(&self) -> Option<&'self T> { last_opt(*self) }

2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
    /**
     * Find the first index matching some predicate
     *
     * Apply function `f` to each element of `v`.  When function `f` returns
     * true then an option containing the index is returned. If `f` matches no
     * elements then none is returned.
     */
    #[inline]
    fn position(&self, f: &fn(t: &T) -> bool) -> Option<uint> {
        position(*self, f)
    }

    /**
     * Find the last index matching some predicate
     *
     * Apply function `f` to each element of `v` in reverse order.  When
     * function `f` returns true then an option containing the index is
     * returned. If `f` matches no elements then none is returned.
     */
    #[inline]
    fn rposition(&self, f: &fn(t: &T) -> bool) -> Option<uint> {
        rposition(*self, f)
    }

2067 2068
    /// Iterates over a vector's elements in reverse.
    #[inline]
A
Alex Crichton 已提交
2069 2070 2071
    fn each_reverse(&self, blk: &fn(&T) -> bool) -> bool {
        each_reverse(*self, blk)
    }
2072 2073

    /// Iterates over a vector's elements and indices in reverse.
A
Alex Crichton 已提交
2074 2075 2076 2077
    #[inline]
    fn eachi_reverse(&self, blk: &fn(uint, &T) -> bool) -> bool {
        eachi_reverse(*self, blk)
    }
2078 2079 2080

    /// Reduce a vector from right to left
    #[inline]
2081
    fn foldr<'a, U>(&'a self, z: U, p: &fn(t: &'a T, u: U) -> U) -> U {
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133
        foldr(*self, z, p)
    }

    /// Apply a function to each element of a vector and return the results
    #[inline]
    fn map<U>(&self, f: &fn(t: &T) -> U) -> ~[U] { map(*self, f) }

    /**
     * Apply a function to the index and value of each element in the vector
     * and return the results
     */
    fn mapi<U>(&self, f: &fn(uint, t: &T) -> U) -> ~[U] {
        mapi(*self, f)
    }

    #[inline]
    fn map_r<U>(&self, f: &fn(x: &T) -> U) -> ~[U] {
        let mut r = ~[];
        let mut i = 0;
        while i < self.len() {
            r.push(f(&self[i]));
            i += 1;
        }
        r
    }

    /**
     * Returns true if the function returns true for all elements.
     *
     *     If the vector is empty, true is returned.
     */
    fn alli(&self, f: &fn(uint, t: &T) -> bool) -> bool {
        alli(*self, f)
    }
    /**
     * Apply a function to each element of a vector and return a concatenation
     * of each result vector
     */
    #[inline]
    fn flat_map<U>(&self, f: &fn(t: &T) -> ~[U]) -> ~[U] {
        flat_map(*self, f)
    }
    /**
     * Apply a function to each element of a vector and return the results
     *
     * If function `f` returns `none` then that element is excluded from
     * the resulting vector.
     */
    #[inline]
    fn filter_mapped<U:Copy>(&self, f: &fn(t: &T) -> Option<U>) -> ~[U] {
        filter_mapped(*self, f)
    }
2134 2135 2136 2137 2138 2139 2140 2141

    /// Returns a pointer to the element at the given index, without doing
    /// bounds checking.
    #[inline(always)]
    unsafe fn unsafe_ref(&self, index: uint) -> *T {
        let (ptr, _): (*T, uint) = transmute(*self);
        ptr.offset(index)
    }
2142 2143
}

2144
pub trait ImmutableEqVector<T:Eq> {
2145 2146
    fn position_elem(&self, t: &T) -> Option<uint>;
    fn rposition_elem(&self, t: &T) -> Option<uint>;
2147 2148
}

2149
impl<'self,T:Eq> ImmutableEqVector<T> for &'self [T] {
2150 2151
    /// Find the first index containing a matching value
    #[inline]
2152
    fn position_elem(&self, x: &T) -> Option<uint> {
2153
        position_elem(*self, x)
N
Niko Matsakis 已提交
2154 2155
    }

2156 2157
    /// Find the last index containing a matching value
    #[inline]
2158
    fn rposition_elem(&self, t: &T) -> Option<uint> {
2159
        rposition_elem(*self, t)
N
Niko Matsakis 已提交
2160
    }
2161 2162
}

G
Graydon Hoare 已提交
2163
pub trait ImmutableCopyableVector<T> {
2164 2165 2166
    fn filtered(&self, f: &fn(&T) -> bool) -> ~[T];
    fn rfind(&self, f: &fn(t: &T) -> bool) -> Option<T>;
    fn partitioned(&self, f: &fn(&T) -> bool) -> (~[T], ~[T]);
2167
    unsafe fn unsafe_get(&self, elem: uint) -> T;
2168 2169
}

2170
/// Extension methods for vectors
2171
impl<'self,T:Copy> ImmutableCopyableVector<T> for &'self [T] {
2172 2173 2174 2175 2176 2177 2178
    /**
     * 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.
     */
2179
    #[inline]
2180
    fn filtered(&self, f: &fn(t: &T) -> bool) -> ~[T] {
2181
        filtered(*self, f)
N
Niko Matsakis 已提交
2182 2183
    }

2184 2185 2186 2187 2188 2189 2190
    /**
     * Search for the last element that matches a given predicate
     *
     * Apply function `f` to each element of `v` in reverse order. When
     * function `f` returns true then an option containing the element is
     * returned. If `f` matches no elements then none is returned.
     */
2191
    #[inline]
2192
    fn rfind(&self, f: &fn(t: &T) -> bool) -> Option<T> {
2193 2194
        rfind(*self, f)
    }
2195 2196 2197 2198 2199 2200

    /**
     * Partitions the vector into those that satisfies the predicate, and
     * those that do not.
     */
    #[inline]
2201
    fn partitioned(&self, f: &fn(&T) -> bool) -> (~[T], ~[T]) {
2202 2203
        partitioned(*self, f)
    }
2204 2205 2206

    /// Returns the element at the given index, without doing bounds checking.
    #[inline(always)]
2207 2208
    unsafe fn unsafe_get(&self, index: uint) -> T {
        *self.unsafe_ref(index)
2209
    }
2210 2211
}

2212
pub trait OwnedVector<T> {
T
Tim Chevalier 已提交
2213 2214
    fn push(&mut self, t: T);
    fn push_all_move(&mut self, rhs: ~[T]);
N
Niko Matsakis 已提交
2215 2216
    fn pop(&mut self) -> T;
    fn shift(&mut self) -> T;
T
Tim Chevalier 已提交
2217
    fn unshift(&mut self, x: T);
2218 2219
    fn insert(&mut self, i: uint, x:T);
    fn remove(&mut self, i: uint) -> T;
N
Niko Matsakis 已提交
2220 2221
    fn swap_remove(&mut self, index: uint) -> T;
    fn truncate(&mut self, newlen: uint);
2222
    fn retain(&mut self, f: &fn(t: &T) -> bool);
2223
    fn consume(self, f: &fn(uint, v: T));
E
Erick Tryzelaar 已提交
2224
    fn consume_reverse(self, f: &fn(uint, v: T));
2225
    fn filter(self, f: &fn(t: &T) -> bool) -> ~[T];
2226
    fn partition(self, f: &fn(&T) -> bool) -> (~[T], ~[T]);
D
Daniel Micay 已提交
2227
    fn grow_fn(&mut self, n: uint, op: old_iter::InitOp<T>);
2228 2229
}

2230
impl<T> OwnedVector<T> for ~[T] {
2231
    #[inline]
T
Tim Chevalier 已提交
2232
    fn push(&mut self, t: T) {
B
Brian Anderson 已提交
2233
        push(self, t);
2234 2235
    }

2236
    #[inline]
T
Tim Chevalier 已提交
2237
    fn push_all_move(&mut self, rhs: ~[T]) {
B
Brian Anderson 已提交
2238
        push_all_move(self, rhs);
2239
    }
N
Niko Matsakis 已提交
2240

2241
    #[inline]
N
Niko Matsakis 已提交
2242 2243 2244 2245
    fn pop(&mut self) -> T {
        pop(self)
    }

2246
    #[inline]
N
Niko Matsakis 已提交
2247 2248 2249 2250
    fn shift(&mut self) -> T {
        shift(self)
    }

2251
    #[inline]
T
Tim Chevalier 已提交
2252
    fn unshift(&mut self, x: T) {
B
Brian Anderson 已提交
2253
        unshift(self, x)
N
Niko Matsakis 已提交
2254 2255
    }

2256
    #[inline]
2257
    fn insert(&mut self, i: uint, x:T) {
B
Brian Anderson 已提交
2258
        insert(self, i, x)
2259 2260
    }

2261
    #[inline]
2262 2263 2264 2265
    fn remove(&mut self, i: uint) -> T {
        remove(self, i)
    }

2266
    #[inline]
N
Niko Matsakis 已提交
2267 2268 2269 2270
    fn swap_remove(&mut self, index: uint) -> T {
        swap_remove(self, index)
    }

2271
    #[inline]
N
Niko Matsakis 已提交
2272 2273 2274
    fn truncate(&mut self, newlen: uint) {
        truncate(self, newlen);
    }
2275

2276
    #[inline]
2277
    fn retain(&mut self, f: &fn(t: &T) -> bool) {
2278 2279
        retain(self, f);
    }
2280

E
Erick Tryzelaar 已提交
2281
    #[inline]
2282
    fn consume(self, f: &fn(uint, v: T)) {
E
Erick Tryzelaar 已提交
2283 2284
        consume(self, f)
    }
2285

E
Erick Tryzelaar 已提交
2286 2287 2288 2289 2290
    #[inline]
    fn consume_reverse(self, f: &fn(uint, v: T)) {
        consume_reverse(self, f)
    }

2291
    #[inline]
2292
    fn filter(self, f: &fn(&T) -> bool) -> ~[T] {
2293 2294 2295
        filter(self, f)
    }

2296 2297 2298 2299 2300
    /**
     * Partitions the vector into those that satisfies the predicate, and
     * those that do not.
     */
    #[inline]
2301
    fn partition(self, f: &fn(&T) -> bool) -> (~[T], ~[T]) {
2302 2303
        partition(self, f)
    }
D
Daniel Micay 已提交
2304 2305

    #[inline]
D
Daniel Micay 已提交
2306
    fn grow_fn(&mut self, n: uint, op: old_iter::InitOp<T>) {
D
Daniel Micay 已提交
2307 2308
        grow_fn(self, n, op);
    }
2309 2310
}

2311
impl<T> Mutable for ~[T] {
D
Daniel Micay 已提交
2312 2313 2314 2315
    /// Clear the vector, removing all values.
    fn clear(&mut self) { self.truncate(0) }
}

2316
pub trait OwnedCopyableVector<T:Copy> {
2317
    fn push_all(&mut self, rhs: &const [T]);
2318 2319 2320 2321
    fn grow(&mut self, n: uint, initval: &T);
    fn grow_set(&mut self, index: uint, initval: &T, val: T);
}

2322
impl<T:Copy> OwnedCopyableVector<T> for ~[T] {
2323
    #[inline]
2324
    fn push_all(&mut self, rhs: &const [T]) {
2325 2326
        push_all(self, rhs);
    }
N
Niko Matsakis 已提交
2327

2328
    #[inline]
N
Niko Matsakis 已提交
2329 2330 2331 2332
    fn grow(&mut self, n: uint, initval: &T) {
        grow(self, n, initval);
    }

2333
    #[inline]
T
Tim Chevalier 已提交
2334
    fn grow_set(&mut self, index: uint, initval: &T, val: T) {
N
Niko Matsakis 已提交
2335 2336 2337 2338
        grow_set(self, index, initval, val);
    }
}

2339
trait OwnedEqVector<T:Eq> {
2340 2341 2342
    fn dedup(&mut self);
}

2343
impl<T:Eq> OwnedEqVector<T> for ~[T] {
2344
    #[inline]
N
Niko Matsakis 已提交
2345 2346 2347
    fn dedup(&mut self) {
        dedup(self)
    }
2348 2349
}

2350 2351 2352
pub trait MutableVector<'self, T> {
    fn mut_slice(&mut self, start: uint, end: uint) -> &'self mut [T];

2353 2354
    unsafe fn unsafe_mut_ref(&self, index: uint) -> *mut T;
    unsafe fn unsafe_set(&self, index: uint, val: T);
2355 2356
}

2357 2358 2359 2360 2361 2362
impl<'self,T> MutableVector<'self, T> for &'self mut [T] {
    #[inline]
    fn mut_slice(&mut self, start: uint, end: uint) -> &'self mut [T] {
        mut_slice(*self, start, end)
    }

2363
    #[inline(always)]
2364
    unsafe fn unsafe_mut_ref(&self, index: uint) -> *mut T {
2365 2366
        let pair_ptr: &(*mut T, uint) = transmute(self);
        let (ptr, _) = *pair_ptr;
2367 2368 2369 2370 2371 2372
        ptr.offset(index)
    }

    #[inline(always)]
    unsafe fn unsafe_set(&self, index: uint, val: T) {
        *self.unsafe_mut_ref(index) = val;
2373 2374 2375
    }
}

T
Tim Chevalier 已提交
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
/**
* Constructs a vector from an unsafe pointer to a buffer
*
* # Arguments
*
* * ptr - An unsafe pointer to a buffer of `T`
* * elts - The number of elements in the buffer
*/
// Wrapper for fn in raw: needs to be called by net_tcp::on_tcp_read_cb
pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> ~[T] {
    raw::from_buf_raw(ptr, elts)
}

2389 2390
/// The internal 'unboxed' representation of a vector
pub struct UnboxedVecRepr {
2391 2392
    fill: uint,
    alloc: uint,
2393 2394 2395
    data: u8
}

2396
/// Unsafe operations
2397
pub mod raw {
2398
    use cast::transmute;
2399
    use kinds::Copy;
2400
    use managed;
2401
    use option::{None, Some};
2402 2403
    use ptr;
    use sys;
2404
    use unstable::intrinsics;
2405
    use vec::{UnboxedVecRepr, as_const_buf, as_mut_buf, len, with_capacity};
A
Alex Crichton 已提交
2406
    use util;
2407 2408

    /// The internal representation of a (boxed) vector
G
Graydon Hoare 已提交
2409
    pub struct VecRepr {
2410
        box_header: managed::raw::BoxHeaderRepr,
2411 2412 2413
        unboxed: UnboxedVecRepr
    }

2414
    pub struct SliceRepr {
2415 2416
        data: *u8,
        len: uint
2417
    }
2418

2419 2420 2421 2422 2423 2424 2425
    /**
     * Sets the length of a vector
     *
     * This will explicitly set the size of the vector, without actually
     * modifing its buffers, so it is up to the caller to ensure that
     * the vector is actually the specified size.
     */
2426
    #[inline(always)]
G
Graydon Hoare 已提交
2427
    pub unsafe fn set_len<T>(v: &mut ~[T], new_len: uint) {
2428
        let repr: **mut VecRepr = transmute(v);
2429
        (**repr).unboxed.fill = new_len * sys::nonzero_size_of::<T>();
2430 2431
    }

2432 2433 2434 2435 2436 2437 2438 2439 2440
    /**
     * 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.
     */
2441
    #[inline(always)]
2442 2443 2444 2445 2446
    pub fn to_ptr<T>(v: &[T]) -> *T {
        unsafe {
            let repr: **SliceRepr = transmute(&v);
            transmute(&((**repr).data))
        }
2447 2448
    }

2449
    /** see `to_ptr()` */
2450
    #[inline(always)]
2451 2452 2453 2454 2455
    pub fn to_const_ptr<T>(v: &const [T]) -> *const T {
        unsafe {
            let repr: **SliceRepr = transmute(&v);
            transmute(&((**repr).data))
        }
2456
    }
2457

2458 2459
    /** see `to_ptr()` */
    #[inline(always)]
2460 2461 2462 2463 2464
    pub fn to_mut_ptr<T>(v: &mut [T]) -> *mut T {
        unsafe {
            let repr: **SliceRepr = transmute(&v);
            transmute(&((**repr).data))
        }
2465
    }
2466

2467 2468 2469 2470
    /**
     * Form a slice from a pointer and length (as a number of units,
     * not bytes).
     */
2471
    #[inline(always)]
2472 2473
    pub unsafe fn buf_as_slice<T,U>(p: *T,
                                    len: uint,
2474
                                    f: &fn(v: &[T]) -> U) -> U {
2475
        let pair = (p, len * sys::nonzero_size_of::<T>());
2476
        let v : *(&'blk [T]) = transmute(&pair);
2477 2478
        f(*v)
    }
2479

2480 2481 2482 2483 2484 2485 2486 2487 2488
    /**
     * Form a slice from a pointer and length (as a number of units,
     * not bytes).
     */
    #[inline(always)]
    pub unsafe fn mut_buf_as_slice<T,U>(p: *mut T,
                                        len: uint,
                                        f: &fn(v: &mut [T]) -> U) -> U {
        let pair = (p, len * sys::nonzero_size_of::<T>());
2489
        let v : *(&'blk mut [T]) = transmute(&pair);
2490 2491 2492
        f(*v)
    }

2493 2494 2495 2496
    /**
     * Unchecked vector indexing.
     */
    #[inline(always)]
2497
    pub unsafe fn get<T:Copy>(v: &const [T], i: uint) -> T {
2498
        as_const_buf(v, |p, _len| *ptr::const_offset(p, i))
2499 2500 2501
    }

    /**
N
Niko Matsakis 已提交
2502 2503 2504
     * Unchecked vector index assignment.  Does not drop the
     * old value and hence is only suitable when the vector
     * is newly allocated.
2505 2506
     */
    #[inline(always)]
B
Ben Striegel 已提交
2507
    pub unsafe fn init_elem<T>(v: &mut [T], i: uint, val: T) {
B
Brian Anderson 已提交
2508
        let mut box = Some(val);
2509
        do as_mut_buf(v) |p, _len| {
A
Alex Crichton 已提交
2510
            let box2 = util::replace(&mut box, None);
2511
            intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i)),
D
Daniel Micay 已提交
2512
                                      box2.unwrap());
2513 2514 2515
        }
    }

T
Tim Chevalier 已提交
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
    /**
    * Constructs a vector from an unsafe pointer to a buffer
    *
    * # Arguments
    *
    * * ptr - An unsafe pointer to a buffer of `T`
    * * elts - The number of elements in the buffer
    */
    // Was in raw, but needs to be called by net_tcp::on_tcp_read_cb
    #[inline(always)]
    pub unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
        let mut dst = with_capacity(elts);
        set_len(&mut dst, elts);
2529
        as_mut_buf(dst, |p_dst, _len_dst| ptr::copy_memory(p_dst, ptr, elts));
B
Brian Anderson 已提交
2530
        dst
T
Tim Chevalier 已提交
2531 2532
    }

2533 2534 2535 2536 2537 2538
    /**
      * Copies data from one vector to another.
      *
      * Copies `count` bytes from `src` to `dst`. The source and destination
      * may overlap.
      */
2539
    #[inline(always)]
2540
    pub unsafe fn copy_memory<T>(dst: &mut [T], src: &const [T],
T
Tim Chevalier 已提交
2541
                                 count: uint) {
P
Patrick Walton 已提交
2542 2543
        assert!(dst.len() >= count);
        assert!(src.len() >= count);
2544

2545 2546
        do as_mut_buf(dst) |p_dst, _len_dst| {
            do as_const_buf(src) |p_src, _len_src| {
2547
                ptr::copy_memory(p_dst, p_src, count)
2548 2549 2550
            }
        }
    }
2551 2552
}

2553
/// Operations on `[u8]`
G
Graydon Hoare 已提交
2554
pub mod bytes {
2555 2556
    use libc;
    use uint;
2557
    use vec::raw;
2558
    use vec;
2559

2560
    /// Bytewise string comparison
2561
    pub fn memcmp(a: &~[u8], b: &~[u8]) -> int {
D
Daniel Micay 已提交
2562 2563
        let a_len = a.len();
        let b_len = b.len();
2564
        let n = uint::min(a_len, b_len) as libc::size_t;
2565
        let r = unsafe {
B
Brian Anderson 已提交
2566 2567
            libc::memcmp(raw::to_ptr(*a) as *libc::c_void,
                         raw::to_ptr(*b) as *libc::c_void, n) as int
2568
        };
2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580

        if r != 0 { r } else {
            if a_len == b_len {
                0
            } else if a_len < b_len {
                -1
            } else {
                1
            }
        }
    }

2581
    /// Bytewise less than or equal
2582
    pub fn lt(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) < 0 }
2583

2584
    /// Bytewise less than or equal
2585
    pub fn le(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) <= 0 }
2586

2587
    /// Bytewise equality
2588
    pub fn eq(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) == 0 }
2589

2590
    /// Bytewise inequality
2591
    pub fn ne(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) != 0 }
2592

2593
    /// Bytewise greater than or equal
2594
    pub fn ge(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) >= 0 }
2595

2596
    /// Bytewise greater than
2597
    pub fn gt(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) > 0 }
2598

2599 2600 2601 2602
    /**
      * Copies data from one vector to another.
      *
      * Copies `count` bytes from `src` to `dst`. The source and destination
2603
      * may overlap.
2604
      */
2605
    #[inline(always)]
2606
    pub fn copy_memory(dst: &mut [u8], src: &const [u8], count: uint) {
2607 2608
        // Bound checks are done at vec::raw::copy_memory.
        unsafe { vec::raw::copy_memory(dst, src, count) }
2609
    }
2610 2611
}

2612 2613
// ___________________________________________________________________________
// ITERATION TRAIT METHODS
2614

D
Daniel Micay 已提交
2615
impl<'self,A> old_iter::BaseIter<A> for &'self [A] {
2616
    #[inline(always)]
A
Alex Crichton 已提交
2617 2618 2619
    fn each<'a>(&'a self, blk: &fn(v: &'a A) -> bool) -> bool {
        each(*self, blk)
    }
2620 2621 2622 2623
    #[inline(always)]
    fn size_hint(&self) -> Option<uint> { Some(self.len()) }
}

E
Erick Tryzelaar 已提交
2624
// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2625
impl<A> old_iter::BaseIter<A> for ~[A] {
A
Alex Crichton 已提交
2626 2627 2628 2629
    #[inline(always)]
    fn each<'a>(&'a self, blk: &fn(v: &'a A) -> bool) -> bool {
        each(*self, blk)
    }
2630 2631 2632 2633 2634
    #[inline(always)]
    fn size_hint(&self) -> Option<uint> { Some(self.len()) }
}

// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2635
impl<A> old_iter::BaseIter<A> for @[A] {
A
Alex Crichton 已提交
2636 2637 2638 2639
    #[inline(always)]
    fn each<'a>(&'a self, blk: &fn(v: &'a A) -> bool) -> bool {
        each(*self, blk)
    }
2640 2641 2642 2643
    #[inline(always)]
    fn size_hint(&self) -> Option<uint> { Some(self.len()) }
}

D
Daniel Micay 已提交
2644
impl<'self,A> old_iter::MutableIter<A> for &'self mut [A] {
A
Alex Crichton 已提交
2645 2646 2647 2648
    #[inline(always)]
    fn each_mut<'a>(&'a mut self, blk: &fn(v: &'a mut A) -> bool) -> bool {
        each_mut(*self, blk)
    }
2649 2650
}

D
Daniel Micay 已提交
2651
// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2652
impl<A> old_iter::MutableIter<A> for ~[A] {
A
Alex Crichton 已提交
2653 2654 2655 2656
    #[inline(always)]
    fn each_mut<'a>(&'a mut self, blk: &fn(v: &'a mut A) -> bool) -> bool {
        each_mut(*self, blk)
    }
2657 2658
}

D
Daniel Micay 已提交
2659
// FIXME(#4148): This should be redundant
A
Alex Crichton 已提交
2660 2661 2662 2663 2664 2665 2666
impl<A> old_iter::MutableIter<A> for @mut [A] {
    #[inline(always)]
    fn each_mut(&mut self, blk: &fn(v: &mut A) -> bool) -> bool {
        each_mut(*self, blk)
    }
}

D
Daniel Micay 已提交
2667
impl<'self,A> old_iter::ExtendedIter<A> for &'self [A] {
A
Alex Crichton 已提交
2668 2669 2670
    pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) -> bool {
        old_iter::eachi(self, blk)
    }
2671
    pub fn all(&self, blk: &fn(&A) -> bool) -> bool {
D
Daniel Micay 已提交
2672
        old_iter::all(self, blk)
2673
    }
2674
    pub fn any(&self, blk: &fn(&A) -> bool) -> bool {
D
Daniel Micay 已提交
2675
        old_iter::any(self, blk)
2676
    }
2677
    pub fn foldl<B>(&self, b0: B, blk: &fn(&B, &A) -> B) -> B {
D
Daniel Micay 已提交
2678
        old_iter::foldl(self, b0, blk)
2679
    }
2680
    pub fn position(&self, f: &fn(&A) -> bool) -> Option<uint> {
D
Daniel Micay 已提交
2681
        old_iter::position(self, f)
2682
    }
2683
    fn map_to_vec<B>(&self, op: &fn(&A) -> B) -> ~[B] {
D
Daniel Micay 已提交
2684
        old_iter::map_to_vec(self, op)
2685
    }
2686
    fn flat_map_to_vec<B,IB:BaseIter<B>>(&self, op: &fn(&A) -> IB)
2687
        -> ~[B] {
D
Daniel Micay 已提交
2688
        old_iter::flat_map_to_vec(self, op)
2689
    }
2690 2691
}

D
Daniel Micay 已提交
2692
impl<'self,A> old_iter::ExtendedMutableIter<A> for &'self mut [A] {
2693
    #[inline(always)]
A
Alex Crichton 已提交
2694 2695 2696
    pub fn eachi_mut(&mut self, blk: &fn(uint, v: &mut A) -> bool) -> bool {
        eachi_mut(*self, blk)
    }
2697 2698
}

E
Erick Tryzelaar 已提交
2699
// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2700
impl<A> old_iter::ExtendedIter<A> for ~[A] {
A
Alex Crichton 已提交
2701 2702 2703
    pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) -> bool {
        old_iter::eachi(self, blk)
    }
2704
    pub fn all(&self, blk: &fn(&A) -> bool) -> bool {
D
Daniel Micay 已提交
2705
        old_iter::all(self, blk)
E
Erick Tryzelaar 已提交
2706
    }
2707
    pub fn any(&self, blk: &fn(&A) -> bool) -> bool {
D
Daniel Micay 已提交
2708
        old_iter::any(self, blk)
E
Erick Tryzelaar 已提交
2709
    }
2710
    pub fn foldl<B>(&self, b0: B, blk: &fn(&B, &A) -> B) -> B {
D
Daniel Micay 已提交
2711
        old_iter::foldl(self, b0, blk)
E
Erick Tryzelaar 已提交
2712
    }
2713
    pub fn position(&self, f: &fn(&A) -> bool) -> Option<uint> {
D
Daniel Micay 已提交
2714
        old_iter::position(self, f)
E
Erick Tryzelaar 已提交
2715
    }
2716
    fn map_to_vec<B>(&self, op: &fn(&A) -> B) -> ~[B] {
D
Daniel Micay 已提交
2717
        old_iter::map_to_vec(self, op)
E
Erick Tryzelaar 已提交
2718
    }
2719
    fn flat_map_to_vec<B,IB:BaseIter<B>>(&self, op: &fn(&A) -> IB)
E
Erick Tryzelaar 已提交
2720
        -> ~[B] {
D
Daniel Micay 已提交
2721
        old_iter::flat_map_to_vec(self, op)
E
Erick Tryzelaar 已提交
2722 2723 2724 2725
    }
}

// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2726
impl<A> old_iter::ExtendedIter<A> for @[A] {
A
Alex Crichton 已提交
2727 2728 2729
    pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) -> bool {
        old_iter::eachi(self, blk)
    }
2730
    pub fn all(&self, blk: &fn(&A) -> bool) -> bool {
D
Daniel Micay 已提交
2731
        old_iter::all(self, blk)
E
Erick Tryzelaar 已提交
2732
    }
2733
    pub fn any(&self, blk: &fn(&A) -> bool) -> bool {
D
Daniel Micay 已提交
2734
        old_iter::any(self, blk)
E
Erick Tryzelaar 已提交
2735
    }
2736
    pub fn foldl<B>(&self, b0: B, blk: &fn(&B, &A) -> B) -> B {
D
Daniel Micay 已提交
2737
        old_iter::foldl(self, b0, blk)
E
Erick Tryzelaar 已提交
2738
    }
2739
    pub fn position(&self, f: &fn(&A) -> bool) -> Option<uint> {
D
Daniel Micay 已提交
2740
        old_iter::position(self, f)
E
Erick Tryzelaar 已提交
2741
    }
2742
    fn map_to_vec<B>(&self, op: &fn(&A) -> B) -> ~[B] {
D
Daniel Micay 已提交
2743
        old_iter::map_to_vec(self, op)
E
Erick Tryzelaar 已提交
2744
    }
2745
    fn flat_map_to_vec<B,IB:BaseIter<B>>(&self, op: &fn(&A) -> IB)
E
Erick Tryzelaar 已提交
2746
        -> ~[B] {
D
Daniel Micay 已提交
2747
        old_iter::flat_map_to_vec(self, op)
E
Erick Tryzelaar 已提交
2748 2749 2750
    }
}

D
Daniel Micay 已提交
2751 2752 2753
impl<'self,A:Eq> old_iter::EqIter<A> for &'self [A] {
    pub fn contains(&self, x: &A) -> bool { old_iter::contains(self, x) }
    pub fn count(&self, x: &A) -> uint { old_iter::count(self, x) }
2754 2755
}

E
Erick Tryzelaar 已提交
2756
// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2757 2758 2759
impl<A:Eq> old_iter::EqIter<A> for ~[A] {
    pub fn contains(&self, x: &A) -> bool { old_iter::contains(self, x) }
    pub fn count(&self, x: &A) -> uint { old_iter::count(self, x) }
E
Erick Tryzelaar 已提交
2760 2761 2762
}

// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2763 2764 2765
impl<A:Eq> old_iter::EqIter<A> for @[A] {
    pub fn contains(&self, x: &A) -> bool { old_iter::contains(self, x) }
    pub fn count(&self, x: &A) -> uint { old_iter::count(self, x) }
E
Erick Tryzelaar 已提交
2766 2767
}

D
Daniel Micay 已提交
2768
impl<'self,A:Copy> old_iter::CopyableIter<A> for &'self [A] {
2769
    fn filter_to_vec(&self, pred: &fn(&A) -> bool) -> ~[A] {
D
Daniel Micay 已提交
2770
        old_iter::filter_to_vec(self, pred)
2771
    }
D
Daniel Micay 已提交
2772
    fn to_vec(&self) -> ~[A] { old_iter::to_vec(self) }
2773
    pub fn find(&self, f: &fn(&A) -> bool) -> Option<A> {
D
Daniel Micay 已提交
2774
        old_iter::find(self, f)
G
Graydon Hoare 已提交
2775
    }
2776 2777
}

E
Erick Tryzelaar 已提交
2778
// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2779
impl<A:Copy> old_iter::CopyableIter<A> for ~[A] {
2780
    fn filter_to_vec(&self, pred: &fn(&A) -> bool) -> ~[A] {
D
Daniel Micay 已提交
2781
        old_iter::filter_to_vec(self, pred)
E
Erick Tryzelaar 已提交
2782
    }
D
Daniel Micay 已提交
2783
    fn to_vec(&self) -> ~[A] { old_iter::to_vec(self) }
2784
    pub fn find(&self, f: &fn(&A) -> bool) -> Option<A> {
D
Daniel Micay 已提交
2785
        old_iter::find(self, f)
E
Erick Tryzelaar 已提交
2786 2787 2788 2789
    }
}

// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2790
impl<A:Copy> old_iter::CopyableIter<A> for @[A] {
2791
    fn filter_to_vec(&self, pred: &fn(&A) -> bool) -> ~[A] {
D
Daniel Micay 已提交
2792
        old_iter::filter_to_vec(self, pred)
E
Erick Tryzelaar 已提交
2793
    }
D
Daniel Micay 已提交
2794
    fn to_vec(&self) -> ~[A] { old_iter::to_vec(self) }
2795
    pub fn find(&self, f: &fn(&A) -> bool) -> Option<A> {
D
Daniel Micay 已提交
2796
        old_iter::find(self, f)
E
Erick Tryzelaar 已提交
2797 2798 2799
    }
}

D
Daniel Micay 已提交
2800 2801 2802
impl<'self,A:Copy + Ord> old_iter::CopyableOrderedIter<A> for &'self [A] {
    fn min(&self) -> A { old_iter::min(self) }
    fn max(&self) -> A { old_iter::max(self) }
2803
}
2804

E
Erick Tryzelaar 已提交
2805
// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2806 2807 2808
impl<A:Copy + Ord> old_iter::CopyableOrderedIter<A> for ~[A] {
    fn min(&self) -> A { old_iter::min(self) }
    fn max(&self) -> A { old_iter::max(self) }
E
Erick Tryzelaar 已提交
2809 2810 2811
}

// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2812 2813 2814
impl<A:Copy + Ord> old_iter::CopyableOrderedIter<A> for @[A] {
    fn min(&self) -> A { old_iter::min(self) }
    fn max(&self) -> A { old_iter::max(self) }
E
Erick Tryzelaar 已提交
2815 2816
}

D
Daniel Micay 已提交
2817
impl<'self,A:Copy> old_iter::CopyableNonstrictIter<A> for &'self [A] {
2818
    fn each_val(&const self, f: &fn(A) -> bool) -> bool {
2819 2820
        let mut i = 0;
        while i < self.len() {
2821
            if !f(copy self[i]) { return false; }
2822 2823
            i += 1;
        }
2824
        return true;
2825 2826 2827
    }
}

E
Erick Tryzelaar 已提交
2828
// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2829
impl<A:Copy> old_iter::CopyableNonstrictIter<A> for ~[A] {
2830
    fn each_val(&const self, f: &fn(A) -> bool) -> bool {
2831
        let mut i = 0;
2832
        while i < uniq_len(self) {
2833
            if !f(copy self[i]) { return false; }
2834 2835
            i += 1;
        }
2836
        return true;
2837 2838 2839
    }
}

E
Erick Tryzelaar 已提交
2840
// FIXME(#4148): This should be redundant
D
Daniel Micay 已提交
2841
impl<A:Copy> old_iter::CopyableNonstrictIter<A> for @[A] {
2842
    fn each_val(&const self, f: &fn(A) -> bool) -> bool {
2843 2844
        let mut i = 0;
        while i < self.len() {
2845
            if !f(copy self[i]) { return false; }
2846 2847
            i += 1;
        }
2848
        return true;
2849 2850 2851
    }
}

B
Ben Striegel 已提交
2852 2853 2854
impl<A:Clone> Clone for ~[A] {
    #[inline]
    fn clone(&self) -> ~[A] {
2855
        self.map(|item| item.clone())
B
Ben Striegel 已提交
2856 2857 2858
    }
}

D
Daniel Micay 已提交
2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879
// could be implemented with &[T] with .slice(), but this avoids bounds checks
pub struct VecIterator<'self, T> {
    priv ptr: *T,
    priv end: *T,
    priv lifetime: &'self T // FIXME: #5922
}

impl<'self, T> Iterator<&'self T> for VecIterator<'self, T> {
    #[inline]
    fn next(&mut self) -> Option<&'self T> {
        unsafe {
            if self.ptr == self.end {
                None
            } else {
                let old = self.ptr;
                self.ptr = self.ptr.offset(1);
                Some(cast::transmute(old))
            }
        }
    }
}
2880

2881 2882
#[cfg(test)]
mod tests {
2883
    use option::{None, Option, Some};
2884
    use sys;
2885
    use vec::*;
D
Daniel Micay 已提交
2886
    use cmp::*;
2887

D
Daniel Micay 已提交
2888
    fn square(n: uint) -> uint { n * n }
2889

D
Daniel Micay 已提交
2890
    fn square_ref(n: &uint) -> uint { square(*n) }
2891

2892
    fn is_three(n: &uint) -> bool { *n == 3u }
2893

2894
    fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
2895

2896
    fn is_equal(x: &uint, y:&uint) -> bool { *x == *y }
2897

2898
    fn square_if_odd_r(n: &uint) -> Option<uint> {
D
Daniel Micay 已提交
2899
        if *n % 2u == 1u { Some(*n * *n) } else { None }
2900 2901
    }

2902
    fn square_if_odd_v(n: uint) -> Option<uint> {
D
Daniel Micay 已提交
2903
        if n % 2u == 1u { Some(n * n) } else { None }
2904 2905
    }

D
Daniel Micay 已提交
2906
    fn add(x: uint, y: &uint) -> uint { x + *y }
2907 2908

    #[test]
2909 2910 2911
    fn test_unsafe_ptrs() {
        unsafe {
            // Test on-stack copy-from-buf.
2912
            let a = ~[1, 2, 3];
B
Brian Anderson 已提交
2913
            let mut ptr = raw::to_ptr(a);
T
Tim Chevalier 已提交
2914
            let b = from_buf(ptr, 3u);
2915 2916 2917 2918
            assert_eq!(b.len(), 3u);
            assert_eq!(b[0], 1);
            assert_eq!(b[1], 2);
            assert_eq!(b[2], 3);
2919 2920

            // Test on-heap copy-from-buf.
2921
            let c = ~[1, 2, 3, 4, 5];
B
Brian Anderson 已提交
2922
            ptr = raw::to_ptr(c);
T
Tim Chevalier 已提交
2923
            let d = from_buf(ptr, 5u);
2924 2925 2926 2927 2928 2929
            assert_eq!(d.len(), 5u);
            assert_eq!(d[0], 1);
            assert_eq!(d[1], 2);
            assert_eq!(d[2], 3);
            assert_eq!(d[3], 4);
            assert_eq!(d[4], 5);
2930
        }
2931 2932 2933
    }

    #[test]
2934 2935
    fn test_from_fn() {
        // Test on-stack from_fn.
2936
        let mut v = from_fn(3u, square);
2937 2938 2939 2940
        assert_eq!(v.len(), 3u);
        assert_eq!(v[0], 0u);
        assert_eq!(v[1], 1u);
        assert_eq!(v[2], 4u);
2941

2942 2943
        // Test on-heap from_fn.
        v = from_fn(5u, square);
2944 2945 2946 2947 2948 2949
        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);
2950 2951 2952
    }

    #[test]
2953 2954
    fn test_from_elem() {
        // Test on-stack from_elem.
2955
        let mut v = from_elem(2u, 10u);
2956 2957 2958
        assert_eq!(v.len(), 2u);
        assert_eq!(v[0], 10u);
        assert_eq!(v[1], 10u);
2959

2960 2961
        // Test on-heap from_elem.
        v = from_elem(6u, 20u);
2962 2963 2964 2965 2966 2967
        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);
2968 2969 2970 2971
    }

    #[test]
    fn test_is_empty() {
E
Erick Tryzelaar 已提交
2972 2973
        assert!(is_empty::<int>([]));
        assert!(!is_empty([0]));
2974 2975
    }

2976 2977
    #[test]
    fn test_len_divzero() {
2978
        type Z = [i8, ..0];
2979 2980 2981
        let v0 : &[Z] = &[];
        let v1 : &[Z] = &[[]];
        let v2 : &[Z] = &[[], []];
2982 2983 2984 2985
        assert_eq!(sys::size_of::<Z>(), 0);
        assert_eq!(v0.len(), 0);
        assert_eq!(v1.len(), 1);
        assert_eq!(v2.len(), 2);
2986 2987
    }

2988 2989
    #[test]
    fn test_head() {
2990
        let mut a = ~[11];
2991
        assert_eq!(a.head(), &11);
2992
        a = ~[11, 12];
2993
        assert_eq!(a.head(), &11);
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
    }

    #[test]
    #[should_fail]
    #[ignore(cfg(windows))]
    fn test_head_empty() {
        let a: ~[int] = ~[];
        a.head();
    }

    #[test]
    fn test_head_opt() {
        let mut a = ~[];
3007
        assert_eq!(a.head_opt(), None);
3008
        a = ~[11];
3009
        assert_eq!(a.head_opt().unwrap(), &11);
3010
        a = ~[11, 12];
3011
        assert_eq!(a.head_opt().unwrap(), &11);
3012 3013 3014 3015
    }

    #[test]
    fn test_tail() {
3016
        let mut a = ~[11];
3017
        assert_eq!(a.tail(), &[]);
3018
        a = ~[11, 12];
3019
        assert_eq!(a.tail(), &[12]);
3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032
    }

    #[test]
    #[should_fail]
    #[ignore(cfg(windows))]
    fn test_tail_empty() {
        let a: ~[int] = ~[];
        a.tail();
    }

    #[test]
    fn test_tailn() {
        let mut a = ~[11, 12, 13];
3033
        assert_eq!(a.tailn(0), &[11, 12, 13]);
3034
        a = ~[11, 12, 13];
3035
        assert_eq!(a.tailn(2), &[13]);
3036 3037 3038 3039 3040 3041 3042 3043
    }

    #[test]
    #[should_fail]
    #[ignore(cfg(windows))]
    fn test_tailn_empty() {
        let a: ~[int] = ~[];
        a.tailn(2);
3044 3045
    }

3046 3047 3048
    #[test]
    fn test_init() {
        let mut a = ~[11];
3049
        assert_eq!(a.init(), &[]);
3050
        a = ~[11, 12];
3051
        assert_eq!(a.init(), &[11]);
3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064
    }

    #[init]
    #[should_fail]
    #[ignore(cfg(windows))]
    fn test_init_empty() {
        let a: ~[int] = ~[];
        a.init();
    }

    #[test]
    fn test_initn() {
        let mut a = ~[11, 12, 13];
3065
        assert_eq!(a.initn(0), &[11, 12, 13]);
3066
        a = ~[11, 12, 13];
3067
        assert_eq!(a.initn(2), &[11]);
3068 3069 3070 3071 3072 3073 3074 3075 3076 3077
    }

    #[init]
    #[should_fail]
    #[ignore(cfg(windows))]
    fn test_initn_empty() {
        let a: ~[int] = ~[];
        a.initn(2);
    }

3078 3079
    #[test]
    fn test_last() {
3080
        let mut a = ~[11];
3081
        assert_eq!(a.last(), &11);
3082
        a = ~[11, 12];
3083
        assert_eq!(a.last(), &12);
3084 3085 3086 3087
    }

    #[test]
    #[should_fail]
J
Jeff Olson 已提交
3088
    #[ignore(cfg(windows))]
3089 3090 3091 3092 3093 3094 3095 3096
    fn test_last_empty() {
        let a: ~[int] = ~[];
        a.last();
    }

    #[test]
    fn test_last_opt() {
        let mut a = ~[];
3097
        assert_eq!(a.last_opt(), None);
3098
        a = ~[11];
3099
        assert_eq!(a.last_opt().unwrap(), &11);
3100
        a = ~[11, 12];
3101
        assert_eq!(a.last_opt().unwrap(), &12);
3102 3103 3104 3105
    }

    #[test]
    fn test_slice() {
3106 3107
        // Test fixed length vector.
        let vec_fixed = [1, 2, 3, 4];
D
Daniel Micay 已提交
3108
        let v_a = slice(vec_fixed, 1u, vec_fixed.len()).to_vec();
3109 3110 3111 3112
        assert_eq!(v_a.len(), 3u);
        assert_eq!(v_a[0], 2);
        assert_eq!(v_a[1], 3);
        assert_eq!(v_a[2], 4);
3113 3114 3115 3116

        // Test on stack.
        let vec_stack = &[1, 2, 3];
        let v_b = slice(vec_stack, 1u, 3u).to_vec();
3117 3118 3119
        assert_eq!(v_b.len(), 2u);
        assert_eq!(v_b[0], 2);
        assert_eq!(v_b[1], 3);
3120 3121 3122 3123

        // Test on managed heap.
        let vec_managed = @[1, 2, 3, 4, 5];
        let v_c = slice(vec_managed, 0u, 3u).to_vec();
3124 3125 3126 3127
        assert_eq!(v_c.len(), 3u);
        assert_eq!(v_c[0], 1);
        assert_eq!(v_c[1], 2);
        assert_eq!(v_c[2], 3);
3128 3129 3130 3131

        // Test on exchange heap.
        let vec_unique = ~[1, 2, 3, 4, 5, 6];
        let v_d = slice(vec_unique, 1u, 6u).to_vec();
3132 3133 3134 3135 3136 3137
        assert_eq!(v_d.len(), 5u);
        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);
3138 3139 3140 3141 3142
    }

    #[test]
    fn test_pop() {
        // Test on-heap pop.
3143 3144
        let mut v = ~[1, 2, 3, 4, 5];
        let e = v.pop();
3145 3146 3147 3148 3149 3150
        assert_eq!(v.len(), 4u);
        assert_eq!(v[0], 1);
        assert_eq!(v[1], 2);
        assert_eq!(v[2], 3);
        assert_eq!(v[3], 4);
        assert_eq!(e, 5);
3151 3152
    }

B
Ben Blum 已提交
3153 3154 3155
    #[test]
    fn test_swap_remove() {
        let mut v = ~[1, 2, 3, 4, 5];
N
Niko Matsakis 已提交
3156
        let mut e = v.swap_remove(0);
3157 3158 3159
        assert_eq!(v.len(), 4);
        assert_eq!(e, 1);
        assert_eq!(v[0], 5);
N
Niko Matsakis 已提交
3160
        e = v.swap_remove(3);
3161 3162 3163 3164 3165
        assert_eq!(v.len(), 3);
        assert_eq!(e, 4);
        assert_eq!(v[0], 5);
        assert_eq!(v[1], 2);
        assert_eq!(v[2], 3);
B
Ben Blum 已提交
3166 3167 3168 3169 3170
    }

    #[test]
    fn test_swap_remove_noncopyable() {
        // Tests that we don't accidentally run destructors twice.
3171 3172 3173
        let mut v = ~[::unstable::sync::exclusive(()),
                      ::unstable::sync::exclusive(()),
                      ::unstable::sync::exclusive(())];
N
Niko Matsakis 已提交
3174
        let mut _e = v.swap_remove(0);
3175
        assert_eq!(v.len(), 2);
N
Niko Matsakis 已提交
3176
        _e = v.swap_remove(1);
3177
        assert_eq!(v.len(), 1);
N
Niko Matsakis 已提交
3178
        _e = v.swap_remove(0);
3179
        assert_eq!(v.len(), 0);
B
Ben Blum 已提交
3180 3181
    }

3182 3183 3184
    #[test]
    fn test_push() {
        // Test on-stack push().
3185
        let mut v = ~[];
3186
        v.push(1);
3187 3188
        assert_eq!(v.len(), 1u);
        assert_eq!(v[0], 1);
3189 3190

        // Test on-heap push().
3191
        v.push(2);
3192 3193 3194
        assert_eq!(v.len(), 2u);
        assert_eq!(v[0], 1);
        assert_eq!(v[1], 2);
3195 3196 3197 3198 3199
    }

    #[test]
    fn test_grow() {
        // Test on-stack grow().
3200
        let mut v = ~[];
N
Niko Matsakis 已提交
3201
        v.grow(2u, &1);
3202 3203 3204
        assert_eq!(v.len(), 2u);
        assert_eq!(v[0], 1);
        assert_eq!(v[1], 1);
3205 3206

        // Test on-heap grow().
N
Niko Matsakis 已提交
3207
        v.grow(3u, &2);
3208 3209 3210 3211 3212 3213
        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);
3214 3215 3216 3217
    }

    #[test]
    fn test_grow_fn() {
3218
        let mut v = ~[];
N
Niko Matsakis 已提交
3219
        v.grow_fn(3u, square);
3220 3221 3222 3223
        assert_eq!(v.len(), 3u);
        assert_eq!(v[0], 0u);
        assert_eq!(v[1], 1u);
        assert_eq!(v[2], 4u);
3224 3225 3226 3227
    }

    #[test]
    fn test_grow_set() {
3228
        let mut v = ~[1, 2, 3];
N
Niko Matsakis 已提交
3229
        v.grow_set(4u, &4, 5);
3230 3231 3232 3233 3234 3235
        assert_eq!(v.len(), 5u);
        assert_eq!(v[0], 1);
        assert_eq!(v[1], 2);
        assert_eq!(v[2], 3);
        assert_eq!(v[3], 4);
        assert_eq!(v[4], 5);
3236 3237
    }

3238 3239 3240
    #[test]
    fn test_truncate() {
        let mut v = ~[@6,@5,@4];
N
Niko Matsakis 已提交
3241
        v.truncate(1);
3242 3243
        assert_eq!(v.len(), 1);
        assert_eq!(*(v[0]), 6);
3244 3245
        // If the unsafe block didn't drop things properly, we blow up here.
    }
D
Daniel Micay 已提交
3246 3247 3248 3249 3250

    #[test]
    fn test_clear() {
        let mut v = ~[@6,@5,@4];
        v.clear();
3251
        assert_eq!(v.len(), 0);
D
Daniel Micay 已提交
3252 3253
        // If the unsafe block didn't drop things properly, we blow up here.
    }
3254

3255 3256
    #[test]
    fn test_dedup() {
T
Tim Chevalier 已提交
3257
        fn case(a: ~[uint], b: ~[uint]) {
B
Brian Anderson 已提交
3258
            let mut v = a;
N
Niko Matsakis 已提交
3259
            v.dedup();
3260
            assert_eq!(v, b);
3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274
        }
        case(~[], ~[]);
        case(~[1], ~[1]);
        case(~[1,1], ~[1]);
        case(~[1,2,3], ~[1,2,3]);
        case(~[1,1,2,3], ~[1,2,3]);
        case(~[1,2,2,3], ~[1,2,3]);
        case(~[1,2,3,3], ~[1,2,3]);
        case(~[1,1,2,2,2,3,3], ~[1,2,3]);
    }

    #[test]
    fn test_dedup_unique() {
        let mut v0 = ~[~1, ~1, ~2, ~3];
N
Niko Matsakis 已提交
3275
        v0.dedup();
3276
        let mut v1 = ~[~1, ~2, ~2, ~3];
N
Niko Matsakis 已提交
3277
        v1.dedup();
3278
        let mut v2 = ~[~1, ~2, ~3, ~3];
N
Niko Matsakis 已提交
3279
        v2.dedup();
3280 3281 3282 3283 3284 3285 3286 3287 3288
        /*
         * If the ~pointers were leaked or otherwise misused, valgrind and/or
         * rustrt should raise errors.
         */
    }

    #[test]
    fn test_dedup_shared() {
        let mut v0 = ~[@1, @1, @2, @3];
N
Niko Matsakis 已提交
3289
        v0.dedup();
3290
        let mut v1 = ~[@1, @2, @2, @3];
N
Niko Matsakis 已提交
3291
        v1.dedup();
3292
        let mut v2 = ~[@1, @2, @3, @3];
N
Niko Matsakis 已提交
3293
        v2.dedup();
3294 3295 3296 3297 3298 3299
        /*
         * If the @pointers were leaked or otherwise misused, valgrind and/or
         * rustrt should raise errors.
         */
    }

3300 3301 3302
    #[test]
    fn test_map() {
        // Test on-stack map.
3303
        let mut v = ~[1u, 2u, 3u];
3304
        let mut w = map(v, square_ref);
3305 3306 3307 3308
        assert_eq!(w.len(), 3u);
        assert_eq!(w[0], 1u);
        assert_eq!(w[1], 4u);
        assert_eq!(w[2], 9u);
3309 3310

        // Test on-heap map.
3311
        v = ~[1u, 2u, 3u, 4u, 5u];
3312
        w = map(v, square_ref);
3313 3314 3315 3316 3317 3318
        assert_eq!(w.len(), 5u);
        assert_eq!(w[0], 1u);
        assert_eq!(w[1], 4u);
        assert_eq!(w[2], 9u);
        assert_eq!(w[3], 16u);
        assert_eq!(w[4], 25u);
3319 3320 3321
    }

    #[test]
3322
    fn test_map_zip() {
D
Daniel Micay 已提交
3323
        fn times(x: &int, y: &int) -> int { *x * *y }
3324
        let f = times;
3325 3326
        let v0 = ~[1, 2, 3, 4, 5];
        let v1 = ~[5, 4, 3, 2, 1];
3327
        let u = map_zip::<int, int, int>(v0, v1, f);
3328
        let mut i = 0;
P
Patrick Walton 已提交
3329
        while i < 5 { assert!(v0[i] * v1[i] == u[i]); i += 1; }
3330 3331 3332
    }

    #[test]
3333
    fn test_filter_mapped() {
3334
        // Test on-stack filter-map.
3335
        let mut v = ~[1u, 2u, 3u];
3336
        let mut w = filter_mapped(v, square_if_odd_r);
3337 3338 3339
        assert_eq!(w.len(), 2u);
        assert_eq!(w[0], 1u);
        assert_eq!(w[1], 9u);
3340 3341

        // Test on-heap filter-map.
3342
        v = ~[1u, 2u, 3u, 4u, 5u];
3343
        w = filter_mapped(v, square_if_odd_r);
3344 3345 3346 3347
        assert_eq!(w.len(), 3u);
        assert_eq!(w[0], 1u);
        assert_eq!(w[1], 9u);
        assert_eq!(w[2], 25u);
3348

N
Niko Matsakis 已提交
3349 3350
        fn halve(i: &int) -> Option<int> {
            if *i % 2 == 0 {
D
Daniel Micay 已提交
3351
                Some::<int>(*i / 2)
3352
            } else {
D
Daniel Micay 已提交
3353
                None::<int>
3354
            }
3355
        }
D
Daniel Micay 已提交
3356
        fn halve_for_sure(i: &int) -> int { *i / 2 }
3357 3358 3359 3360 3361
        let all_even: ~[int] = ~[0, 2, 8, 6];
        let all_odd1: ~[int] = ~[1, 7, 3];
        let all_odd2: ~[int] = ~[];
        let mix: ~[int] = ~[9, 2, 6, 7, 1, 0, 0, 3];
        let mix_dest: ~[int] = ~[1, 3, 0, 0];
P
Patrick Walton 已提交
3362
        assert!(filter_mapped(all_even, halve) ==
3363
                     map(all_even, halve_for_sure));
3364 3365 3366
        assert_eq!(filter_mapped(all_odd1, halve), ~[]);
        assert_eq!(filter_mapped(all_odd2, halve), ~[]);
        assert_eq!(filter_mapped(mix, halve), mix_dest);
3367 3368 3369 3370 3371 3372 3373
    }

    #[test]
    fn test_filter_map() {
        // Test on-stack filter-map.
        let mut v = ~[1u, 2u, 3u];
        let mut w = filter_map(v, square_if_odd_v);
3374 3375 3376
        assert_eq!(w.len(), 2u);
        assert_eq!(w[0], 1u);
        assert_eq!(w[1], 9u);
3377 3378 3379 3380

        // Test on-heap filter-map.
        v = ~[1u, 2u, 3u, 4u, 5u];
        w = filter_map(v, square_if_odd_v);
3381 3382 3383 3384
        assert_eq!(w.len(), 3u);
        assert_eq!(w[0], 1u);
        assert_eq!(w[1], 9u);
        assert_eq!(w[2], 25u);
3385 3386 3387

        fn halve(i: int) -> Option<int> {
            if i % 2 == 0 {
D
Daniel Micay 已提交
3388
                Some::<int>(i / 2)
3389
            } else {
D
Daniel Micay 已提交
3390
                None::<int>
3391 3392
            }
        }
D
Daniel Micay 已提交
3393
        fn halve_for_sure(i: &int) -> int { *i / 2 }
3394 3395 3396 3397 3398 3399
        let all_even: ~[int] = ~[0, 2, 8, 6];
        let all_even0: ~[int] = copy all_even;
        let all_odd1: ~[int] = ~[1, 7, 3];
        let all_odd2: ~[int] = ~[];
        let mix: ~[int] = ~[9, 2, 6, 7, 1, 0, 0, 3];
        let mix_dest: ~[int] = ~[1, 3, 0, 0];
P
Patrick Walton 已提交
3400
        assert!(filter_map(all_even, halve) ==
3401
                     map(all_even0, halve_for_sure));
3402 3403 3404
        assert_eq!(filter_map(all_odd1, halve), ~[]);
        assert_eq!(filter_map(all_odd2, halve), ~[]);
        assert_eq!(filter_map(mix, halve), mix_dest);
3405 3406 3407 3408
    }

    #[test]
    fn test_filter() {
3409 3410
        assert_eq!(filter(~[1u, 2u, 3u], is_odd), ~[1u, 3u]);
        assert_eq!(filter(~[1u, 2u, 4u, 8u, 16u], is_three), ~[]);
3411 3412
    }

S
Seo Sanghyeon 已提交
3413 3414 3415 3416
    #[test]
    fn test_retain() {
        let mut v = ~[1, 2, 3, 4, 5];
        v.retain(is_odd);
3417
        assert_eq!(v, ~[1, 3, 5]);
S
Seo Sanghyeon 已提交
3418 3419
    }

3420 3421 3422
    #[test]
    fn test_foldl() {
        // Test on-stack fold.
3423
        let mut v = ~[1u, 2u, 3u];
3424
        let mut sum = foldl(0u, v, add);
3425
        assert_eq!(sum, 6u);
3426 3427

        // Test on-heap fold.
3428
        v = ~[1u, 2u, 3u, 4u, 5u];
3429
        sum = foldl(0u, v, add);
3430
        assert_eq!(sum, 15u);
3431 3432 3433 3434
    }

    #[test]
    fn test_foldl2() {
T
Tim Chevalier 已提交
3435
        fn sub(a: int, b: &int) -> int {
N
Niko Matsakis 已提交
3436
            a - *b
3437
        }
3438
        let v = ~[1, 2, 3, 4];
3439
        let sum = foldl(0, v, sub);
3440
        assert_eq!(sum, -10);
3441 3442 3443 3444
    }

    #[test]
    fn test_foldr() {
T
Tim Chevalier 已提交
3445
        fn sub(a: &int, b: int) -> int {
N
Niko Matsakis 已提交
3446
            *a - b
3447
        }
3448
        let v = ~[1, 2, 3, 4];
3449
        let sum = foldr(v, 0, sub);
3450
        assert_eq!(sum, -2);
3451 3452 3453
    }

    #[test]
3454
    fn test_each_empty() {
E
Erick Tryzelaar 已提交
3455
        for each::<int>([]) |_v| {
3456
            fail!(); // should never be executed
3457
        }
3458 3459 3460
    }

    #[test]
Y
Youngsoo Son 已提交
3461
    fn test_each_nonempty() {
3462
        let mut i = 0;
E
Erick Tryzelaar 已提交
3463
        for each([1, 2, 3]) |v| {
3464 3465
            i += *v;
        }
3466
        assert_eq!(i, 6);
3467 3468 3469
    }

    #[test]
Y
Youngsoo Son 已提交
3470
    fn test_eachi() {
3471
        let mut i = 0;
E
Erick Tryzelaar 已提交
3472
        for eachi([1, 2, 3]) |j, v| {
P
Patrick Walton 已提交
3473
            if i == 0 { assert!(*v == 1); }
3474
            assert_eq!(j + 1u, *v as uint);
3475
            i += *v;
3476
        }
3477
        assert_eq!(i, 6);
3478 3479 3480
    }

    #[test]
3481 3482 3483
    fn test_each_reverse_empty() {
        let v: ~[int] = ~[];
        for v.each_reverse |_v| {
3484
            fail!(); // should never execute
3485
        }
3486 3487 3488
    }

    #[test]
3489
    fn test_each_reverse_nonempty() {
3490
        let mut i = 0;
E
Erick Tryzelaar 已提交
3491
        for each_reverse([1, 2, 3]) |v| {
P
Patrick Walton 已提交
3492
            if i == 0 { assert!(*v == 3); }
3493
            i += *v
3494
        }
3495
        assert_eq!(i, 6);
3496 3497 3498
    }

    #[test]
3499
    fn test_eachi_reverse() {
3500
        let mut i = 0;
E
Erick Tryzelaar 已提交
3501
        for eachi_reverse([0, 1, 2]) |j, v| {
P
Patrick Walton 已提交
3502
            if i == 0 { assert!(*v == 2); }
3503
            assert_eq!(j, *v as uint);
3504
            i += *v;
3505
        }
3506
        assert_eq!(i, 3);
3507 3508
    }

3509 3510 3511 3512 3513 3514 3515 3516
    #[test]
    fn test_eachi_reverse_empty() {
        let v: ~[int] = ~[];
        for v.eachi_reverse |_i, _v| {
            fail!(); // should never execute
        }
    }

3517
    #[test]
N
Niko Matsakis 已提交
3518
    fn test_each_permutation() {
3519
        let mut results: ~[~[int]];
3520

3521
        results = ~[];
E
Erick Tryzelaar 已提交
3522
        for each_permutation([]) |v| { results.push(to_owned(v)); }
3523
        assert_eq!(results, ~[~[]]);
3524

3525
        results = ~[];
E
Erick Tryzelaar 已提交
3526
        for each_permutation([7]) |v| { results.push(to_owned(v)); }
3527
        assert_eq!(results, ~[~[7]]);
3528

3529
        results = ~[];
E
Erick Tryzelaar 已提交
3530
        for each_permutation([1,1]) |v| { results.push(to_owned(v)); }
3531
        assert_eq!(results, ~[~[1,1],~[1,1]]);
3532

3533
        results = ~[];
E
Erick Tryzelaar 已提交
3534
        for each_permutation([5,2,0]) |v| { results.push(to_owned(v)); }
P
Patrick Walton 已提交
3535
        assert!(results ==
3536
            ~[~[5,2,0],~[5,0,2],~[2,5,0],~[2,0,5],~[0,5,2],~[0,2,5]]);
3537 3538 3539 3540
    }

    #[test]
    fn test_any_and_all() {
E
Erick Tryzelaar 已提交
3541 3542 3543 3544
        assert!(any([1u, 2u, 3u], is_three));
        assert!(!any([0u, 1u, 2u], is_three));
        assert!(any([1u, 2u, 3u, 4u, 5u], is_three));
        assert!(!any([1u, 2u, 4u, 5u, 6u], is_three));
3545

E
Erick Tryzelaar 已提交
3546 3547 3548 3549
        assert!(all([3u, 3u, 3u], is_three));
        assert!(!all([3u, 3u, 2u], is_three));
        assert!(all([3u, 3u, 3u, 3u, 3u], is_three));
        assert!(!all([3u, 3u, 0u, 1u, 2u], is_three));
3550 3551 3552 3553 3554
    }

    #[test]
    fn test_any2_and_all2() {

E
Erick Tryzelaar 已提交
3555 3556 3557 3558
        assert!(any2([2u, 4u, 6u], [2u, 4u, 6u], is_equal));
        assert!(any2([1u, 2u, 3u], [4u, 5u, 3u], is_equal));
        assert!(!any2([1u, 2u, 3u], [4u, 5u, 6u], is_equal));
        assert!(any2([2u, 4u, 6u], [2u, 4u], is_equal));
3559

E
Erick Tryzelaar 已提交
3560 3561 3562 3563
        assert!(all2([2u, 4u, 6u], [2u, 4u, 6u], is_equal));
        assert!(!all2([1u, 2u, 3u], [4u, 5u, 3u], is_equal));
        assert!(!all2([1u, 2u, 3u], [4u, 5u, 6u], is_equal));
        assert!(!all2([2u, 4u, 6u], [2u, 4u], is_equal));
3564 3565 3566 3567
    }

    #[test]
    fn test_zip_unzip() {
3568 3569
        let v1 = ~[1, 2, 3];
        let v2 = ~[4, 5, 6];
3570

B
Brian Anderson 已提交
3571
        let z1 = zip(v1, v2);
3572

3573 3574 3575
        assert_eq!((1, 4), z1[0]);
        assert_eq!((2, 5), z1[1]);
        assert_eq!((3, 6), z1[2]);
3576

B
Brian Anderson 已提交
3577
        let (left, right) = unzip(z1);
3578

3579 3580 3581
        assert_eq!((1, 4), (left[0], right[0]));
        assert_eq!((2, 5), (left[1], right[1]));
        assert_eq!((3, 6), (left[2], right[2]));
3582 3583 3584
    }

    #[test]
3585
    fn test_position_elem() {
E
Erick Tryzelaar 已提交
3586
        assert!(position_elem([], &1).is_none());
3587

3588
        let v1 = ~[1, 2, 3, 3, 2, 5];
3589 3590 3591
        assert_eq!(position_elem(v1, &1), Some(0u));
        assert_eq!(position_elem(v1, &2), Some(1u));
        assert_eq!(position_elem(v1, &5), Some(5u));
P
Patrick Walton 已提交
3592
        assert!(position_elem(v1, &4).is_none());
3593 3594 3595
    }

    #[test]
3596
    fn test_position() {
D
Daniel Micay 已提交
3597 3598
        fn less_than_three(i: &int) -> bool { *i < 3 }
        fn is_eighteen(i: &int) -> bool { *i == 18 }
3599

E
Erick Tryzelaar 已提交
3600
        assert!(position([], less_than_three).is_none());
3601

3602
        let v1 = ~[5, 4, 3, 2, 1];
3603
        assert_eq!(position(v1, less_than_three), Some(3u));
P
Patrick Walton 已提交
3604
        assert!(position(v1, is_eighteen).is_none());
3605 3606 3607
    }

    #[test]
3608
    fn test_position_between() {
E
Erick Tryzelaar 已提交
3609
        assert!(position_between([], 0u, 0u, f).is_none());
3610

N
Niko Matsakis 已提交
3611
        fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
3612
        let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
3613

P
Patrick Walton 已提交
3614 3615
        assert!(position_between(v, 0u, 0u, f).is_none());
        assert!(position_between(v, 0u, 1u, f).is_none());
3616 3617 3618
        assert_eq!(position_between(v, 0u, 2u, f), Some(1u));
        assert_eq!(position_between(v, 0u, 3u, f), Some(1u));
        assert_eq!(position_between(v, 0u, 4u, f), Some(1u));
3619

P
Patrick Walton 已提交
3620
        assert!(position_between(v, 1u, 1u, f).is_none());
3621 3622 3623
        assert_eq!(position_between(v, 1u, 2u, f), Some(1u));
        assert_eq!(position_between(v, 1u, 3u, f), Some(1u));
        assert_eq!(position_between(v, 1u, 4u, f), Some(1u));
3624

P
Patrick Walton 已提交
3625 3626
        assert!(position_between(v, 2u, 2u, f).is_none());
        assert!(position_between(v, 2u, 3u, f).is_none());
3627
        assert_eq!(position_between(v, 2u, 4u, f), Some(3u));
3628

P
Patrick Walton 已提交
3629
        assert!(position_between(v, 3u, 3u, f).is_none());
3630
        assert_eq!(position_between(v, 3u, 4u, f), Some(3u));
3631

P
Patrick Walton 已提交
3632
        assert!(position_between(v, 4u, 4u, f).is_none());
3633 3634
    }

3635 3636
    #[test]
    fn test_find() {
E
Erick Tryzelaar 已提交
3637
        assert!(find([], f).is_none());
3638

N
Niko Matsakis 已提交
3639 3640
        fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
        fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
3641
        let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
3642

3643
        assert_eq!(find(v, f), Some((1, 'b')));
P
Patrick Walton 已提交
3644
        assert!(find(v, g).is_none());
3645 3646 3647
    }

    #[test]
3648
    fn test_find_between() {
E
Erick Tryzelaar 已提交
3649
        assert!(find_between([], 0u, 0u, f).is_none());
3650

N
Niko Matsakis 已提交
3651
        fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
3652
        let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
3653

P
Patrick Walton 已提交
3654 3655
        assert!(find_between(v, 0u, 0u, f).is_none());
        assert!(find_between(v, 0u, 1u, f).is_none());
3656 3657 3658
        assert_eq!(find_between(v, 0u, 2u, f), Some((1, 'b')));
        assert_eq!(find_between(v, 0u, 3u, f), Some((1, 'b')));
        assert_eq!(find_between(v, 0u, 4u, f), Some((1, 'b')));
3659

P
Patrick Walton 已提交
3660
        assert!(find_between(v, 1u, 1u, f).is_none());
3661 3662 3663
        assert_eq!(find_between(v, 1u, 2u, f), Some((1, 'b')));
        assert_eq!(find_between(v, 1u, 3u, f), Some((1, 'b')));
        assert_eq!(find_between(v, 1u, 4u, f), Some((1, 'b')));
3664

P
Patrick Walton 已提交
3665 3666
        assert!(find_between(v, 2u, 2u, f).is_none());
        assert!(find_between(v, 2u, 3u, f).is_none());
3667
        assert_eq!(find_between(v, 2u, 4u, f), Some((3, 'b')));
3668

P
Patrick Walton 已提交
3669
        assert!(find_between(v, 3u, 3u, f).is_none());
3670
        assert_eq!(find_between(v, 3u, 4u, f), Some((3, 'b')));
3671

P
Patrick Walton 已提交
3672
        assert!(find_between(v, 4u, 4u, f).is_none());
3673 3674
    }

3675 3676
    #[test]
    fn test_rposition() {
E
Erick Tryzelaar 已提交
3677
        assert!(find([], f).is_none());
3678

N
Niko Matsakis 已提交
3679 3680
        fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
        fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
3681
        let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
3682

3683
        assert_eq!(position(v, f), Some(1u));
P
Patrick Walton 已提交
3684
        assert!(position(v, g).is_none());
3685 3686 3687
    }

    #[test]
3688
    fn test_rposition_between() {
E
Erick Tryzelaar 已提交
3689
        assert!(rposition_between([], 0u, 0u, f).is_none());
3690

N
Niko Matsakis 已提交
3691
        fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
3692
        let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
3693

P
Patrick Walton 已提交
3694 3695
        assert!(rposition_between(v, 0u, 0u, f).is_none());
        assert!(rposition_between(v, 0u, 1u, f).is_none());
3696 3697 3698
        assert_eq!(rposition_between(v, 0u, 2u, f), Some(1u));
        assert_eq!(rposition_between(v, 0u, 3u, f), Some(1u));
        assert_eq!(rposition_between(v, 0u, 4u, f), Some(3u));
3699

P
Patrick Walton 已提交
3700
        assert!(rposition_between(v, 1u, 1u, f).is_none());
3701 3702 3703
        assert_eq!(rposition_between(v, 1u, 2u, f), Some(1u));
        assert_eq!(rposition_between(v, 1u, 3u, f), Some(1u));
        assert_eq!(rposition_between(v, 1u, 4u, f), Some(3u));
3704

P
Patrick Walton 已提交
3705 3706
        assert!(rposition_between(v, 2u, 2u, f).is_none());
        assert!(rposition_between(v, 2u, 3u, f).is_none());
3707
        assert_eq!(rposition_between(v, 2u, 4u, f), Some(3u));
3708

P
Patrick Walton 已提交
3709
        assert!(rposition_between(v, 3u, 3u, f).is_none());
3710
        assert_eq!(rposition_between(v, 3u, 4u, f), Some(3u));
3711

P
Patrick Walton 已提交
3712
        assert!(rposition_between(v, 4u, 4u, f).is_none());
3713
    }
3714 3715 3716

    #[test]
    fn test_rfind() {
E
Erick Tryzelaar 已提交
3717
        assert!(rfind([], f).is_none());
3718

N
Niko Matsakis 已提交
3719 3720
        fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
        fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
3721
        let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
3722

3723
        assert_eq!(rfind(v, f), Some((3, 'b')));
P
Patrick Walton 已提交
3724
        assert!(rfind(v, g).is_none());
3725 3726 3727
    }

    #[test]
3728
    fn test_rfind_between() {
E
Erick Tryzelaar 已提交
3729
        assert!(rfind_between([], 0u, 0u, f).is_none());
3730

N
Niko Matsakis 已提交
3731
        fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
3732
        let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
3733

P
Patrick Walton 已提交
3734 3735
        assert!(rfind_between(v, 0u, 0u, f).is_none());
        assert!(rfind_between(v, 0u, 1u, f).is_none());
3736 3737 3738
        assert_eq!(rfind_between(v, 0u, 2u, f), Some((1, 'b')));
        assert_eq!(rfind_between(v, 0u, 3u, f), Some((1, 'b')));
        assert_eq!(rfind_between(v, 0u, 4u, f), Some((3, 'b')));
3739

P
Patrick Walton 已提交
3740
        assert!(rfind_between(v, 1u, 1u, f).is_none());
3741 3742 3743
        assert_eq!(rfind_between(v, 1u, 2u, f), Some((1, 'b')));
        assert_eq!(rfind_between(v, 1u, 3u, f), Some((1, 'b')));
        assert_eq!(rfind_between(v, 1u, 4u, f), Some((3, 'b')));
3744

P
Patrick Walton 已提交
3745 3746
        assert!(rfind_between(v, 2u, 2u, f).is_none());
        assert!(rfind_between(v, 2u, 3u, f).is_none());
3747
        assert_eq!(rfind_between(v, 2u, 4u, f), Some((3, 'b')));
3748

P
Patrick Walton 已提交
3749
        assert!(rfind_between(v, 3u, 3u, f).is_none());
3750
        assert_eq!(rfind_between(v, 3u, 4u, f), Some((3, 'b')));
3751

P
Patrick Walton 已提交
3752
        assert!(rfind_between(v, 4u, 4u, f).is_none());
3753 3754
    }

G
Graydon Hoare 已提交
3755 3756
    #[test]
    fn test_bsearch_elem() {
3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788
        assert_eq!(bsearch_elem([1,2,3,4,5], &5), Some(4));
        assert_eq!(bsearch_elem([1,2,3,4,5], &4), Some(3));
        assert_eq!(bsearch_elem([1,2,3,4,5], &3), Some(2));
        assert_eq!(bsearch_elem([1,2,3,4,5], &2), Some(1));
        assert_eq!(bsearch_elem([1,2,3,4,5], &1), Some(0));

        assert_eq!(bsearch_elem([2,4,6,8,10], &1), None);
        assert_eq!(bsearch_elem([2,4,6,8,10], &5), None);
        assert_eq!(bsearch_elem([2,4,6,8,10], &4), Some(1));
        assert_eq!(bsearch_elem([2,4,6,8,10], &10), Some(4));

        assert_eq!(bsearch_elem([2,4,6,8], &1), None);
        assert_eq!(bsearch_elem([2,4,6,8], &5), None);
        assert_eq!(bsearch_elem([2,4,6,8], &4), Some(1));
        assert_eq!(bsearch_elem([2,4,6,8], &8), Some(3));

        assert_eq!(bsearch_elem([2,4,6], &1), None);
        assert_eq!(bsearch_elem([2,4,6], &5), None);
        assert_eq!(bsearch_elem([2,4,6], &4), Some(1));
        assert_eq!(bsearch_elem([2,4,6], &6), Some(2));

        assert_eq!(bsearch_elem([2,4], &1), None);
        assert_eq!(bsearch_elem([2,4], &5), None);
        assert_eq!(bsearch_elem([2,4], &2), Some(0));
        assert_eq!(bsearch_elem([2,4], &4), Some(1));

        assert_eq!(bsearch_elem([2], &1), None);
        assert_eq!(bsearch_elem([2], &5), None);
        assert_eq!(bsearch_elem([2], &2), Some(0));

        assert_eq!(bsearch_elem([], &1), None);
        assert_eq!(bsearch_elem([], &5), None);
3789 3790 3791 3792 3793

        assert!(bsearch_elem([1,1,1,1,1], &1) != None);
        assert!(bsearch_elem([1,1,1,1,2], &1) != None);
        assert!(bsearch_elem([1,1,1,2,2], &1) != None);
        assert!(bsearch_elem([1,1,2,2,2], &1) != None);
3794
        assert_eq!(bsearch_elem([1,2,2,2,2], &1), Some(0));
3795

3796 3797
        assert_eq!(bsearch_elem([1,2,3,4,5], &6), None);
        assert_eq!(bsearch_elem([1,2,3,4,5], &0), None);
G
Graydon Hoare 已提交
3798 3799
    }

3800 3801
    #[test]
    fn reverse_and_reversed() {
B
Ben Striegel 已提交
3802
        let mut v: ~[int] = ~[10, 20];
3803 3804
        assert_eq!(v[0], 10);
        assert_eq!(v[1], 20);
3805
        reverse(v);
3806 3807
        assert_eq!(v[0], 20);
        assert_eq!(v[1], 10);
E
Erick Tryzelaar 已提交
3808
        let v2 = reversed::<int>([10, 20]);
3809 3810
        assert_eq!(v2[0], 20);
        assert_eq!(v2[1], 10);
3811
        v[0] = 30;
3812
        assert_eq!(v2[0], 20);
3813 3814
        // Make sure they work with 0-length vectors too.

E
Erick Tryzelaar 已提交
3815
        let v4 = reversed::<int>([]);
3816
        assert_eq!(v4, ~[]);
B
Ben Striegel 已提交
3817
        let mut v3: ~[int] = ~[];
3818 3819 3820 3821 3822
        reverse::<int>(v3);
    }

    #[test]
    fn reversed_mut() {
E
Erick Tryzelaar 已提交
3823
        let v2 = reversed::<int>([10, 20]);
3824 3825
        assert_eq!(v2[0], 20);
        assert_eq!(v2[1], 10);
3826 3827
    }

3828 3829
    #[test]
    fn test_split() {
N
Niko Matsakis 已提交
3830
        fn f(x: &int) -> bool { *x == 3 }
3831

E
Erick Tryzelaar 已提交
3832 3833 3834 3835 3836
        assert_eq!(split([], f), ~[]);
        assert_eq!(split([1, 2], f), ~[~[1, 2]]);
        assert_eq!(split([3, 1, 2], f), ~[~[], ~[1, 2]]);
        assert_eq!(split([1, 2, 3], f), ~[~[1, 2], ~[]]);
        assert_eq!(split([1, 2, 3, 4, 3, 5], f), ~[~[1, 2], ~[4], ~[5]]);
3837 3838 3839 3840
    }

    #[test]
    fn test_splitn() {
N
Niko Matsakis 已提交
3841
        fn f(x: &int) -> bool { *x == 3 }
3842

E
Erick Tryzelaar 已提交
3843 3844 3845 3846 3847
        assert_eq!(splitn([], 1u, f), ~[]);
        assert_eq!(splitn([1, 2], 1u, f), ~[~[1, 2]]);
        assert_eq!(splitn([3, 1, 2], 1u, f), ~[~[], ~[1, 2]]);
        assert_eq!(splitn([1, 2, 3], 1u, f), ~[~[1, 2], ~[]]);
        assert!(splitn([1, 2, 3, 4, 3, 5], 1u, f) ==
3848
                      ~[~[1, 2], ~[4, 3, 5]]);
3849 3850 3851 3852
    }

    #[test]
    fn test_rsplit() {
N
Niko Matsakis 已提交
3853
        fn f(x: &int) -> bool { *x == 3 }
3854

E
Erick Tryzelaar 已提交
3855 3856 3857 3858
        assert_eq!(rsplit([], f), ~[]);
        assert_eq!(rsplit([1, 2], f), ~[~[1, 2]]);
        assert_eq!(rsplit([1, 2, 3], f), ~[~[1, 2], ~[]]);
        assert!(rsplit([1, 2, 3, 4, 3, 5], f) ==
P
Patrick Walton 已提交
3859
            ~[~[1, 2], ~[4], ~[5]]);
3860 3861 3862 3863
    }

    #[test]
    fn test_rsplitn() {
N
Niko Matsakis 已提交
3864
        fn f(x: &int) -> bool { *x == 3 }
3865

E
Erick Tryzelaar 已提交
3866 3867 3868 3869
        assert_eq!(rsplitn([], 1u, f), ~[]);
        assert_eq!(rsplitn([1, 2], 1u, f), ~[~[1, 2]]);
        assert_eq!(rsplitn([1, 2, 3], 1u, f), ~[~[1, 2], ~[]]);
        assert_eq!(rsplitn([1, 2, 3, 4, 3, 5], 1u, f), ~[~[1, 2, 3, 4], ~[5]]);
3870 3871
    }

3872 3873
    #[test]
    fn test_partition() {
3874
        // FIXME (#4355 maybe): using v.partition here crashes
3875
        assert_eq!(partition(~[], |x: &int| *x < 3), (~[], ~[]));
E
Erick Tryzelaar 已提交
3876 3877 3878
        assert_eq!(partition(~[1, 2, 3], |x: &int| *x < 4), (~[1, 2, 3], ~[]));
        assert_eq!(partition(~[1, 2, 3], |x: &int| *x < 2), (~[1], ~[2, 3]));
        assert_eq!(partition(~[1, 2, 3], |x: &int| *x < 0), (~[], ~[1, 2, 3]));
3879 3880 3881 3882
    }

    #[test]
    fn test_partitioned() {
E
Erick Tryzelaar 已提交
3883 3884 3885 3886
        assert_eq!(([]).partitioned(|x: &int| *x < 3), (~[], ~[]))
        assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
        assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (~[1], ~[2, 3]));
        assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
3887 3888
    }

3889 3890
    #[test]
    fn test_concat() {
E
Erick Tryzelaar 已提交
3891
        assert_eq!(concat([~[1], ~[2,3]]), ~[1, 2, 3]);
3892 3893
    }

3894 3895
    #[test]
    fn test_connect() {
E
Erick Tryzelaar 已提交
3896 3897 3898
        assert_eq!(connect([], &0), ~[]);
        assert_eq!(connect([~[1], ~[2, 3]], &0), ~[1, 0, 2, 3]);
        assert_eq!(connect([~[1], ~[2], ~[3]], &0), ~[1, 0, 2, 0, 3]);
3899 3900
    }

3901 3902
    #[test]
    fn test_windowed () {
3903 3904
        fn t(n: uint, expected: &[&[int]]) {
            let mut i = 0;
E
Erick Tryzelaar 已提交
3905
            for windowed(n, [1,2,3,4,5,6]) |v| {
3906 3907 3908
                assert_eq!(v, expected[i]);
                i += 1;
            }
3909

3910 3911 3912 3913 3914 3915
            // check that we actually iterated the right number of times
            assert_eq!(i, expected.len());
        }
        t(3, &[&[1,2,3],&[2,3,4],&[3,4,5],&[4,5,6]]);
        t(4, &[&[1,2,3,4],&[2,3,4,5],&[3,4,5,6]]);
        t(7, &[]);
3916
        t(8, &[]);
3917 3918 3919 3920
    }

    #[test]
    #[should_fail]
3921
    #[ignore(cfg(windows))]
3922
    fn test_windowed_() {
E
Erick Tryzelaar 已提交
3923
        for windowed (0u, [1u,2u,3u,4u,5u,6u]) |_v| {}
3924
    }
3925

E
Eric Holk 已提交
3926 3927
    #[test]
    fn test_unshift() {
3928
        let mut x = ~[1, 2, 3];
N
Niko Matsakis 已提交
3929
        x.unshift(0);
3930
        assert_eq!(x, ~[0, 1, 2, 3]);
E
Eric Holk 已提交
3931 3932
    }

3933 3934 3935 3936
    #[test]
    fn test_insert() {
        let mut a = ~[1, 2, 4];
        a.insert(2, 3);
3937
        assert_eq!(a, ~[1, 2, 3, 4]);
3938 3939 3940

        let mut a = ~[1, 2, 3];
        a.insert(0, 0);
3941
        assert_eq!(a, ~[0, 1, 2, 3]);
3942 3943 3944

        let mut a = ~[1, 2, 3];
        a.insert(3, 4);
3945
        assert_eq!(a, ~[1, 2, 3, 4]);
3946 3947 3948

        let mut a = ~[];
        a.insert(0, 1);
3949
        assert_eq!(a, ~[1]);
3950 3951 3952
    }

    #[test]
3953
    #[ignore(cfg(windows))]
3954 3955 3956 3957 3958 3959 3960 3961 3962 3963
    #[should_fail]
    fn test_insert_oob() {
        let mut a = ~[1, 2, 3];
        a.insert(4, 5);
    }

    #[test]
    fn test_remove() {
        let mut a = ~[1, 2, 3, 4];
        a.remove(2);
3964
        assert_eq!(a, ~[1, 2, 4]);
3965 3966 3967

        let mut a = ~[1, 2, 3];
        a.remove(0);
3968
        assert_eq!(a, ~[2, 3]);
3969 3970 3971

        let mut a = ~[1];
        a.remove(0);
3972
        assert_eq!(a, ~[]);
3973 3974 3975
    }

    #[test]
3976
    #[ignore(cfg(windows))]
3977 3978 3979 3980 3981 3982
    #[should_fail]
    fn test_remove_oob() {
        let mut a = ~[1, 2, 3];
        a.remove(3);
    }

B
Brian Anderson 已提交
3983 3984
    #[test]
    fn test_capacity() {
3985
        let mut v = ~[0u64];
3986
        reserve(&mut v, 10u);
3987
        assert_eq!(capacity(&v), 10u);
3988
        let mut v = ~[0u32];
3989
        reserve(&mut v, 10u);
3990
        assert_eq!(capacity(&v), 10u);
B
Brian Anderson 已提交
3991
    }
3992 3993

    #[test]
3994
    fn test_slice_2() {
3995
        let v = ~[1, 2, 3, 4, 5];
3996
        let v = v.slice(1u, 3u);
3997 3998 3999
        assert_eq!(v.len(), 2u);
        assert_eq!(v[0], 2);
        assert_eq!(v[1], 3);
4000
    }
4001 4002 4003 4004 4005 4006 4007


    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_from_fn_fail() {
        do from_fn(100) |v| {
4008
            if v == 50 { fail!() }
4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021
            (~0, @0)
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_build_fail() {
        do build |push| {
            push((~0, @0));
            push((~0, @0));
            push((~0, @0));
            push((~0, @0));
4022
            fail!();
4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_split_fail_ret_true() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do split(v) |_elt| {
            if i == 2 {
4035
                fail!()
4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051
            }
            i += 1;

            true
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_split_fail_ret_false() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do split(v) |_elt| {
            if i == 2 {
4052
                fail!()
4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068
            }
            i += 1;

            false
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_splitn_fail_ret_true() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do splitn(v, 100) |_elt| {
            if i == 2 {
4069
                fail!()
4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085
            }
            i += 1;

            true
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_splitn_fail_ret_false() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do split(v) |_elt| {
            if i == 2 {
4086
                fail!()
4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102
            }
            i += 1;

            false
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_rsplit_fail_ret_true() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do rsplit(v) |_elt| {
            if i == 2 {
4103
                fail!()
4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119
            }
            i += 1;

            true
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_rsplit_fail_ret_false() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do rsplit(v) |_elt| {
            if i == 2 {
4120
                fail!()
4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136
            }
            i += 1;

            false
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_rsplitn_fail_ret_true() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do rsplitn(v, 100) |_elt| {
            if i == 2 {
4137
                fail!()
4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153
            }
            i += 1;

            true
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_rsplitn_fail_ret_false() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do rsplitn(v, 100) |_elt| {
            if i == 2 {
4154
                fail!()
4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167
            }
            i += 1;

            false
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_consume_fail() {
        let v = ~[(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
B
Brian Anderson 已提交
4168
        do consume(v) |_i, _elt| {
4169
            if i == 2 {
4170
                fail!()
4171 4172 4173 4174 4175 4176 4177 4178
            }
            i += 1;
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
B
Brian Anderson 已提交
4179
    #[allow(non_implicitly_copyable_typarams)]
4180 4181
    fn test_grow_fn_fail() {
        let mut v = ~[];
N
Niko Matsakis 已提交
4182
        do v.grow_fn(100) |i| {
4183
            if i == 50 {
4184
                fail!()
4185 4186 4187 4188 4189 4190 4191 4192 4193
            }
            (~0, @0)
        }
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_map_fail() {
4194
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
4195 4196 4197
        let mut i = 0;
        do map(v) |_elt| {
            if i == 2 {
4198
                fail!()
4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210
            }
            i += 0;
            ~[(~0, @0)]
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_map_consume_fail() {
        let v = ~[(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
B
Brian Anderson 已提交
4211
        do map_consume(v) |_elt| {
4212
            if i == 2 {
4213
                fail!()
4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227
            }
            i += 0;
            ~[(~0, @0)]
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_mapi_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do mapi(v) |_i, _elt| {
            if i == 2 {
4228
                fail!()
4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242
            }
            i += 0;
            ~[(~0, @0)]
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_flat_map_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do map(v) |_elt| {
            if i == 2 {
4243
                fail!()
4244 4245 4246 4247 4248 4249 4250 4251 4252 4253
            }
            i += 0;
            ~[(~0, @0)]
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
4254
    fn test_map_zip_fail() {
4255 4256
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
4257
        do map_zip(v, v) |_elt1, _elt2| {
4258
            if i == 2 {
4259
                fail!()
4260 4261 4262 4263 4264 4265 4266 4267 4268 4269
            }
            i += 0;
            ~[(~0, @0)]
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
4270
    fn test_filter_mapped_fail() {
4271 4272
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
4273
        do filter_mapped(v) |_elt| {
4274
            if i == 2 {
4275
                fail!()
4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288
            }
            i += 0;
            Some((~0, @0))
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_filter_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
4289
        do v.filtered |_elt| {
4290
            if i == 2 {
4291
                fail!()
4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306
            }
            i += 0;
            true
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_foldl_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do foldl((~0, @0), v) |_a, _b| {
            if i == 2 {
4307
                fail!()
4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322
            }
            i += 0;
            (~0, @0)
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_foldr_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do foldr(v, (~0, @0)) |_a, _b| {
            if i == 2 {
4323
                fail!()
4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337
            }
            i += 0;
            (~0, @0)
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_any_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do any(v) |_elt| {
            if i == 2 {
4338
                fail!()
4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352
            }
            i += 0;
            false
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_any2_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do any(v) |_elt| {
            if i == 2 {
4353
                fail!()
4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367
            }
            i += 0;
            false
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_all_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do all(v) |_elt| {
            if i == 2 {
4368
                fail!()
4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382
            }
            i += 0;
            true
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_alli_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do alli(v) |_i, _elt| {
            if i == 2 {
4383
                fail!()
4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397
            }
            i += 0;
            true
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_all2_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do all2(v, v) |_elt1, _elt2| {
            if i == 2 {
4398
                fail!()
4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413
            }
            i += 0;
            true
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_find_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do find(v) |_elt| {
            if i == 2 {
4414
                fail!()
4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428
            }
            i += 0;
            false
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_position_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do position(v) |_elt| {
            if i == 2 {
4429
                fail!()
4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443
            }
            i += 0;
            false
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_rposition_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do rposition(v) |_elt| {
            if i == 2 {
4444
                fail!()
4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458
            }
            i += 0;
            false
        };
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_each_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do each(v) |_elt| {
            if i == 2 {
4459
                fail!()
4460 4461 4462
            }
            i += 0;
            false
A
Alex Crichton 已提交
4463
        };
4464 4465 4466 4467 4468 4469 4470 4471 4472 4473
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_eachi_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do eachi(v) |_i, _elt| {
            if i == 2 {
4474
                fail!()
4475 4476 4477
            }
            i += 0;
            false
A
Alex Crichton 已提交
4478
        };
4479 4480 4481 4482 4483 4484 4485 4486 4487
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    #[allow(non_implicitly_copyable_typarams)]
    fn test_permute_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
N
Niko Matsakis 已提交
4488
        for each_permutation(v) |_elt| {
4489
            if i == 2 {
4490
                fail!()
4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501
            }
            i += 0;
        }
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_as_imm_buf_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        do as_imm_buf(v) |_buf, _i| {
4502
            fail!()
4503 4504 4505 4506 4507 4508 4509 4510 4511
        }
    }

    #[test]
    #[ignore(windows)]
    #[should_fail]
    fn test_as_const_buf_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        do as_const_buf(v) |_buf, _i| {
4512
            fail!()
4513 4514 4515 4516
        }
    }

    #[test]
4517
    #[ignore(cfg(windows))]
4518 4519
    #[should_fail]
    fn test_as_mut_buf_fail() {
B
Ben Striegel 已提交
4520
        let mut v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
4521
        do as_mut_buf(v) |_buf, _i| {
4522
            fail!()
4523 4524
        }
    }
4525 4526 4527

    #[test]
    #[should_fail]
4528
    #[ignore(cfg(windows))]
4529 4530
    fn test_copy_memory_oob() {
        unsafe {
B
Ben Striegel 已提交
4531
            let mut a = [1, 2, 3, 4];
4532 4533 4534
            let b = [1, 2, 3, 4, 5];
            raw::copy_memory(a, b, 5);
        }
4535 4536
    }

D
Daniel Micay 已提交
4537 4538 4539 4540 4541 4542 4543 4544
    #[test]
    fn test_total_ord() {
        [1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
        [1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
        [1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
        [1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
        [2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
    }
D
Daniel Micay 已提交
4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557

    #[test]
    fn test_iterator() {
        use iterator::*;
        let xs = [1, 2, 5, 10, 11];
        let ys = [1, 2, 5, 10, 11, 19];
        let mut it = xs.iter();
        let mut i = 0;
        for it.advance |&x| {
            assert_eq!(x, ys[i]);
            i += 1;
        }
    }
4558

4559 4560 4561 4562
    #[test]
    fn test_reverse_part() {
        let mut values = [1,2,3,4,5];
        reverse_part(values,1,4);
C
Corey Richardson 已提交
4563
        assert_eq!(values, [1,4,3,2,5]);
4564 4565 4566 4567 4568 4569 4570
    }

    #[test]
    fn test_permutations0() {
        let values = [];
        let mut v : ~[~[int]] = ~[];
        for each_permutation(values) |p| {
C
Corey Richardson 已提交
4571
            v.push(p.to_owned());
4572
        }
C
Corey Richardson 已提交
4573
        assert_eq!(v, ~[~[]]);
4574 4575 4576 4577 4578 4579 4580
    }

    #[test]
    fn test_permutations1() {
        let values = [1];
        let mut v : ~[~[int]] = ~[];
        for each_permutation(values) |p| {
C
Corey Richardson 已提交
4581
            v.push(p.to_owned());
4582
        }
C
Corey Richardson 已提交
4583
        assert_eq!(v, ~[~[1]]);
4584 4585 4586 4587 4588 4589 4590
    }

    #[test]
    fn test_permutations2() {
        let values = [1,2];
        let mut v : ~[~[int]] = ~[];
        for each_permutation(values) |p| {
C
Corey Richardson 已提交
4591
            v.push(p.to_owned());
4592
        }
C
Corey Richardson 已提交
4593
        assert_eq!(v, ~[~[1,2],~[2,1]]);
4594 4595 4596 4597 4598 4599 4600
    }

    #[test]
    fn test_permutations3() {
        let values = [1,2,3];
        let mut v : ~[~[int]] = ~[];
        for each_permutation(values) |p| {
C
Corey Richardson 已提交
4601
            v.push(p.to_owned());
4602
        }
C
Corey Richardson 已提交
4603
        assert_eq!(v, ~[~[1,2,3],~[1,3,2],~[2,1,3],~[2,3,1],~[3,1,2],~[3,2,1]]);
4604 4605
    }

4606 4607 4608 4609 4610 4611 4612
    #[test]
    fn test_each_val() {
        use old_iter::CopyableNonstrictIter;
        let mut i = 0;
        for [1, 2, 3].each_val |v| {
            i += v;
        }
4613
        assert_eq!(i, 6);
4614
    }
4615
}