auto merge of #16332 : brson/rust/slicestab, r=aturon

This implements some of the recommendations from https://github.com/rust-lang/meeting-minutes/blob/master/Meeting-API-review-2014-08-06.md.

Explanation in commits.
This commit is contained in:
bors 2014-08-14 05:36:25 +00:00
commit 385c39a77b
65 changed files with 450 additions and 210 deletions

View file

@ -233,7 +233,7 @@ fn parse_exec_env(line: &str) -> Option<(String, String)> {
parse_name_value_directive(line, "exec-env").map(|nv| {
// nv is either FOO or FOO=BAR
let mut strs: Vec<String> = nv.as_slice()
.splitn('=', 1)
.splitn(1, '=')
.map(|s| s.to_string())
.collect();

View file

@ -293,13 +293,12 @@ def emit_bsearch_range_table(f):
f.write("""
fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool {
use core::cmp::{Equal, Less, Greater};
use core::slice::ImmutableVector;
use core::option::None;
r.bsearch(|&(lo,hi)| {
use core::slice::ImmutableSlice;
r.binary_search(|&(lo,hi)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
}) != None
}).found().is_some()
}\n
""")
@ -352,9 +351,10 @@ def emit_conversions_module(f, lowerupper, upperlower):
f.write("pub mod conversions {")
f.write("""
use core::cmp::{Equal, Less, Greater};
use core::slice::ImmutableVector;
use core::slice::ImmutableSlice;
use core::tuple::Tuple2;
use core::option::{Option, Some, None};
use core::slice;
pub fn to_lower(c: char) -> char {
match bsearch_case_table(c, LuLl_table) {
@ -371,11 +371,14 @@ def emit_conversions_module(f, lowerupper, upperlower):
}
fn bsearch_case_table(c: char, table: &'static [(char, char)]) -> Option<uint> {
table.bsearch(|&(key, _)| {
match table.binary_search(|&(key, _)| {
if c == key { Equal }
else if key < c { Less }
else { Greater }
})
}) {
slice::Found(i) => Some(i),
slice::NotFound(_) => None,
}
}
""")
@ -387,8 +390,8 @@ def emit_conversions_module(f, lowerupper, upperlower):
def emit_grapheme_module(f, grapheme_table, grapheme_cats):
f.write("""pub mod grapheme {
use core::option::{Some, None};
use core::slice::ImmutableVector;
use core::slice::ImmutableSlice;
use core::slice;
#[allow(non_camel_case_types)]
#[deriving(Clone)]
@ -400,16 +403,16 @@ def emit_grapheme_module(f, grapheme_table, grapheme_cats):
fn bsearch_range_value_table(c: char, r: &'static [(char, char, GraphemeCat)]) -> GraphemeCat {
use core::cmp::{Equal, Less, Greater};
match r.bsearch(|&(lo, hi, _)| {
match r.binary_search(|&(lo, hi, _)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
}) {
Some(idx) => {
slice::Found(idx) => {
let (_, _, cat) = r[idx];
cat
}
None => GC_Any
slice::NotFound(_) => GC_Any
}
}
@ -427,20 +430,21 @@ def emit_grapheme_module(f, grapheme_table, grapheme_cats):
def emit_charwidth_module(f, width_table):
f.write("pub mod charwidth {\n")
f.write(" use core::option::{Option, Some, None};\n")
f.write(" use core::slice::ImmutableVector;\n")
f.write(" use core::slice::ImmutableSlice;\n")
f.write(" use core::slice;\n")
f.write("""
fn bsearch_range_value_table(c: char, is_cjk: bool, r: &'static [(char, char, u8, u8)]) -> u8 {
use core::cmp::{Equal, Less, Greater};
match r.bsearch(|&(lo, hi, _, _)| {
match r.binary_search(|&(lo, hi, _, _)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
}) {
Some(idx) => {
slice::Found(idx) => {
let (_, _, r_ncjk, r_cjk) = r[idx];
if is_cjk { r_cjk } else { r_ncjk }
}
None => 1
slice::NotFound(_) => 1
}
}
""")
@ -525,19 +529,19 @@ def emit_norm_module(f, canon, compat, combine, norm_props):
f.write("""
fn bsearch_range_value_table(c: char, r: &'static [(char, char, u8)]) -> u8 {
use core::option::{Some, None};
use core::cmp::{Equal, Less, Greater};
use core::slice::ImmutableVector;
match r.bsearch(|&(lo, hi, _)| {
use core::slice::ImmutableSlice;
use core::slice;
match r.binary_search(|&(lo, hi, _)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
}) {
Some(idx) => {
slice::Found(idx) => {
let (_, _, result) = r[idx];
result
}
None => 0
slice::NotFound(_) => 0
}
}\n
""")

View file

@ -296,7 +296,7 @@ mod tests {
use std::prelude::*;
use std::mem;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use super::{Hash, Hasher, Writer};
struct MyWriterHasher;

View file

@ -275,7 +275,7 @@ mod tests {
use str::Str;
use string::String;
use slice::{Vector, ImmutableVector};
use slice::{Slice, ImmutableSlice};
use vec::Vec;
use super::super::{Hash, Writer};

View file

@ -362,6 +362,7 @@ pub struct MutItems<'a, T> {
impl<'a, T> Iterator<&'a mut T> for MutItems<'a, T> {
#[inline]
#[allow(deprecated)] // mut_shift_ref
fn next(&mut self) -> Option<&'a mut T> {
if self.nelts == 0 {
return None;
@ -384,6 +385,7 @@ impl<'a, T> Iterator<&'a mut T> for MutItems<'a, T> {
impl<'a, T> DoubleEndedIterator<&'a mut T> for MutItems<'a, T> {
#[inline]
#[allow(deprecated)] // mut_shift_ref
fn next_back(&mut self) -> Option<&'a mut T> {
if self.nelts == 0 {
return None;

View file

@ -45,8 +45,8 @@ represents iteration over a slice.
## Traits
A number of traits add methods that allow you to accomplish tasks with slices.
These traits include `ImmutableVector`, which is defined for `&[T]` types,
and `MutableVector`, defined for `&mut [T]` types.
These traits include `ImmutableSlice`, which is defined for `&[T]` types,
and `MutableSlice`, defined for `&mut [T]` types.
An example is the method `.slice(a, b)` that returns an immutable "view" into
a `Vec` or another slice from the index interval `[a, b)`:
@ -98,10 +98,11 @@ use {Collection, MutableSeq};
use vec::Vec;
pub use core::slice::{ref_slice, mut_ref_slice, Splits, Windows};
pub use core::slice::{Chunks, Vector, ImmutableVector, ImmutableEqVector};
pub use core::slice::{ImmutableOrdVector, MutableVector, Items, MutItems};
pub use core::slice::{Chunks, Slice, ImmutableSlice, ImmutablePartialEqSlice};
pub use core::slice::{ImmutableOrdSlice, MutableSlice, Items, MutItems};
pub use core::slice::{MutSplits, MutChunks};
pub use core::slice::{bytes, MutableCloneableVector};
pub use core::slice::{bytes, MutableCloneableSlice};
pub use core::slice::{BinarySearchResult, Found, NotFound};
// Functional utilities
@ -116,7 +117,7 @@ pub trait VectorVector<T> {
fn connect_vec(&self, sep: &T) -> Vec<T>;
}
impl<'a, T: Clone, V: Vector<T>> VectorVector<T> for &'a [V] {
impl<'a, T: Clone, V: Slice<T>> VectorVector<T> for &'a [V] {
fn concat_vec(&self) -> Vec<T> {
let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
let mut result = Vec::with_capacity(size);
@ -558,7 +559,7 @@ fn merge_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
/// Extension methods for vectors such that their elements are
/// mutable.
pub trait MutableVectorAllocating<'a, T> {
pub trait MutableSliceAllocating<'a, T> {
/// Sort the vector, in place, using `compare` to compare
/// elements.
///
@ -604,7 +605,7 @@ pub trait MutableVectorAllocating<'a, T> {
fn move_from(self, src: Vec<T>, start: uint, end: uint) -> uint;
}
impl<'a,T> MutableVectorAllocating<'a, T> for &'a mut [T] {
impl<'a,T> MutableSliceAllocating<'a, T> for &'a mut [T] {
#[inline]
fn sort_by(self, compare: |&T, &T| -> Ordering) {
merge_sort(self, compare)
@ -621,7 +622,7 @@ impl<'a,T> MutableVectorAllocating<'a, T> for &'a mut [T] {
/// Methods for mutable vectors with orderable elements, such as
/// in-place sorting.
pub trait MutableOrdVector<T> {
pub trait MutableOrdSlice<T> {
/// Sort the vector, in place.
///
/// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
@ -667,7 +668,7 @@ pub trait MutableOrdVector<T> {
fn prev_permutation(self) -> bool;
}
impl<'a, T: Ord> MutableOrdVector<T> for &'a mut [T] {
impl<'a, T: Ord> MutableOrdSlice<T> for &'a mut [T] {
#[inline]
fn sort(self) {
self.sort_by(|a,b| a.cmp(b))

View file

@ -894,7 +894,7 @@ mod tests {
use {Collection, MutableSeq};
use super::*;
use std::slice::{Vector, ImmutableVector};
use std::slice::{Slice, ImmutableSlice};
use string::String;
use vec::Vec;
@ -1812,17 +1812,17 @@ mod tests {
fn test_splitn_char_iterator() {
let data = "\nMäry häd ä little lämb\nLittle lämb\n";
let split: Vec<&str> = data.splitn(' ', 3).collect();
let split: Vec<&str> = data.splitn(3, ' ').collect();
assert_eq!(split, vec!["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
let split: Vec<&str> = data.splitn(|c: char| c == ' ', 3).collect();
let split: Vec<&str> = data.splitn(3, |c: char| c == ' ').collect();
assert_eq!(split, vec!["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
// Unicode
let split: Vec<&str> = data.splitn('ä', 3).collect();
let split: Vec<&str> = data.splitn(3, 'ä').collect();
assert_eq!(split, vec!["\nM", "ry h", "d ", " little lämb\nLittle lämb\n"]);
let split: Vec<&str> = data.splitn(|c: char| c == 'ä', 3).collect();
let split: Vec<&str> = data.splitn(3, |c: char| c == 'ä').collect();
assert_eq!(split, vec!["\nM", "ry h", "d ", " little lämb\nLittle lämb\n"]);
}
@ -1830,20 +1830,20 @@ mod tests {
fn test_rsplitn_char_iterator() {
let data = "\nMäry häd ä little lämb\nLittle lämb\n";
let mut split: Vec<&str> = data.rsplitn(' ', 3).collect();
let mut split: Vec<&str> = data.rsplitn(3, ' ').collect();
split.reverse();
assert_eq!(split, vec!["\nMäry häd ä", "little", "lämb\nLittle", "lämb\n"]);
let mut split: Vec<&str> = data.rsplitn(|c: char| c == ' ', 3).collect();
let mut split: Vec<&str> = data.rsplitn(3, |c: char| c == ' ').collect();
split.reverse();
assert_eq!(split, vec!["\nMäry häd ä", "little", "lämb\nLittle", "lämb\n"]);
// Unicode
let mut split: Vec<&str> = data.rsplitn('ä', 3).collect();
let mut split: Vec<&str> = data.rsplitn(3, 'ä').collect();
split.reverse();
assert_eq!(split, vec!["\nMäry häd ", " little l", "mb\nLittle l", "mb\n"]);
let mut split: Vec<&str> = data.rsplitn(|c: char| c == 'ä', 3).collect();
let mut split: Vec<&str> = data.rsplitn(3, |c: char| c == 'ä').collect();
split.reverse();
assert_eq!(split, vec!["\nMäry häd ", " little l", "mb\nLittle l", "mb\n"]);
}

View file

@ -18,12 +18,15 @@ use core::default::Default;
use core::fmt;
use core::mem;
use core::ptr;
use core::raw::Slice;
// FIXME: ICE's abound if you import the `Slice` type while importing `Slice` trait
use RawSlice = core::raw::Slice;
use core::slice::Slice;
use {Collection, Mutable, MutableSeq};
use hash;
use str;
use str::{CharRange, StrAllocating, MaybeOwned, Owned, Slice};
use str::{CharRange, StrAllocating, MaybeOwned, Owned};
use MaybeOwnedSlice = str::Slice; // So many `Slice`s...
use vec::Vec;
/// A growable string stored as a UTF-8 encoded buffer.
@ -130,7 +133,7 @@ impl String {
/// ```
pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> MaybeOwned<'a> {
if str::is_utf8(v) {
return Slice(unsafe { mem::transmute(v) })
return MaybeOwnedSlice(unsafe { mem::transmute(v) })
}
static TAG_CONT_U8: u8 = 128u8;
@ -138,7 +141,7 @@ impl String {
let mut i = 0;
let total = v.len();
fn unsafe_get(xs: &[u8], i: uint) -> u8 {
unsafe { *xs.unsafe_ref(i) }
unsafe { *xs.unsafe_get(i) }
}
fn safe_get(xs: &[u8], i: uint, total: uint) -> u8 {
if i >= total {
@ -496,7 +499,7 @@ impl String {
unsafe {
// Attempt to not use an intermediate buffer by just pushing bytes
// directly onto this string.
let slice = Slice {
let slice = RawSlice {
data: self.vec.as_ptr().offset(cur_len as int),
len: 4,
};

View file

@ -926,7 +926,7 @@ macro_rules! iterator_impl {
// such thing as invalid pointers and memory unsafety. The
// reason is performance, without doing this we can get the
// bench_iter_large microbenchmark down to about 30000 ns/iter
// (using .unsafe_ref to index self.stack directly, 38000
// (using .unsafe_get to index self.stack directly, 38000
// ns/iter with [] checked indexing), but this smashes that down
// to 13500 ns/iter.
//

View file

@ -13,7 +13,8 @@
use core::prelude::*;
use alloc::heap::{allocate, reallocate, deallocate};
use core::raw::Slice;
use RawSlice = core::raw::Slice;
use core::slice::Slice;
use core::cmp::max;
use core::default::Default;
use core::fmt;
@ -24,7 +25,7 @@ use core::ptr;
use core::uint;
use {Collection, Mutable, MutableSeq};
use slice::{MutableOrdVector, MutableVectorAllocating, CloneableVector};
use slice::{MutableOrdSlice, MutableSliceAllocating, CloneableVector};
use slice::{Items, MutItems};
@ -347,7 +348,7 @@ impl<T: Clone> Vec<T> {
unsafe {
ptr::write(
self.as_mut_slice().unsafe_mut_ref(len),
other.unsafe_ref(i).clone());
other.unsafe_get(i).clone());
self.set_len(len + 1);
}
}
@ -506,7 +507,7 @@ impl<T: PartialOrd> PartialOrd for Vec<T> {
impl<T: Eq> Eq for Vec<T> {}
impl<T: PartialEq, V: Vector<T>> Equiv<V> for Vec<T> {
impl<T: PartialEq, V: Slice<T>> Equiv<V> for Vec<T> {
#[inline]
fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
}
@ -702,7 +703,7 @@ impl<T> Vec<T> {
// decrement len before the read(), so a failure on Drop doesn't
// re-drop the just-failed value.
self.len -= 1;
ptr::read(self.as_slice().unsafe_ref(self.len));
ptr::read(self.as_slice().unsafe_get(self.len));
}
}
}
@ -720,7 +721,7 @@ impl<T> Vec<T> {
#[inline]
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
unsafe {
mem::transmute(Slice {
mem::transmute(RawSlice {
data: self.as_mut_ptr() as *const T,
len: self.len,
})
@ -911,8 +912,9 @@ impl<T> Vec<T> {
/// assert!(vec.tailn(2) == [3, 4]);
/// ```
#[inline]
#[deprecated = "use slice_from"]
pub fn tailn<'a>(&'a self, n: uint) -> &'a [T] {
self.as_slice().tailn(n)
self.as_slice().slice_from(n)
}
/// Returns a reference to the last element of a vector, or `None` if it is
@ -1502,7 +1504,7 @@ impl<T:PartialEq> Vec<T> {
}
}
impl<T> Vector<T> for Vec<T> {
impl<T> Slice<T> for Vec<T> {
/// Work with `self` as a slice.
///
/// # Example
@ -1515,11 +1517,11 @@ impl<T> Vector<T> for Vec<T> {
/// ```
#[inline]
fn as_slice<'a>(&'a self) -> &'a [T] {
unsafe { mem::transmute(Slice { data: self.as_ptr(), len: self.len }) }
unsafe { mem::transmute(RawSlice { data: self.as_ptr(), len: self.len }) }
}
}
impl<T: Clone, V: Vector<T>> Add<V, Vec<T>> for Vec<T> {
impl<T: Clone, V: Slice<T>> Add<V, Vec<T>> for Vec<T> {
#[inline]
fn add(&self, rhs: &V) -> Vec<T> {
let mut res = Vec::with_capacity(self.len() + rhs.as_slice().len());
@ -1604,7 +1606,7 @@ impl<T> MutableSeq<T> for Vec<T> {
} else {
unsafe {
self.len -= 1;
Some(ptr::read(self.as_slice().unsafe_ref(self.len())))
Some(ptr::read(self.as_slice().unsafe_get(self.len())))
}
}
}

View file

@ -17,7 +17,7 @@ use iter::{range, DoubleEndedIterator};
use num::{Float, FPNaN, FPInfinite, ToPrimitive, Primitive};
use num::{Zero, One, cast};
use result::Ok;
use slice::{ImmutableVector, MutableVector};
use slice::{ImmutableSlice, MutableSlice};
use slice;
use str::StrSlice;

View file

@ -24,7 +24,7 @@ use option::{Option, Some, None};
use ops::Deref;
use result::{Ok, Err};
use result;
use slice::{Vector, ImmutableVector};
use slice::{Slice, ImmutableSlice};
use slice;
use str::StrSlice;
use str;

View file

@ -18,7 +18,7 @@ use collections::Collection;
use fmt;
use iter::DoubleEndedIterator;
use num::{Int, cast, zero};
use slice::{ImmutableVector, MutableVector};
use slice::{ImmutableSlice, MutableSlice};
/// A type that represents a specific radix
#[doc(hidden)]

View file

@ -143,7 +143,7 @@
use cmp::{PartialEq, Eq, Ord};
use default::Default;
use slice::Vector;
use slice::Slice;
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
use mem;
use slice;
@ -518,7 +518,7 @@ impl<T: Default> Option<T> {
// Trait implementations
/////////////////////////////////////////////////////////////////////////////
impl<T> Vector<T> for Option<T> {
impl<T> Slice<T> for Option<T> {
/// Convert from `Option<T>` to `&[T]` (without copying)
#[inline]
fn as_slice<'a>(&'a self) -> &'a [T] {

View file

@ -61,6 +61,6 @@ pub use str::{Str, StrSlice};
pub use tuple::{Tuple1, Tuple2, Tuple3, Tuple4};
pub use tuple::{Tuple5, Tuple6, Tuple7, Tuple8};
pub use tuple::{Tuple9, Tuple10, Tuple11, Tuple12};
pub use slice::{ImmutableEqVector, ImmutableOrdVector};
pub use slice::{MutableVector};
pub use slice::{Vector, ImmutableVector};
pub use slice::{ImmutablePartialEqSlice, ImmutableOrdSlice};
pub use slice::{MutableSlice};
pub use slice::{Slice, ImmutableSlice};

View file

@ -12,6 +12,7 @@
//!
//! For more details `std::slice`.
#![stable]
#![doc(primitive = "slice")]
// How this module is organized.
@ -47,20 +48,25 @@ use ptr::RawPtr;
use mem;
use mem::size_of;
use kinds::marker;
use raw::{Repr, Slice};
use raw::Repr;
// Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
use RawSlice = raw::Slice;
//
// Extension traits
//
/// Extension methods for vectors
pub trait ImmutableVector<'a, T> {
#[unstable = "may merge with other traits; region parameter may disappear"]
pub trait ImmutableSlice<'a, T> {
/**
* Returns a slice of self spanning the interval [`start`, `end`).
*
* Fails when the slice (or part of it) is outside the bounds of self,
* or when `start` > `end`.
*/
#[unstable]
fn slice(&self, start: uint, end: uint) -> &'a [T];
/**
@ -68,6 +74,7 @@ pub trait ImmutableVector<'a, T> {
*
* Fails when `start` points outside the bounds of self.
*/
#[unstable]
fn slice_from(&self, start: uint) -> &'a [T];
/**
@ -75,6 +82,7 @@ pub trait ImmutableVector<'a, T> {
*
* Fails when `end` points outside the bounds of self.
*/
#[unstable]
fn slice_to(&self, end: uint) -> &'a [T];
/// Divides one slice into two at an index.
@ -84,24 +92,29 @@ pub trait ImmutableVector<'a, T> {
/// indices from `[mid, len)` (excluding the index `len` itself).
///
/// Fails if `mid > len`.
#[unstable]
fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]);
/// Returns an iterator over the vector
#[unstable = "iterator type may change"]
fn iter(self) -> Items<'a, T>;
/// Returns an iterator over the subslices of the vector which are
/// separated by elements that match `pred`. The matched element
/// is not contained in the subslices.
#[unstable = "iterator type may change"]
fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T>;
/// Returns an iterator over the subslices of the vector which are
/// separated by elements that match `pred`, limited to splitting
/// at most `n` times. The matched element is not contained in
/// the subslices.
#[unstable = "iterator type may change"]
fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T>;
/// Returns an iterator over the subslices of the vector which are
/// separated by elements that match `pred` limited to splitting
/// at most `n` times. This starts at the end of the vector and
/// works backwards. The matched element is not contained in the
/// subslices.
#[unstable = "iterator type may change"]
fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T>;
/**
@ -126,6 +139,7 @@ pub trait ImmutableVector<'a, T> {
* ```
*
*/
#[unstable = "iterator type may change"]
fn windows(self, size: uint) -> Windows<'a, T>;
/**
*
@ -151,28 +165,42 @@ pub trait ImmutableVector<'a, T> {
* ```
*
*/
#[unstable = "iterator type may change"]
fn chunks(self, size: uint) -> Chunks<'a, T>;
/// Returns the element of a vector at the given index, or `None` if the
/// index is out of bounds
#[unstable]
fn get(&self, index: uint) -> Option<&'a T>;
/// Returns the first element of a vector, or `None` if it is empty
#[unstable = "name may change"]
fn head(&self) -> Option<&'a T>;
/// Returns all but the first element of a vector
#[unstable = "name may change"]
fn tail(&self) -> &'a [T];
/// Returns all but the first `n' elements of a vector
#[deprecated = "use slice_from"]
fn tailn(&self, n: uint) -> &'a [T];
/// Returns all but the last element of a vector
#[unstable = "name may change"]
fn init(&self) -> &'a [T];
/// Returns all but the last `n' elements of a vector
#[deprecated = "use slice_to but note the arguments are different"]
fn initn(&self, n: uint) -> &'a [T];
/// Returns the last element of a vector, or `None` if it is empty.
#[unstable = "name may change"]
fn last(&self) -> Option<&'a T>;
/// Returns a pointer to the element at the given index, without doing
/// bounds checking.
#[deprecated = "renamed to `unsafe_get`"]
unsafe fn unsafe_ref(self, index: uint) -> &'a T;
/// Returns a pointer to the element at the given index, without doing
/// bounds checking.
#[unstable]
unsafe fn unsafe_get(self, index: uint) -> &'a T;
/**
* Returns an unsafe pointer to the vector's buffer
*
@ -182,6 +210,7 @@ pub trait ImmutableVector<'a, T> {
* Modifying the vector may cause its buffer to be reallocated, which
* would also make any pointers to it invalid.
*/
#[unstable]
fn as_ptr(&self) -> *const T;
/**
@ -195,8 +224,23 @@ pub trait ImmutableVector<'a, T> {
* Returns the index where the comparator returned `Equal`, or `None` if
* not found.
*/
#[deprecated = "use binary_search"]
fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>;
/// Binary search a sorted vector with a comparator function.
///
/// The comparator function should implement an order consistent
/// with the sort order of the underlying vector, returning an
/// order code that indicates whether its argument is `Less`,
/// `Equal` or `Greater` the desired target.
///
/// If the value is found then `Found` is returned, containing the
/// index of the matching element; if the value is not found then
/// `NotFound` is returned, containing the index where a matching
/// element could be inserted while maintaining sorted order.
#[unstable]
fn binary_search(&self, f: |&T| -> Ordering) -> BinarySearchResult;
/**
* Returns an immutable reference to the first element in this slice
* and adjusts the slice in place so that it no longer contains
@ -213,6 +257,7 @@ pub trait ImmutableVector<'a, T> {
*
* Returns `None` if vector is empty
*/
#[deprecated = "find some other way. sorry"]
fn shift_ref(&mut self) -> Option<&'a T>;
/**
@ -231,16 +276,18 @@ pub trait ImmutableVector<'a, T> {
*
* Returns `None` if slice is empty.
*/
#[deprecated = "find some other way. sorry"]
fn pop_ref(&mut self) -> Option<&'a T>;
}
impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
#[unstable]
impl<'a,T> ImmutableSlice<'a, T> for &'a [T] {
#[inline]
fn slice(&self, start: uint, end: uint) -> &'a [T] {
assert!(start <= end);
assert!(end <= self.len());
unsafe {
transmute(Slice {
transmute(RawSlice {
data: self.as_ptr().offset(start as int),
len: (end - start)
})
@ -331,6 +378,7 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
fn tail(&self) -> &'a [T] { self.slice(1, self.len()) }
#[inline]
#[deprecated = "use slice_from"]
fn tailn(&self, n: uint) -> &'a [T] { self.slice(n, self.len()) }
#[inline]
@ -339,6 +387,7 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
}
#[inline]
#[deprecated = "use slice_to but note the arguments are different"]
fn initn(&self, n: uint) -> &'a [T] {
self.slice(0, self.len() - n)
}
@ -349,16 +398,23 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
}
#[inline]
#[deprecated = "renamed to `unsafe_get`"]
unsafe fn unsafe_ref(self, index: uint) -> &'a T {
transmute(self.repr().data.offset(index as int))
}
#[inline]
unsafe fn unsafe_get(self, index: uint) -> &'a T {
transmute(self.repr().data.offset(index as int))
}
#[inline]
fn as_ptr(&self) -> *const T {
self.repr().data
}
#[deprecated = "use binary_search"]
fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint> {
let mut base : uint = 0;
let mut lim : uint = self.len();
@ -378,9 +434,29 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
return None;
}
#[unstable]
fn binary_search(&self, f: |&T| -> Ordering) -> BinarySearchResult {
let mut base : uint = 0;
let mut lim : uint = self.len();
while lim != 0 {
let ix = base + (lim >> 1);
match f(&self[ix]) {
Equal => return Found(ix),
Less => {
base = ix + 1;
lim -= 1;
}
Greater => ()
}
lim >>= 1;
}
return NotFound(base);
}
fn shift_ref(&mut self) -> Option<&'a T> {
unsafe {
let s: &mut Slice<T> = transmute(self);
let s: &mut RawSlice<T> = transmute(self);
match raw::shift_ptr(s) {
Some(p) => Some(&*p),
None => None
@ -390,7 +466,7 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
fn pop_ref(&mut self) -> Option<&'a T> {
unsafe {
let s: &mut Slice<T> = transmute(self);
let s: &mut RawSlice<T> = transmute(self);
match raw::pop_ptr(s) {
Some(p) => Some(&*p),
None => None
@ -401,7 +477,8 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
/// Extension methods for vectors such that their elements are
/// mutable.
pub trait MutableVector<'a, T> {
#[experimental = "may merge with other traits; may lose region param; needs review"]
pub trait MutableSlice<'a, T> {
/// Returns a mutable reference to the element at the given index,
/// or `None` if the index is out of bounds
fn get_mut(self, index: uint) -> Option<&'a mut T>;
@ -465,6 +542,7 @@ pub trait MutableVector<'a, T> {
*
* Returns `None` if slice is empty
*/
#[deprecated = "find some other way. sorry"]
fn mut_shift_ref(&mut self) -> Option<&'a mut T>;
/**
@ -483,6 +561,7 @@ pub trait MutableVector<'a, T> {
*
* Returns `None` if slice is empty.
*/
#[deprecated = "find some other way. sorry"]
fn mut_pop_ref(&mut self) -> Option<&'a mut T>;
/// Swaps two elements in a vector.
@ -607,7 +686,8 @@ pub trait MutableVector<'a, T> {
unsafe fn copy_memory(self, src: &[T]);
}
impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
#[experimental = "trait is experimental"]
impl<'a,T> MutableSlice<'a, T> for &'a mut [T] {
#[inline]
fn get_mut(self, index: uint) -> Option<&'a mut T> {
if index < self.len() { Some(&mut self[index]) } else { None }
@ -620,7 +700,7 @@ impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
assert!(start <= end);
assert!(end <= self.len());
unsafe {
transmute(Slice {
transmute(RawSlice {
data: self.as_mut_ptr().offset(start as int) as *const T,
len: (end - start)
})
@ -685,7 +765,7 @@ impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
fn mut_shift_ref(&mut self) -> Option<&'a mut T> {
unsafe {
let s: &mut Slice<T> = transmute(self);
let s: &mut RawSlice<T> = transmute(self);
match raw::shift_ptr(s) {
// FIXME #13933: this `&` -> `&mut` cast is a little
// dubious
@ -697,7 +777,7 @@ impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
fn mut_pop_ref(&mut self) -> Option<&'a mut T> {
unsafe {
let s: &mut Slice<T> = transmute(self);
let s: &mut RawSlice<T> = transmute(self);
match raw::pop_ptr(s) {
// FIXME #13933: this `&` -> `&mut` cast is a little
// dubious
@ -755,7 +835,8 @@ impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
}
/// Extension methods for vectors contain `PartialEq` elements.
pub trait ImmutableEqVector<T:PartialEq> {
#[unstable = "may merge with other traits"]
pub trait ImmutablePartialEqSlice<T:PartialEq> {
/// Find the first index containing a matching value
fn position_elem(&self, t: &T) -> Option<uint>;
@ -772,7 +853,8 @@ pub trait ImmutableEqVector<T:PartialEq> {
fn ends_with(&self, needle: &[T]) -> bool;
}
impl<'a,T:PartialEq> ImmutableEqVector<T> for &'a [T] {
#[unstable = "trait is unstable"]
impl<'a,T:PartialEq> ImmutablePartialEqSlice<T> for &'a [T] {
#[inline]
fn position_elem(&self, x: &T) -> Option<uint> {
self.iter().position(|y| *x == *y)
@ -802,23 +884,51 @@ impl<'a,T:PartialEq> ImmutableEqVector<T> for &'a [T] {
}
/// Extension methods for vectors containing `Ord` elements.
pub trait ImmutableOrdVector<T: Ord> {
#[unstable = "may merge with other traits"]
pub trait ImmutableOrdSlice<T: Ord> {
/**
* Binary search a sorted vector for a given element.
*
* Returns the index of the element or None if not found.
*/
#[deprecated = "use binary_search_elem"]
fn bsearch_elem(&self, x: &T) -> Option<uint>;
/**
* Binary search a sorted vector for a given element.
*
* If the value is found then `Found` is returned, containing the
* index of the matching element; if the value is not found then
* `NotFound` is returned, containing the index where a matching
* element could be inserted while maintaining sorted order.
*/
#[unstable]
fn binary_search_elem(&self, x: &T) -> BinarySearchResult;
}
impl<'a, T: Ord> ImmutableOrdVector<T> for &'a [T] {
#[unstable = "trait is unstable"]
impl<'a, T: Ord> ImmutableOrdSlice<T> for &'a [T] {
#[deprecated = "use binary_search_elem"]
#[allow(deprecated)]
fn bsearch_elem(&self, x: &T) -> Option<uint> {
self.bsearch(|p| p.cmp(x))
}
#[unstable]
fn binary_search_elem(&self, x: &T) -> BinarySearchResult {
self.binary_search(|p| p.cmp(x))
}
}
/// Trait for &[T] where T is Cloneable
pub trait MutableCloneableVector<T> {
#[unstable = "may merge with other traits"]
pub trait MutableCloneableSlice<T> {
/// Copies as many elements from `src` as it can into `self` (the
/// shorter of `self.len()` and `src.len()`). Returns the number
/// of elements copied.
#[deprecated = "renamed to clone_from_slice"]
fn copy_from(self, s: &[T]) -> uint { self.clone_from_slice(s) }
/// Copies as many elements from `src` as it can into `self` (the
/// shorter of `self.len()` and `src.len()`). Returns the number
/// of elements copied.
@ -826,7 +936,7 @@ pub trait MutableCloneableVector<T> {
/// # Example
///
/// ```rust
/// use std::slice::MutableCloneableVector;
/// use std::slice::MutableCloneableSlice;
///
/// let mut dst = [0i, 0, 0];
/// let src = [1i, 2];
@ -838,12 +948,13 @@ pub trait MutableCloneableVector<T> {
/// assert!(dst.copy_from(src2) == 3);
/// assert!(dst == [3i, 4, 5]);
/// ```
fn copy_from(self, &[T]) -> uint;
fn clone_from_slice(self, &[T]) -> uint;
}
impl<'a, T:Clone> MutableCloneableVector<T> for &'a mut [T] {
#[unstable = "trait is unstable"]
impl<'a, T:Clone> MutableCloneableSlice<T> for &'a mut [T] {
#[inline]
fn copy_from(self, src: &[T]) -> uint {
fn clone_from_slice(self, src: &[T]) -> uint {
for (a, b) in self.mut_iter().zip(src.iter()) {
a.clone_from(b);
}
@ -859,16 +970,19 @@ impl<'a, T:Clone> MutableCloneableVector<T> for &'a mut [T] {
//
/// Any vector that can be represented as a slice.
pub trait Vector<T> {
#[unstable = "may merge with other traits"]
pub trait Slice<T> {
/// Work with `self` as a slice.
fn as_slice<'a>(&'a self) -> &'a [T];
}
impl<'a,T> Vector<T> for &'a [T] {
#[unstable = "trait is unstable"]
impl<'a,T> Slice<T> for &'a [T] {
#[inline(always)]
fn as_slice<'a>(&'a self) -> &'a [T] { *self }
}
#[experimental = "trait is experimental"]
impl<'a, T> Collection for &'a [T] {
/// Returns the length of a vector
#[inline]
@ -877,6 +991,7 @@ impl<'a, T> Collection for &'a [T] {
}
}
#[unstable = "waiting for DST"]
impl<'a, T> Default for &'a [T] {
fn default() -> &'a [T] { &[] }
}
@ -891,6 +1006,7 @@ impl<'a, T> Default for &'a [T] {
// The shared definition of the `Item` and `MutItems` iterators
macro_rules! iterator {
(struct $name:ident -> $ptr:ty, $elem:ty) => {
#[experimental = "needs review"]
impl<'a, T> Iterator<$elem> for $name<'a, T> {
#[inline]
fn next(&mut self) -> Option<$elem> {
@ -926,6 +1042,7 @@ macro_rules! iterator {
}
}
#[experimental = "needs review"]
impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<$elem> {
@ -953,6 +1070,7 @@ macro_rules! iterator {
}
/// Immutable slice iterator
#[experimental = "needs review"]
pub struct Items<'a, T> {
ptr: *const T,
end: *const T,
@ -961,12 +1079,15 @@ pub struct Items<'a, T> {
iterator!{struct Items -> *const T, &'a T}
#[experimental = "needs review"]
impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}
#[experimental = "needs review"]
impl<'a, T> Clone for Items<'a, T> {
fn clone(&self) -> Items<'a, T> { *self }
}
#[experimental = "needs review"]
impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
#[inline]
fn indexable(&self) -> uint {
@ -992,6 +1113,7 @@ impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
}
/// Mutable slice iterator
#[experimental = "needs review"]
pub struct MutItems<'a, T> {
ptr: *mut T,
end: *mut T,
@ -1001,16 +1123,19 @@ pub struct MutItems<'a, T> {
iterator!{struct MutItems -> *mut T, &'a mut T}
#[experimental = "needs review"]
impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
/// An iterator over the slices of a vector separated by elements that
/// match a predicate function.
#[experimental = "needs review"]
pub struct Splits<'a, T> {
v: &'a [T],
pred: |t: &T|: 'a -> bool,
finished: bool
}
#[experimental = "needs review"]
impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
#[inline]
fn next(&mut self) -> Option<&'a [T]> {
@ -1039,6 +1164,7 @@ impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
}
}
#[experimental = "needs review"]
impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<&'a [T]> {
@ -1060,12 +1186,14 @@ impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> {
/// An iterator over the subslices of the vector which are separated
/// by elements that match `pred`.
#[experimental = "needs review"]
pub struct MutSplits<'a, T> {
v: &'a mut [T],
pred: |t: &T|: 'a -> bool,
finished: bool
}
#[experimental = "needs review"]
impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
#[inline]
fn next(&mut self) -> Option<&'a mut [T]> {
@ -1102,6 +1230,7 @@ impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
}
}
#[experimental = "needs review"]
impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<&'a mut [T]> {
@ -1126,12 +1255,14 @@ impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
/// An iterator over the slices of a vector separated by elements that
/// match a predicate function, splitting at most a fixed number of times.
#[experimental = "needs review"]
pub struct SplitsN<'a, T> {
iter: Splits<'a, T>,
count: uint,
invert: bool
}
#[experimental = "needs review"]
impl<'a, T> Iterator<&'a [T]> for SplitsN<'a, T> {
#[inline]
fn next(&mut self) -> Option<&'a [T]> {
@ -1161,11 +1292,13 @@ impl<'a, T> Iterator<&'a [T]> for SplitsN<'a, T> {
/// An iterator over the (overlapping) slices of length `size` within
/// a vector.
#[deriving(Clone)]
#[experimental = "needs review"]
pub struct Windows<'a, T> {
v: &'a [T],
size: uint
}
#[experimental = "needs review"]
impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
#[inline]
fn next(&mut self) -> Option<&'a [T]> {
@ -1195,11 +1328,13 @@ impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
/// When the vector len is not evenly divided by the chunk size,
/// the last slice of the iteration will be the remainder.
#[deriving(Clone)]
#[experimental = "needs review"]
pub struct Chunks<'a, T> {
v: &'a [T],
size: uint
}
#[experimental = "needs review"]
impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
#[inline]
fn next(&mut self) -> Option<&'a [T]> {
@ -1225,6 +1360,7 @@ impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
}
}
#[experimental = "needs review"]
impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<&'a [T]> {
@ -1240,6 +1376,7 @@ impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
}
}
#[experimental = "needs review"]
impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
#[inline]
fn indexable(&self) -> uint {
@ -1263,11 +1400,13 @@ impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
/// An iterator over a vector in (non-overlapping) mutable chunks (`size` elements at a time). When
/// the vector len is not evenly divided by the chunk size, the last slice of the iteration will be
/// the remainder.
#[experimental = "needs review"]
pub struct MutChunks<'a, T> {
v: &'a mut [T],
chunk_size: uint
}
#[experimental = "needs review"]
impl<'a, T> Iterator<&'a mut [T]> for MutChunks<'a, T> {
#[inline]
fn next(&mut self) -> Option<&'a mut [T]> {
@ -1294,6 +1433,7 @@ impl<'a, T> Iterator<&'a mut [T]> for MutChunks<'a, T> {
}
}
#[experimental = "needs review"]
impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<&'a mut [T]> {
@ -1313,6 +1453,43 @@ impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
/// The result of calling `binary_search`.
///
/// `Found` means the search succeeded, and the contained value is the
/// index of the matching element. `NotFound` means the search
/// succeeded, and the contained value is an index where a matching
/// value could be inserted while maintaining sort order.
#[deriving(PartialEq, Show)]
#[experimental = "needs review"]
pub enum BinarySearchResult {
/// The index of the found value.
Found(uint),
/// The index where the value should have been found.
NotFound(uint)
}
#[experimental = "needs review"]
impl BinarySearchResult {
/// Converts a `Found` to `Some`, `NotFound` to `None`.
/// Similar to `Result::ok`.
pub fn found(&self) -> Option<uint> {
match *self {
Found(i) => Some(i),
NotFound(_) => None
}
}
/// Convert a `Found` to `None`, `NotFound` to `Some`.
/// Similar to `Result::err`.
pub fn not_found(&self) -> Option<uint> {
match *self {
Found(_) => None,
NotFound(i) => Some(i)
}
}
}
//
// Free functions
@ -1321,19 +1498,21 @@ impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
/**
* Converts a pointer to A into a slice of length 1 (without copying).
*/
#[unstable = "waiting for DST"]
pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
unsafe {
transmute(Slice { data: s, len: 1 })
transmute(RawSlice { data: s, len: 1 })
}
}
/**
* Converts a pointer to A into a slice of length 1 (without copying).
*/
#[unstable = "waiting for DST"]
pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
unsafe {
let ptr: *const A = transmute(s);
transmute(Slice { data: ptr, len: 1 })
transmute(RawSlice { data: ptr, len: 1 })
}
}
@ -1345,6 +1524,7 @@ pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
//
/// Unsafe operations
#[experimental = "needs review"]
pub mod raw {
use mem::transmute;
use ptr::RawPtr;
@ -1410,10 +1590,11 @@ pub mod raw {
}
/// Operations on `[u8]`.
#[experimental = "needs review"]
pub mod bytes {
use collections::Collection;
use ptr;
use slice::MutableVector;
use slice::MutableSlice;
/// A trait for operations on mutable `[u8]`s.
pub trait MutableByteVector {
@ -1447,6 +1628,7 @@ pub mod bytes {
// Boilerplate traits
//
#[unstable = "waiting for DST"]
impl<'a,T:PartialEq> PartialEq for &'a [T] {
fn eq(&self, other: & &'a [T]) -> bool {
self.len() == other.len() &&
@ -1458,19 +1640,23 @@ impl<'a,T:PartialEq> PartialEq for &'a [T] {
}
}
#[unstable = "waiting for DST"]
impl<'a,T:Eq> Eq for &'a [T] {}
impl<'a,T:PartialEq, V: Vector<T>> Equiv<V> for &'a [T] {
#[unstable = "waiting for DST"]
impl<'a,T:PartialEq, V: Slice<T>> Equiv<V> for &'a [T] {
#[inline]
fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
}
#[unstable = "waiting for DST"]
impl<'a,T:Ord> Ord for &'a [T] {
fn cmp(&self, other: & &'a [T]) -> Ordering {
order::cmp(self.iter(), other.iter())
}
}
#[unstable = "waiting for DST"]
impl<'a, T: PartialOrd> PartialOrd for &'a [T] {
#[inline]
fn partial_cmp(&self, other: &&'a [T]) -> Option<Ordering> {

View file

@ -30,7 +30,7 @@ use iter::range;
use num::{CheckedMul, Saturating};
use option::{Option, None, Some};
use raw::Repr;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use slice;
use uint;
@ -964,7 +964,7 @@ pub mod raw {
use collections::Collection;
use ptr::RawPtr;
use raw::Slice;
use slice::{ImmutableVector};
use slice::{ImmutableSlice};
use str::{is_utf8, StrSlice};
/// Converts a slice of bytes to a string slice without checking
@ -1147,22 +1147,22 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: Vec<&str> = "Mary had a little lambda".splitn(' ', 2).collect();
/// let v: Vec<&str> = "Mary had a little lambda".splitn(2, ' ').collect();
/// assert_eq!(v, vec!["Mary", "had", "a little lambda"]);
///
/// let v: Vec<&str> = "abc1def2ghi".splitn(|c: char| c.is_digit(), 1).collect();
/// let v: Vec<&str> = "abc1def2ghi".splitn(1, |c: char| c.is_digit()).collect();
/// assert_eq!(v, vec!["abc", "def2ghi"]);
///
/// let v: Vec<&str> = "lionXXtigerXleopard".splitn('X', 2).collect();
/// let v: Vec<&str> = "lionXXtigerXleopard".splitn(2, 'X').collect();
/// assert_eq!(v, vec!["lion", "", "tigerXleopard"]);
///
/// let v: Vec<&str> = "abcXdef".splitn('X', 0).collect();
/// let v: Vec<&str> = "abcXdef".splitn(0, 'X').collect();
/// assert_eq!(v, vec!["abcXdef"]);
///
/// let v: Vec<&str> = "".splitn('X', 1).collect();
/// let v: Vec<&str> = "".splitn(1, 'X').collect();
/// assert_eq!(v, vec![""]);
/// ```
fn splitn<Sep: CharEq>(&self, sep: Sep, count: uint) -> CharSplitsN<'a, Sep>;
fn splitn<Sep: CharEq>(&self, count: uint, sep: Sep) -> CharSplitsN<'a, Sep>;
/// An iterator over substrings of `self`, separated by characters
/// matched by `sep`.
@ -1197,16 +1197,16 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: Vec<&str> = "Mary had a little lamb".rsplitn(' ', 2).collect();
/// let v: Vec<&str> = "Mary had a little lamb".rsplitn(2, ' ').collect();
/// assert_eq!(v, vec!["lamb", "little", "Mary had a"]);
///
/// let v: Vec<&str> = "abc1def2ghi".rsplitn(|c: char| c.is_digit(), 1).collect();
/// let v: Vec<&str> = "abc1def2ghi".rsplitn(1, |c: char| c.is_digit()).collect();
/// assert_eq!(v, vec!["ghi", "abc1def"]);
///
/// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn('X', 2).collect();
/// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(2, 'X').collect();
/// assert_eq!(v, vec!["leopard", "tiger", "lionX"]);
/// ```
fn rsplitn<Sep: CharEq>(&self, sep: Sep, count: uint) -> CharSplitsN<'a, Sep>;
fn rsplitn<Sep: CharEq>(&self, count: uint, sep: Sep) -> CharSplitsN<'a, Sep>;
/// An iterator over the start and end indices of the disjoint
/// matches of `sep` within `self`.
@ -1697,7 +1697,7 @@ impl<'a> StrSlice<'a> for &'a str {
}
#[inline]
fn splitn<Sep: CharEq>(&self, sep: Sep, count: uint)
fn splitn<Sep: CharEq>(&self, count: uint, sep: Sep)
-> CharSplitsN<'a, Sep> {
CharSplitsN {
iter: self.split(sep),
@ -1716,7 +1716,7 @@ impl<'a> StrSlice<'a> for &'a str {
}
#[inline]
fn rsplitn<Sep: CharEq>(&self, sep: Sep, count: uint)
fn rsplitn<Sep: CharEq>(&self, count: uint, sep: Sep)
-> CharSplitsN<'a, Sep> {
CharSplitsN {
iter: self.split(sep),

View file

@ -28,4 +28,5 @@ mod option;
mod ptr;
mod raw;
mod result;
mod slice;
mod tuple;

35
src/libcoretest/slice.rs Normal file
View file

@ -0,0 +1,35 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::slice::{Found, NotFound};
#[test]
fn binary_search_not_found() {
let b = [1i, 2, 4, 6, 8, 9];
assert!(b.binary_search(|v| v.cmp(&6)) == Found(3));
let b = [1i, 2, 4, 6, 8, 9];
assert!(b.binary_search(|v| v.cmp(&5)) == NotFound(3));
let b = [1i, 2, 4, 6, 7, 8, 9];
assert!(b.binary_search(|v| v.cmp(&6)) == Found(3));
let b = [1i, 2, 4, 6, 7, 8, 9];
assert!(b.binary_search(|v| v.cmp(&5)) == NotFound(3));
let b = [1i, 2, 4, 6, 8, 9];
assert!(b.binary_search(|v| v.cmp(&8)) == Found(4));
let b = [1i, 2, 4, 6, 8, 9];
assert!(b.binary_search(|v| v.cmp(&7)) == NotFound(4));
let b = [1i, 2, 4, 6, 7, 8, 9];
assert!(b.binary_search(|v| v.cmp(&8)) == Found(5));
let b = [1i, 2, 4, 5, 6, 8, 9];
assert!(b.binary_search(|v| v.cmp(&7)) == NotFound(5));
let b = [1i, 2, 4, 5, 6, 8, 9];
assert!(b.binary_search(|v| v.cmp(&0)) == NotFound(0));
let b = [1i, 2, 4, 5, 6, 8];
assert!(b.binary_search(|v| v.cmp(&9)) == NotFound(6));
}

View file

@ -84,7 +84,7 @@ impl<'a, T: Ord> Ord for MaybeOwnedVector<'a, T> {
}
}
impl<'a, T: PartialEq, V: Vector<T>> Equiv<V> for MaybeOwnedVector<'a, T> {
impl<'a, T: PartialEq, V: Slice<T>> Equiv<V> for MaybeOwnedVector<'a, T> {
fn equiv(&self, other: &V) -> bool {
self.as_slice() == other.as_slice()
}
@ -99,7 +99,7 @@ impl<'a, T: PartialEq, V: Vector<T>> Equiv<V> for MaybeOwnedVector<'a, T> {
// In any case, with `Vector` in place, the client can just use
// `as_slice` if they prefer that over `match`.
impl<'b,T> slice::Vector<T> for MaybeOwnedVector<'b,T> {
impl<'b,T> Slice<T> for MaybeOwnedVector<'b,T> {
fn as_slice<'a>(&'a self) -> &'a [T] {
match self {
&Growable(ref v) => v.as_slice(),

View file

@ -341,7 +341,7 @@ impl<T: FromStr + Clone + Integer + PartialOrd>
FromStr for Ratio<T> {
/// Parses `numer/denom` or just `numer`.
fn from_str(s: &str) -> Option<Ratio<T>> {
let mut split = s.splitn('/', 1);
let mut split = s.splitn(1, '/');
let num = split.next().and_then(|n| FromStr::from_str(n));
let den = split.next().or(Some("1")).and_then(|d| FromStr::from_str(d));
@ -357,7 +357,7 @@ impl<T: FromStrRadix + Clone + Integer + PartialOrd>
FromStrRadix for Ratio<T> {
/// Parses `numer/denom` where the numbers are in base `radix`.
fn from_str_radix(s: &str, radix: uint) -> Option<Ratio<T>> {
let split: Vec<&str> = s.splitn('/', 1).collect();
let split: Vec<&str> = s.splitn(1, '/').collect();
if split.len() < 2 {
None
} else {

View file

@ -348,7 +348,7 @@ impl Isaac64Rng {
static MP_VEC: [(uint, uint), .. 2] = [(0,MIDPOINT), (MIDPOINT, 0)];
macro_rules! ind (
($x:expr) => {
*self.mem.unsafe_ref(($x as uint >> 3) & (RAND_SIZE_64 - 1))
*self.mem.unsafe_get(($x as uint >> 3) & (RAND_SIZE_64 - 1))
}
);
@ -362,8 +362,8 @@ impl Isaac64Rng {
let mix = if $j == 0 {!mix} else {mix};
unsafe {
let x = *self.mem.unsafe_ref(base + mr_offset);
a = mix + *self.mem.unsafe_ref(base + m2_offset);
let x = *self.mem.unsafe_get(base + mr_offset);
a = mix + *self.mem.unsafe_get(base + m2_offset);
let y = ind!(x) + a + b;
self.mem.unsafe_set(base + mr_offset, y);
@ -379,8 +379,8 @@ impl Isaac64Rng {
let mix = if $j == 0 {!mix} else {mix};
unsafe {
let x = *self.mem.unsafe_ref(base + mr_offset);
a = mix + *self.mem.unsafe_ref(base + m2_offset);
let x = *self.mem.unsafe_get(base + mr_offset);
a = mix + *self.mem.unsafe_get(base + m2_offset);
let y = ind!(x) + a + b;
self.mem.unsafe_set(base + mr_offset, y);
@ -416,7 +416,7 @@ impl Rng for Isaac64Rng {
self.isaac64();
}
self.cnt -= 1;
unsafe { *self.rsl.unsafe_ref(self.cnt) }
unsafe { *self.rsl.unsafe_get(self.cnt) }
}
}

View file

@ -13,6 +13,7 @@ use std::cmp;
use std::fmt;
use std::iter;
use std::num;
use std::slice;
/// Static data containing Unicode ranges for general categories and scripts.
use unicode::regex::{UNICODE_CLASSES, PERLD, PERLS, PERLW};
@ -518,7 +519,7 @@ impl<'a> Parser<'a> {
min = try!(self.parse_uint(inner.as_slice()));
max = Some(min);
} else {
let pieces: Vec<&str> = inner.as_slice().splitn(',', 1).collect();
let pieces: Vec<&str> = inner.as_slice().splitn(1, ',').collect();
let (smin, smax) = (pieces[0], pieces[1]);
if smin.len() == 0 {
return self.err("Max repetitions cannot be specified \
@ -1017,9 +1018,9 @@ fn is_valid_cap(c: char) -> bool {
}
fn find_class(classes: NamedClasses, name: &str) -> Option<Vec<(char, char)>> {
match classes.bsearch(|&(s, _)| s.cmp(&name)) {
Some(i) => Some(Vec::from_slice(classes[i].val1())),
None => None,
match classes.binary_search(|&(s, _)| s.cmp(&name)) {
slice::Found(i) => Some(Vec::from_slice(classes[i].val1())),
slice::NotFound(_) => None,
}
}

View file

@ -35,7 +35,7 @@
use std::cmp;
use std::mem;
use std::slice::MutableVector;
use std::slice::MutableSlice;
use compile::{
Program,
Match, OneChar, CharClass, Any, EmptyBegin, EmptyEnd, EmptyWordBoundary,
@ -222,8 +222,8 @@ impl<'r, 't> Nfa<'r, 't> {
let negate = flags & FLAG_NEGATED > 0;
let casei = flags & FLAG_NOCASE > 0;
let found = ranges.as_slice();
let found = found.bsearch(|&rc| class_cmp(casei, c, rc));
let found = found.is_some();
let found = found.binary_search(|&rc| class_cmp(casei, c, rc))
.found().is_some();
if found ^ negate {
self.add(nlist, pc+1, caps);
}
@ -513,7 +513,7 @@ pub fn is_word(c: Option<char>) -> bool {
// Try the common ASCII case before invoking binary search.
match c {
'_' | '0' .. '9' | 'a' .. 'z' | 'A' .. 'Z' => true,
_ => PERLW.bsearch(|&(start, end)| {
_ => PERLW.binary_search(|&(start, end)| {
if c >= start && c <= end {
Equal
} else if start > c {
@ -521,7 +521,7 @@ pub fn is_word(c: Option<char>) -> bool {
} else {
Less
}
}).is_some()
}).found().is_some()
}
}

View file

@ -112,7 +112,7 @@ mod test {
use core::iter::Iterator;
use core::collections::Collection;
use core::str::StrSlice;
use core::slice::{MutableVector, ImmutableVector};
use core::slice::{MutableSlice, ImmutableSlice};
use super::{memcmp, memset, memcpy, memmove};

View file

@ -353,7 +353,7 @@ pub fn build_codegen_options(matches: &getopts::Matches) -> CodegenOptions
{
let mut cg = basic_codegen_options();
for option in matches.opt_strs("C").move_iter() {
let mut iter = option.as_slice().splitn('=', 1);
let mut iter = option.as_slice().splitn(1, '=');
let key = iter.next().unwrap();
let value = iter.next();
let option_to_lookup = key.replace("-", "_");
@ -750,7 +750,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
let mut externs = HashMap::new();
for arg in matches.opt_strs("extern").iter() {
let mut parts = arg.as_slice().splitn('=', 1);
let mut parts = arg.as_slice().splitn(1, '=');
let name = match parts.next() {
Some(s) => s,
None => early_error("--extern value must not be empty"),

View file

@ -356,7 +356,7 @@ pub enum PpMode {
}
fn parse_pretty(sess: &Session, name: &str) -> (PpMode, Option<driver::UserIdentifiedItem>) {
let mut split = name.splitn('=', 1);
let mut split = name.splitn(1, '=');
let first = split.next().unwrap();
let opt_second = split.next();
let first = match first {

View file

@ -379,7 +379,7 @@ fn mk_test_module(cx: &TestCtxt, reexport_test_harness_main: &Option<InternedStr
let mainfn = (quote_item!(&cx.ext_cx,
pub fn main() {
#![main]
use std::slice::Vector;
use std::slice::Slice;
test::test_main_static(::std::os::args().as_slice(), TESTS);
}
)).unwrap();

View file

@ -328,7 +328,7 @@ fn acquire_input(input: &str,
fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
let mut externs = HashMap::new();
for arg in matches.opt_strs("extern").iter() {
let mut parts = arg.as_slice().splitn('=', 1);
let mut parts = arg.as_slice().splitn(1, '=');
let name = match parts.next() {
Some(s) => s,
None => {

View file

@ -19,7 +19,7 @@ use fmt;
use iter::Iterator;
use mem;
use option::{Option, Some, None};
use slice::{ImmutableVector, MutableVector, Vector};
use slice::{ImmutableSlice, MutableSlice, Slice};
use str::{Str, StrSlice};
use str;
use string::String;

View file

@ -43,7 +43,7 @@ use option::{Option, Some, None};
use ptr::RawPtr;
use ptr;
use raw;
use slice::Vector;
use slice::Slice;
/// The type representing a foreign chunk of memory
pub struct CVec<T> {
@ -145,7 +145,7 @@ impl<T> CVec<T> {
}
}
impl<T> Vector<T> for CVec<T> {
impl<T> Slice<T> for CVec<T> {
/// View the stored data as a slice.
fn as_slice<'a>(&'a self) -> &'a [T] {
unsafe {

View file

@ -2743,7 +2743,7 @@ mod test_set {
use prelude::*;
use super::HashSet;
use slice::ImmutableEqVector;
use slice::ImmutablePartialEqSlice;
use collections::Collection;
#[test]

View file

@ -29,7 +29,7 @@ use option::*;
use os;
use path::{Path,GenericPath};
use result::*;
use slice::{Vector,ImmutableVector};
use slice::{Slice,ImmutableSlice};
use str;
use string::String;
use vec::Vec;

View file

@ -19,7 +19,7 @@ use iter::ExactSize;
use ops::Drop;
use option::{Some, None, Option};
use result::{Ok, Err};
use slice::{ImmutableVector, MutableVector};
use slice::{ImmutableSlice, MutableSlice};
use slice;
use vec::Vec;

View file

@ -15,7 +15,7 @@ use comm::{Sender, Receiver};
use io;
use option::{None, Option, Some};
use result::{Ok, Err};
use slice::{bytes, MutableVector, ImmutableVector};
use slice::{bytes, MutableSlice, ImmutableSlice};
use str::StrSlice;
use super::{Reader, Writer, IoResult};
use vec::Vec;

View file

@ -21,7 +21,7 @@ use option::{Option, Some, None};
use result::{Ok, Err};
use io;
use io::{IoError, IoResult, Reader};
use slice::{ImmutableVector, Vector};
use slice::{ImmutableSlice, Slice};
use ptr::RawPtr;
/// An iterator that reads a single byte on each iteration,
@ -153,7 +153,7 @@ pub fn u64_to_be_bytes<T>(n: u64, size: uint, f: |v: &[u8]| -> T) -> T {
pub fn u64_from_be_bytes(data: &[u8], start: uint, size: uint) -> u64 {
use ptr::{copy_nonoverlapping_memory};
use mem::from_be64;
use slice::MutableVector;
use slice::MutableSlice;
assert!(size <= 8u);

View file

@ -70,7 +70,7 @@ use path;
use result::{Err, Ok};
use rt::rtio::LocalIo;
use rt::rtio;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use string::String;
use vec::Vec;

View file

@ -19,7 +19,7 @@ use result::{Err, Ok};
use io;
use io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult};
use slice;
use slice::{Vector, ImmutableVector, MutableVector};
use slice::{Slice, ImmutableSlice, MutableSlice};
use vec::Vec;
static BUF_CAPACITY: uint = 128;

View file

@ -235,7 +235,7 @@ use os;
use boxed::Box;
use result::{Ok, Err, Result};
use rt::rtio;
use slice::{Vector, MutableVector, ImmutableVector};
use slice::{Slice, MutableSlice, ImmutableSlice};
use str::{Str, StrSlice};
use str;
use string::String;

View file

@ -21,7 +21,7 @@ use from_str::FromStr;
use iter::Iterator;
use option::{Option, None, Some};
use str::StrSlice;
use slice::{MutableCloneableVector, ImmutableVector, MutableVector};
use slice::{MutableCloneableSlice, ImmutableSlice, MutableSlice};
pub type Port = u16;

View file

@ -21,7 +21,7 @@ use clone::Clone;
use collections::MutableSeq;
use io::IoResult;
use iter::Iterator;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use result::{Ok,Err};
use io::net::addrinfo::get_host_addresses;
use io::net::ip::SocketAddr;

View file

@ -30,7 +30,7 @@ use option::{Some, None};
use boxed::Box;
use result::{Ok, Err};
use rt::rtio::{IoFactory, LocalIo, RtioSignal, Callback};
use slice::ImmutableVector;
use slice::ImmutableSlice;
use vec::Vec;
/// Signals that can be sent and received

View file

@ -41,7 +41,7 @@ use rt;
use rt::local::Local;
use rt::task::Task;
use rt::rtio::{DontClose, IoFactory, LocalIo, RtioFileStream, RtioTTY};
use slice::ImmutableVector;
use slice::ImmutableSlice;
use str::StrSlice;
use uint;

View file

@ -17,7 +17,7 @@ use from_str::FromStr;
use num::{ToStrRadix, FromStrRadix};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use string::String;
pub use core::i16::{BITS, BYTES, MIN, MAX};

View file

@ -17,7 +17,7 @@ use from_str::FromStr;
use num::{ToStrRadix, FromStrRadix};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use string::String;
pub use core::i32::{BITS, BYTES, MIN, MAX};

View file

@ -17,7 +17,7 @@ use from_str::FromStr;
use num::{ToStrRadix, FromStrRadix};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use string::String;
pub use core::i64::{BITS, BYTES, MIN, MAX};

View file

@ -17,7 +17,7 @@ use from_str::FromStr;
use num::{ToStrRadix, FromStrRadix};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use string::String;
pub use core::i8::{BITS, BYTES, MIN, MAX};

View file

@ -17,7 +17,7 @@ use from_str::FromStr;
use num::{ToStrRadix, FromStrRadix};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use string::String;
pub use core::int::{BITS, BYTES, MIN, MAX};

View file

@ -20,7 +20,7 @@ use num::{Float, FPNaN, FPInfinite, ToPrimitive};
use num;
use ops::{Add, Sub, Mul, Div, Rem, Neg};
use option::{None, Option, Some};
use slice::{ImmutableVector, MutableVector};
use slice::{ImmutableSlice, MutableSlice};
use std::cmp::{PartialOrd, PartialEq};
use str::StrSlice;
use string::String;

View file

@ -17,7 +17,7 @@ use from_str::FromStr;
use num::{ToStrRadix, FromStrRadix};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use string::String;
pub use core::u16::{BITS, BYTES, MIN, MAX};

View file

@ -17,7 +17,7 @@ use from_str::FromStr;
use num::{ToStrRadix, FromStrRadix};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use string::String;
pub use core::u32::{BITS, BYTES, MIN, MAX};

View file

@ -17,7 +17,7 @@ use from_str::FromStr;
use num::{ToStrRadix, FromStrRadix};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use string::String;
pub use core::u64::{BITS, BYTES, MIN, MAX};

View file

@ -17,7 +17,7 @@ use from_str::FromStr;
use num::{ToStrRadix, FromStrRadix};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use string::String;
pub use core::u8::{BITS, BYTES, MIN, MAX};

View file

@ -17,7 +17,7 @@ use from_str::FromStr;
use num::{ToStrRadix, FromStrRadix};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
use slice::ImmutableSlice;
use string::String;
pub use core::uint::{BITS, BYTES, MIN, MAX};

View file

@ -45,7 +45,7 @@ use path::{Path, GenericPath, BytesContainer};
use ptr::RawPtr;
use ptr;
use result::{Err, Ok, Result};
use slice::{Vector, ImmutableVector, MutableVector, ImmutableEqVector};
use slice::{Slice, ImmutableSlice, MutableSlice, ImmutablePartialEqSlice};
use str::{Str, StrSlice, StrAllocating};
use string::String;
use sync::atomic::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
@ -145,7 +145,7 @@ pub mod win32 {
use option::{None, Option};
use option;
use os::TMPBUF_SZ;
use slice::{MutableVector, ImmutableVector};
use slice::{MutableSlice, ImmutableSlice};
use string::String;
use str::StrSlice;
use vec::Vec;

View file

@ -74,8 +74,8 @@ use option::{Option, None, Some};
use str;
use str::{MaybeOwned, Str, StrSlice};
use string::String;
use slice::Vector;
use slice::{ImmutableEqVector, ImmutableVector};
use slice::Slice;
use slice::{ImmutablePartialEqSlice, ImmutableSlice};
use vec::Vec;
/// Typedef for POSIX file paths.

View file

@ -21,8 +21,8 @@ use iter::{DoubleEndedIterator, AdditiveIterator, Extendable, Iterator, Map};
use option::{Option, None, Some};
use str::Str;
use str;
use slice::{CloneableVector, Splits, Vector, VectorVector,
ImmutableEqVector, ImmutableVector};
use slice::{CloneableVector, Splits, Slice, VectorVector,
ImmutablePartialEqSlice, ImmutableSlice};
use vec::Vec;
use super::{BytesContainer, GenericPath, GenericPathUnsafe};
@ -367,7 +367,7 @@ impl Path {
/// Returns a normalized byte vector representation of a path, by removing all empty
/// components, and unnecessary . and .. components.
fn normalize<V: Vector<u8>+CloneableVector<u8>>(v: V) -> Vec<u8> {
fn normalize<V: Slice<u8>+CloneableVector<u8>>(v: V) -> Vec<u8> {
// borrowck is being very picky
let val = {
let is_abs = !v.as_slice().is_empty() && v.as_slice()[0] == SEP_BYTE;

View file

@ -23,7 +23,7 @@ use io::Writer;
use iter::{AdditiveIterator, DoubleEndedIterator, Extendable, Iterator, Map};
use mem;
use option::{Option, Some, None};
use slice::{Vector, ImmutableVector};
use slice::{Slice, ImmutableSlice};
use str::{CharSplits, Str, StrAllocating, StrVector, StrSlice};
use string::String;
use unicode::char::UnicodeChar;

View file

@ -83,11 +83,11 @@
#[doc(no_inline)] pub use tuple::{Tuple5, Tuple6, Tuple7, Tuple8};
#[doc(no_inline)] pub use tuple::{Tuple9, Tuple10, Tuple11, Tuple12};
#[doc(no_inline)] pub use slice::{CloneableVector, ImmutableCloneableVector};
#[doc(no_inline)] pub use slice::{MutableCloneableVector, MutableOrdVector};
#[doc(no_inline)] pub use slice::{ImmutableVector, MutableVector};
#[doc(no_inline)] pub use slice::{ImmutableEqVector, ImmutableOrdVector};
#[doc(no_inline)] pub use slice::{Vector, VectorVector};
#[doc(no_inline)] pub use slice::MutableVectorAllocating;
#[doc(no_inline)] pub use slice::{MutableCloneableSlice, MutableOrdSlice};
#[doc(no_inline)] pub use slice::{ImmutableSlice, MutableSlice};
#[doc(no_inline)] pub use slice::{ImmutablePartialEqSlice, ImmutableOrdSlice};
#[doc(no_inline)] pub use slice::{Slice, VectorVector};
#[doc(no_inline)] pub use slice::MutableSliceAllocating;
#[doc(no_inline)] pub use string::String;
#[doc(no_inline)] pub use vec::Vec;

View file

@ -70,7 +70,7 @@ mod imp {
use rand::Rng;
use result::{Ok};
use self::libc::{c_int, size_t};
use slice::MutableVector;
use slice::MutableSlice;
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
@ -138,7 +138,7 @@ mod imp {
use rt::stack;
use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
use self::libc::types::os::arch::extra::{LONG_PTR};
use slice::MutableVector;
use slice::MutableSlice;
type HCRYPTPROV = LONG_PTR;

View file

@ -258,7 +258,7 @@ mod imp {
pub fn write(w: &mut Writer) -> IoResult<()> {
use iter::{Iterator, range};
use result;
use slice::{MutableVector};
use slice::{MutableSlice};
extern {
fn backtrace(buf: *mut *mut libc::c_void,
@ -398,7 +398,7 @@ mod imp {
use path::GenericPath;
use ptr::RawPtr;
use ptr;
use slice::{ImmutableVector, MutableVector};
use slice::{ImmutableSlice, MutableSlice};
////////////////////////////////////////////////////////////////////////
// libbacktrace.h API
@ -670,7 +670,7 @@ mod imp {
use path::Path;
use result::{Ok, Err};
use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
use slice::ImmutableVector;
use slice::ImmutableSlice;
use str::StrSlice;
use dynamic_lib::DynamicLibrary;

View file

@ -51,7 +51,7 @@ impl fmt::Show for CrateId {
impl FromStr for CrateId {
fn from_str(s: &str) -> Option<CrateId> {
let pieces: Vec<&str> = s.splitn('#', 1).collect();
let pieces: Vec<&str> = s.splitn(1, '#').collect();
let path = pieces.get(0).to_string();
if path.as_slice().starts_with("/") || path.as_slice().ends_with("/") ||
@ -60,7 +60,7 @@ impl FromStr for CrateId {
}
let path_pieces: Vec<&str> = path.as_slice()
.rsplitn('/', 1)
.rsplitn(1, '/')
.collect();
let inferred_name = *path_pieces.get(0);
@ -68,7 +68,7 @@ impl FromStr for CrateId {
(inferred_name.to_string(), None)
} else {
let hash_pieces: Vec<&str> = pieces.get(1)
.splitn(':', 1)
.splitn(1, ':')
.collect();
let (hash_name, hash_version) = if hash_pieces.len() == 1 {
("", *hash_pieces.get(0))

View file

@ -15,20 +15,21 @@
use core::cmp::{Equal, Less, Greater};
use core::option::{Option, Some, None};
use core::slice::ImmutableVector;
use core::slice;
use core::slice::ImmutableSlice;
use tables::normalization::{canonical_table, compatibility_table, composition_table};
fn bsearch_table<T>(c: char, r: &'static [(char, &'static [T])]) -> Option<&'static [T]> {
match r.bsearch(|&(val, _)| {
match r.binary_search(|&(val, _)| {
if c == val { Equal }
else if val < c { Less }
else { Greater }
}) {
Some(idx) => {
slice::Found(idx) => {
let (_, result) = r[idx];
Some(result)
}
None => None
slice::NotFound(_) => None
}
}
@ -82,16 +83,16 @@ pub fn compose(a: char, b: char) -> Option<char> {
match bsearch_table(a, composition_table) {
None => None,
Some(candidates) => {
match candidates.bsearch(|&(val, _)| {
match candidates.binary_search(|&(val, _)| {
if b == val { Equal }
else if val < b { Less }
else { Greater }
}) {
Some(idx) => {
slice::Found(idx) => {
let (_, result) = candidates[idx];
Some(result)
}
None => None
slice::NotFound(_) => None
}
}
}

View file

@ -14,13 +14,12 @@
fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool {
use core::cmp::{Equal, Less, Greater};
use core::slice::ImmutableVector;
use core::option::None;
r.bsearch(|&(lo,hi)| {
use core::slice::ImmutableSlice;
r.binary_search(|&(lo,hi)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
}) != None
}).found().is_some()
}
pub mod general_category {
@ -6228,19 +6227,19 @@ pub mod normalization {
fn bsearch_range_value_table(c: char, r: &'static [(char, char, u8)]) -> u8 {
use core::option::{Some, None};
use core::cmp::{Equal, Less, Greater};
use core::slice::ImmutableVector;
match r.bsearch(|&(lo, hi, _)| {
use core::slice::ImmutableSlice;
use core::slice;
match r.binary_search(|&(lo, hi, _)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
}) {
Some(idx) => {
slice::Found(idx) => {
let (_, _, result) = r[idx];
result
}
None => 0
slice::NotFound(_) => 0
}
}
@ -6354,9 +6353,10 @@ pub mod normalization {
pub mod conversions {
use core::cmp::{Equal, Less, Greater};
use core::slice::ImmutableVector;
use core::slice::ImmutableSlice;
use core::tuple::Tuple2;
use core::option::{Option, Some, None};
use core::slice;
pub fn to_lower(c: char) -> char {
match bsearch_case_table(c, LuLl_table) {
@ -6373,11 +6373,14 @@ pub mod conversions {
}
fn bsearch_case_table(c: char, table: &'static [(char, char)]) -> Option<uint> {
table.bsearch(|&(key, _)| {
match table.binary_search(|&(key, _)| {
if c == key { Equal }
else if key < c { Less }
else { Greater }
})
}) {
slice::Found(i) => Some(i),
slice::NotFound(_) => None,
}
}
static LuLl_table: &'static [(char, char)] = &[
@ -6915,20 +6918,21 @@ pub mod conversions {
pub mod charwidth {
use core::option::{Option, Some, None};
use core::slice::ImmutableVector;
use core::slice::ImmutableSlice;
use core::slice;
fn bsearch_range_value_table(c: char, is_cjk: bool, r: &'static [(char, char, u8, u8)]) -> u8 {
use core::cmp::{Equal, Less, Greater};
match r.bsearch(|&(lo, hi, _, _)| {
match r.binary_search(|&(lo, hi, _, _)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
}) {
Some(idx) => {
slice::Found(idx) => {
let (_, _, r_ncjk, r_cjk) = r[idx];
if is_cjk { r_cjk } else { r_ncjk }
}
None => 1
slice::NotFound(_) => 1
}
}
@ -7112,8 +7116,8 @@ pub mod charwidth {
}
pub mod grapheme {
use core::option::{Some, None};
use core::slice::ImmutableVector;
use core::slice::ImmutableSlice;
use core::slice;
#[allow(non_camel_case_types)]
#[deriving(Clone)]
@ -7132,16 +7136,16 @@ pub mod grapheme {
fn bsearch_range_value_table(c: char, r: &'static [(char, char, GraphemeCat)]) -> GraphemeCat {
use core::cmp::{Equal, Less, Greater};
match r.bsearch(|&(lo, hi, _)| {
match r.binary_search(|&(lo, hi, _)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
}) {
Some(idx) => {
slice::Found(idx) => {
let (_, _, cat) = r[idx];
cat
}
None => GC_Any
slice::NotFound(_) => GC_Any
}
}

View file

@ -396,7 +396,7 @@ pub fn decode_form_urlencoded(s: &[u8])
}
fn split_char_first(s: &str, c: char) -> (&str, &str) {
let mut iter = s.splitn(c, 1);
let mut iter = s.splitn(1, c);
match (iter.next(), iter.next()) {
(Some(a), Some(b)) => (a, b),