auto merge of #17807 : nick29581/rust/slice6, r=aturon

r? @aturon
This commit is contained in:
bors 2014-10-07 06:17:11 +00:00
commit e62ef37cfa
123 changed files with 663 additions and 405 deletions

View file

@ -9,7 +9,7 @@
// except according to those terms. // except according to those terms.
#![crate_type = "bin"] #![crate_type = "bin"]
#![feature(phase)] #![feature(phase, slicing_syntax)]
#![deny(warnings)] #![deny(warnings)]

View file

@ -874,7 +874,7 @@ fn check_error_patterns(props: &TestProps,
if done { return; } if done { return; }
let missing_patterns = let missing_patterns =
props.error_patterns.slice(next_err_idx, props.error_patterns.len()); props.error_patterns[next_err_idx..];
if missing_patterns.len() == 1u { if missing_patterns.len() == 1u {
fatal_proc_rec(format!("error pattern '{}' not found!", fatal_proc_rec(format!("error pattern '{}' not found!",
missing_patterns[0]).as_slice(), missing_patterns[0]).as_slice(),

View file

@ -3837,7 +3837,7 @@ type signature of `print`, and the cast expression in `main`.
Within the body of an item that has type parameter declarations, the names of Within the body of an item that has type parameter declarations, the names of
its type parameters are types: its type parameters are types:
``` ```ignore
fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> Vec<B> { fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> Vec<B> {
if xs.len() == 0 { if xs.len() == 0 {
return vec![]; return vec![];

View file

@ -194,7 +194,7 @@ impl Bitv {
if start > self.storage.len() { if start > self.storage.len() {
start = self.storage.len(); start = self.storage.len();
} }
let mut iter = self.storage.slice_from(start).iter(); let mut iter = self.storage[start..].iter();
MaskWords { MaskWords {
next_word: iter.next(), next_word: iter.next(),
iter: iter, iter: iter,

View file

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

View file

@ -19,8 +19,9 @@
html_root_url = "http://doc.rust-lang.org/master/", html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")] html_playground_url = "http://play.rust-lang.org/")]
#![allow(unknown_features)]
#![feature(macro_rules, default_type_params, phase, globs)] #![feature(macro_rules, default_type_params, phase, globs)]
#![feature(unsafe_destructor, import_shadowing)] #![feature(unsafe_destructor, import_shadowing, slicing_syntax)]
#![no_std] #![no_std]
#[phase(plugin, link)] extern crate core; #[phase(plugin, link)] extern crate core;

View file

@ -271,7 +271,7 @@ impl<T> RingBuf<T> {
/// *num = *num - 2; /// *num = *num - 2;
/// } /// }
/// let b: &[_] = &[&mut 3, &mut 1, &mut 2]; /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
/// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>().as_slice(), b); /// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b);
/// ``` /// ```
pub fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> { pub fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
let start_index = raw_index(self.lo, self.elts.len(), 0); let start_index = raw_index(self.lo, self.elts.len(), 0);
@ -291,7 +291,7 @@ impl<T> RingBuf<T> {
} else { } else {
// Items to iterate goes from start_index to end_index: // Items to iterate goes from start_index to end_index:
let (empty, elts) = self.elts.split_at_mut(0); let (empty, elts) = self.elts.split_at_mut(0);
let remaining1 = elts.slice_mut(start_index, end_index); let remaining1 = elts[mut start_index..end_index];
MutItems { remaining1: remaining1, MutItems { remaining1: remaining1,
remaining2: empty, remaining2: empty,
nelts: self.nelts } nelts: self.nelts }

View file

@ -44,15 +44,20 @@
//! //!
//! A number of traits add methods that allow you to accomplish tasks with slices. //! A number of traits add methods that allow you to accomplish tasks with slices.
//! These traits include `ImmutableSlice`, which is defined for `&[T]` types, //! These traits include `ImmutableSlice`, which is defined for `&[T]` types,
//! and `MutableSlice`, defined for `&mut [T]` types. //! `MutableSlice`, defined for `&mut [T]` types, and `Slice` and `SliceMut`
//! which are defined for `[T]`.
//! //!
//! An example is the method `.slice(a, b)` that returns an immutable "view" into //! An example is the `slice` method which enables slicing syntax `[a..b]` that
//! a `Vec` or another slice from the index interval `[a, b)`: //! returns an immutable "view" into a `Vec` or another slice from the index
//! interval `[a, b)`:
//! //!
//! ```rust //! ```rust
//! let numbers = [0i, 1i, 2i]; //! #![feature(slicing_syntax)]
//! let last_numbers = numbers.slice(1, 3); //! fn main() {
//! // last_numbers is now &[1i, 2i] //! let numbers = [0i, 1i, 2i];
//! let last_numbers = numbers[1..3];
//! // last_numbers is now &[1i, 2i]
//! }
//! ``` //! ```
//! //!
//! ## Implementations of other traits //! ## Implementations of other traits
@ -93,7 +98,7 @@ use core::iter::{range_step, MultiplicativeIterator};
use MutableSeq; use MutableSeq;
use vec::Vec; use vec::Vec;
pub use core::slice::{Chunks, Slice, ImmutableSlice, ImmutablePartialEqSlice}; pub use core::slice::{Chunks, AsSlice, ImmutableSlice, ImmutablePartialEqSlice};
pub use core::slice::{ImmutableOrdSlice, MutableSlice, Items, MutItems}; pub use core::slice::{ImmutableOrdSlice, MutableSlice, Items, MutItems};
pub use core::slice::{MutSplits, MutChunks, Splits}; pub use core::slice::{MutSplits, MutChunks, Splits};
pub use core::slice::{bytes, mut_ref_slice, ref_slice, MutableCloneableSlice}; pub use core::slice::{bytes, mut_ref_slice, ref_slice, MutableCloneableSlice};
@ -112,7 +117,7 @@ pub trait VectorVector<T> {
fn connect_vec(&self, sep: &T) -> Vec<T>; fn connect_vec(&self, sep: &T) -> Vec<T>;
} }
impl<'a, T: Clone, V: Slice<T>> VectorVector<T> for &'a [V] { impl<'a, T: Clone, V: AsSlice<T>> VectorVector<T> for &'a [V] {
fn concat_vec(&self) -> Vec<T> { fn concat_vec(&self) -> Vec<T> {
let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len()); let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
let mut result = Vec::with_capacity(size); let mut result = Vec::with_capacity(size);
@ -610,7 +615,7 @@ impl<'a,T> MutableSliceAllocating<'a, T> for &'a mut [T] {
#[inline] #[inline]
fn move_from(self, mut src: Vec<T>, start: uint, end: uint) -> uint { fn move_from(self, mut src: Vec<T>, start: uint, end: uint) -> uint {
for (a, b) in self.iter_mut().zip(src.slice_mut(start, end).iter_mut()) { for (a, b) in self.iter_mut().zip(src[mut start..end].iter_mut()) {
mem::swap(a, b); mem::swap(a, b);
} }
cmp::min(self.len(), end-start) cmp::min(self.len(), end-start)
@ -702,7 +707,7 @@ impl<'a, T: Ord> MutableOrdSlice<T> for &'a mut [T] {
self.swap(j, i-1); self.swap(j, i-1);
// Step 4: Reverse the (previously) weakly decreasing part // Step 4: Reverse the (previously) weakly decreasing part
self.slice_from_mut(i).reverse(); self[mut i..].reverse();
true true
} }
@ -723,7 +728,7 @@ impl<'a, T: Ord> MutableOrdSlice<T> for &'a mut [T] {
} }
// Step 2: Reverse the weakly increasing part // Step 2: Reverse the weakly increasing part
self.slice_from_mut(i).reverse(); self[mut i..].reverse();
// Step 3: Find the rightmost element equal to or bigger than the pivot (i-1) // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
let mut j = self.len() - 1; let mut j = self.len() - 1;
@ -990,7 +995,7 @@ mod tests {
fn test_slice() { fn test_slice() {
// Test fixed length vector. // Test fixed length vector.
let vec_fixed = [1i, 2, 3, 4]; let vec_fixed = [1i, 2, 3, 4];
let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_vec(); let v_a = vec_fixed[1u..vec_fixed.len()].to_vec();
assert_eq!(v_a.len(), 3u); assert_eq!(v_a.len(), 3u);
let v_a = v_a.as_slice(); let v_a = v_a.as_slice();
assert_eq!(v_a[0], 2); assert_eq!(v_a[0], 2);
@ -998,8 +1003,8 @@ mod tests {
assert_eq!(v_a[2], 4); assert_eq!(v_a[2], 4);
// Test on stack. // Test on stack.
let vec_stack = &[1i, 2, 3]; let vec_stack: &[_] = &[1i, 2, 3];
let v_b = vec_stack.slice(1u, 3u).to_vec(); let v_b = vec_stack[1u..3u].to_vec();
assert_eq!(v_b.len(), 2u); assert_eq!(v_b.len(), 2u);
let v_b = v_b.as_slice(); let v_b = v_b.as_slice();
assert_eq!(v_b[0], 2); assert_eq!(v_b[0], 2);
@ -1007,7 +1012,7 @@ mod tests {
// Test `Box<[T]>` // Test `Box<[T]>`
let vec_unique = vec![1i, 2, 3, 4, 5, 6]; let vec_unique = vec![1i, 2, 3, 4, 5, 6];
let v_d = vec_unique.slice(1u, 6u).to_vec(); let v_d = vec_unique[1u..6u].to_vec();
assert_eq!(v_d.len(), 5u); assert_eq!(v_d.len(), 5u);
let v_d = v_d.as_slice(); let v_d = v_d.as_slice();
assert_eq!(v_d[0], 2); assert_eq!(v_d[0], 2);
@ -1020,21 +1025,21 @@ mod tests {
#[test] #[test]
fn test_slice_from() { fn test_slice_from() {
let vec: &[int] = &[1, 2, 3, 4]; let vec: &[int] = &[1, 2, 3, 4];
assert_eq!(vec.slice_from(0), vec); assert_eq!(vec[0..], vec);
let b: &[int] = &[3, 4]; let b: &[int] = &[3, 4];
assert_eq!(vec.slice_from(2), b); assert_eq!(vec[2..], b);
let b: &[int] = &[]; let b: &[int] = &[];
assert_eq!(vec.slice_from(4), b); assert_eq!(vec[4..], b);
} }
#[test] #[test]
fn test_slice_to() { fn test_slice_to() {
let vec: &[int] = &[1, 2, 3, 4]; let vec: &[int] = &[1, 2, 3, 4];
assert_eq!(vec.slice_to(4), vec); assert_eq!(vec[..4], vec);
let b: &[int] = &[1, 2]; let b: &[int] = &[1, 2];
assert_eq!(vec.slice_to(2), b); assert_eq!(vec[..2], b);
let b: &[int] = &[]; let b: &[int] = &[];
assert_eq!(vec.slice_to(0), b); assert_eq!(vec[..0], b);
} }
@ -1975,7 +1980,7 @@ mod tests {
assert!(a == [7i,2,3,4]); assert!(a == [7i,2,3,4]);
let mut a = [1i,2,3,4,5]; let mut a = [1i,2,3,4,5];
let b = vec![5i,6,7,8,9,0]; let b = vec![5i,6,7,8,9,0];
assert_eq!(a.slice_mut(2,4).move_from(b,1,6), 2); assert_eq!(a[mut 2..4].move_from(b,1,6), 2);
assert!(a == [1i,2,6,7,5]); assert!(a == [1i,2,6,7,5]);
} }
@ -1995,7 +2000,7 @@ mod tests {
#[test] #[test]
fn test_reverse_part() { fn test_reverse_part() {
let mut values = [1i,2,3,4,5]; let mut values = [1i,2,3,4,5];
values.slice_mut(1, 4).reverse(); values[mut 1..4].reverse();
assert!(values == [1,4,3,2,5]); assert!(values == [1,4,3,2,5]);
} }
@ -2042,9 +2047,9 @@ mod tests {
fn test_bytes_set_memory() { fn test_bytes_set_memory() {
use slice::bytes::MutableByteVector; use slice::bytes::MutableByteVector;
let mut values = [1u8,2,3,4,5]; let mut values = [1u8,2,3,4,5];
values.slice_mut(0,5).set_memory(0xAB); values[mut 0..5].set_memory(0xAB);
assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]); assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
values.slice_mut(2,4).set_memory(0xFF); values[mut 2..4].set_memory(0xFF);
assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]); assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
} }
@ -2070,12 +2075,18 @@ mod tests {
let mut values = [1u8,2,3,4,5]; let mut values = [1u8,2,3,4,5];
{ {
let (left, right) = values.split_at_mut(2); let (left, right) = values.split_at_mut(2);
assert!(left.slice(0, left.len()) == [1, 2]); {
let left: &[_] = left;
assert!(left[0..left.len()] == [1, 2]);
}
for p in left.iter_mut() { for p in left.iter_mut() {
*p += 1; *p += 1;
} }
assert!(right.slice(0, right.len()) == [3, 4, 5]); {
let right: &[_] = right;
assert!(right[0..right.len()] == [3, 4, 5]);
}
for p in right.iter_mut() { for p in right.iter_mut() {
*p += 2; *p += 2;
} }
@ -2099,7 +2110,7 @@ mod tests {
} }
assert_eq!(cnt, 3); assert_eq!(cnt, 3);
for f in v.slice(1, 3).iter() { for f in v[1..3].iter() {
assert!(*f == Foo); assert!(*f == Foo);
cnt += 1; cnt += 1;
} }

View file

@ -61,7 +61,7 @@ use core::iter::AdditiveIterator;
use core::mem; use core::mem;
use core::prelude::{Char, Clone, Collection, Eq, Equiv, ImmutableSlice}; use core::prelude::{Char, Clone, Collection, Eq, Equiv, ImmutableSlice};
use core::prelude::{Iterator, MutableSlice, None, Option, Ord, Ordering}; use core::prelude::{Iterator, MutableSlice, None, Option, Ord, Ordering};
use core::prelude::{PartialEq, PartialOrd, Result, Slice, Some, Tuple2}; use core::prelude::{PartialEq, PartialOrd, Result, AsSlice, Some, Tuple2};
use core::prelude::{range}; use core::prelude::{range};
use {Deque, MutableSeq}; use {Deque, MutableSeq};
@ -880,7 +880,7 @@ mod tests {
use {Collection, MutableSeq}; use {Collection, MutableSeq};
use super::*; use super::*;
use std::slice::{Slice, ImmutableSlice}; use std::slice::{AsSlice, ImmutableSlice};
use string::String; use string::String;
use vec::Vec; use vec::Vec;
@ -1678,7 +1678,7 @@ mod tests {
let mut bytes = [0u8, ..4]; let mut bytes = [0u8, ..4];
for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) { for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) {
let len = c.encode_utf8(bytes).unwrap_or(0); let len = c.encode_utf8(bytes).unwrap_or(0);
let s = ::core::str::from_utf8(bytes.slice_to(len)).unwrap(); let s = ::core::str::from_utf8(bytes[..len]).unwrap();
if Some(c) != s.chars().next() { if Some(c) != s.chars().next() {
fail!("character {:x}={} does not decode correctly", c as u32, c); fail!("character {:x}={} does not decode correctly", c as u32, c);
} }
@ -1690,7 +1690,7 @@ mod tests {
let mut bytes = [0u8, ..4]; let mut bytes = [0u8, ..4];
for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) { for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) {
let len = c.encode_utf8(bytes).unwrap_or(0); let len = c.encode_utf8(bytes).unwrap_or(0);
let s = ::core::str::from_utf8(bytes.slice_to(len)).unwrap(); let s = ::core::str::from_utf8(bytes[..len]).unwrap();
if Some(c) != s.chars().rev().next() { if Some(c) != s.chars().rev().next() {
fail!("character {:x}={} does not decode correctly", c as u32, c); fail!("character {:x}={} does not decode correctly", c as u32, c);
} }

View file

@ -160,7 +160,7 @@ impl String {
if i > 0 { if i > 0 {
unsafe { unsafe {
res.as_mut_vec().push_all(v.slice_to(i)) res.as_mut_vec().push_all(v[..i])
}; };
} }
@ -177,7 +177,7 @@ impl String {
macro_rules! error(() => ({ macro_rules! error(() => ({
unsafe { unsafe {
if subseqidx != i_ { if subseqidx != i_ {
res.as_mut_vec().push_all(v.slice(subseqidx, i_)); res.as_mut_vec().push_all(v[subseqidx..i_]);
} }
subseqidx = i; subseqidx = i;
res.as_mut_vec().push_all(REPLACEMENT); res.as_mut_vec().push_all(REPLACEMENT);
@ -246,7 +246,7 @@ impl String {
} }
if subseqidx < total { if subseqidx < total {
unsafe { unsafe {
res.as_mut_vec().push_all(v.slice(subseqidx, total)) res.as_mut_vec().push_all(v[subseqidx..total])
}; };
} }
Owned(res.into_string()) Owned(res.into_string())
@ -928,6 +928,7 @@ impl<S: Str> Add<S, String> for String {
} }
} }
#[cfg(stage0)]
impl ops::Slice<uint, str> for String { impl ops::Slice<uint, str> for String {
#[inline] #[inline]
fn as_slice_<'a>(&'a self) -> &'a str { fn as_slice_<'a>(&'a self) -> &'a str {
@ -949,6 +950,28 @@ impl ops::Slice<uint, str> for String {
self[][*from..*to] self[][*from..*to]
} }
} }
#[cfg(not(stage0))]
impl ops::Slice<uint, str> for String {
#[inline]
fn as_slice_<'a>(&'a self) -> &'a str {
self.as_slice()
}
#[inline]
fn slice_from_or_fail<'a>(&'a self, from: &uint) -> &'a str {
self[][*from..]
}
#[inline]
fn slice_to_or_fail<'a>(&'a self, to: &uint) -> &'a str {
self[][..*to]
}
#[inline]
fn slice_or_fail<'a>(&'a self, from: &uint, to: &uint) -> &'a str {
self[][*from..*to]
}
}
/// Unsafe operations /// Unsafe operations
#[unstable = "waiting on raw module conventions"] #[unstable = "waiting on raw module conventions"]

View file

@ -24,6 +24,7 @@ use core::fmt;
use core::fmt::Show; use core::fmt::Show;
use core::mem::zeroed; use core::mem::zeroed;
use core::mem; use core::mem;
use core::ops::{Slice,SliceMut};
use core::uint; use core::uint;
use core::iter; use core::iter;
use std::hash::{Writer, Hash}; use std::hash::{Writer, Hash};
@ -378,7 +379,7 @@ macro_rules! bound {
} }
}; };
// push to the stack. // push to the stack.
it.stack[it.length] = children.$slice_from(slice_idx).$iter(); it.stack[it.length] = children.$slice_from(&slice_idx).$iter();
it.length += 1; it.length += 1;
if ret { return it } if ret { return it }
}) })
@ -388,11 +389,20 @@ macro_rules! bound {
impl<T> TrieMap<T> { impl<T> TrieMap<T> {
// If `upper` is true then returns upper_bound else returns lower_bound. // If `upper` is true then returns upper_bound else returns lower_bound.
#[cfg(stage0)]
#[inline] #[inline]
fn bound<'a>(&'a self, key: uint, upper: bool) -> Entries<'a, T> { fn bound<'a>(&'a self, key: uint, upper: bool) -> Entries<'a, T> {
bound!(Entries, self = self, bound!(Entries, self = self,
key = key, is_upper = upper, key = key, is_upper = upper,
slice_from = slice_from, iter = iter, slice_from = slice_from_, iter = iter,
mutability = )
}
#[cfg(not(stage0))]
#[inline]
fn bound<'a>(&'a self, key: uint, upper: bool) -> Entries<'a, T> {
bound!(Entries, self = self,
key = key, is_upper = upper,
slice_from = slice_from_or_fail, iter = iter,
mutability = ) mutability = )
} }
@ -430,11 +440,20 @@ impl<T> TrieMap<T> {
self.bound(key, true) self.bound(key, true)
} }
// If `upper` is true then returns upper_bound else returns lower_bound. // If `upper` is true then returns upper_bound else returns lower_bound.
#[cfg(stage0)]
#[inline] #[inline]
fn bound_mut<'a>(&'a mut self, key: uint, upper: bool) -> MutEntries<'a, T> { fn bound_mut<'a>(&'a mut self, key: uint, upper: bool) -> MutEntries<'a, T> {
bound!(MutEntries, self = self, bound!(MutEntries, self = self,
key = key, is_upper = upper, key = key, is_upper = upper,
slice_from = slice_from_mut, iter = iter_mut, slice_from = slice_from_mut_, iter = iter_mut,
mutability = mut)
}
#[cfg(not(stage0))]
#[inline]
fn bound_mut<'a>(&'a mut self, key: uint, upper: bool) -> MutEntries<'a, T> {
bound!(MutEntries, self = self,
key = key, is_upper = upper,
slice_from = slice_from_or_fail_mut, iter = iter_mut,
mutability = mut) mutability = mut)
} }

View file

@ -438,7 +438,7 @@ impl<T:Clone> Clone for Vec<T> {
// self.len <= other.len due to the truncate above, so the // self.len <= other.len due to the truncate above, so the
// slice here is always in-bounds. // slice here is always in-bounds.
let slice = other.slice_from(self.len()); let slice = other[self.len()..];
self.push_all(slice); self.push_all(slice);
} }
} }
@ -460,6 +460,7 @@ impl<T> Index<uint,T> for Vec<T> {
} }
}*/ }*/
#[cfg(stage0)]
impl<T> ops::Slice<uint, [T]> for Vec<T> { impl<T> ops::Slice<uint, [T]> for Vec<T> {
#[inline] #[inline]
fn as_slice_<'a>(&'a self) -> &'a [T] { fn as_slice_<'a>(&'a self) -> &'a [T] {
@ -480,7 +481,29 @@ impl<T> ops::Slice<uint, [T]> for Vec<T> {
self.as_slice().slice_(start, end) self.as_slice().slice_(start, end)
} }
} }
#[cfg(not(stage0))]
impl<T> ops::Slice<uint, [T]> for Vec<T> {
#[inline]
fn as_slice_<'a>(&'a self) -> &'a [T] {
self.as_slice()
}
#[inline]
fn slice_from_or_fail<'a>(&'a self, start: &uint) -> &'a [T] {
self.as_slice().slice_from_or_fail(start)
}
#[inline]
fn slice_to_or_fail<'a>(&'a self, end: &uint) -> &'a [T] {
self.as_slice().slice_to_or_fail(end)
}
#[inline]
fn slice_or_fail<'a>(&'a self, start: &uint, end: &uint) -> &'a [T] {
self.as_slice().slice_or_fail(start, end)
}
}
#[cfg(stage0)]
impl<T> ops::SliceMut<uint, [T]> for Vec<T> { impl<T> ops::SliceMut<uint, [T]> for Vec<T> {
#[inline] #[inline]
fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] { fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] {
@ -501,6 +524,27 @@ impl<T> ops::SliceMut<uint, [T]> for Vec<T> {
self.as_mut_slice().slice_mut_(start, end) self.as_mut_slice().slice_mut_(start, end)
} }
} }
#[cfg(not(stage0))]
impl<T> ops::SliceMut<uint, [T]> for Vec<T> {
#[inline]
fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] {
self.as_mut_slice()
}
#[inline]
fn slice_from_or_fail_mut<'a>(&'a mut self, start: &uint) -> &'a mut [T] {
self.as_mut_slice().slice_from_or_fail_mut(start)
}
#[inline]
fn slice_to_or_fail_mut<'a>(&'a mut self, end: &uint) -> &'a mut [T] {
self.as_mut_slice().slice_to_or_fail_mut(end)
}
#[inline]
fn slice_or_fail_mut<'a>(&'a mut self, start: &uint, end: &uint) -> &'a mut [T] {
self.as_mut_slice().slice_or_fail_mut(start, end)
}
}
#[experimental = "waiting on FromIterator stability"] #[experimental = "waiting on FromIterator stability"]
impl<T> FromIterator<T> for Vec<T> { impl<T> FromIterator<T> for Vec<T> {
@ -547,7 +591,7 @@ impl<T: PartialOrd> PartialOrd for Vec<T> {
impl<T: Eq> Eq for Vec<T> {} impl<T: Eq> Eq for Vec<T> {}
#[experimental] #[experimental]
impl<T: PartialEq, V: Slice<T>> Equiv<V> for Vec<T> { impl<T: PartialEq, V: AsSlice<T>> Equiv<V> for Vec<T> {
#[inline] #[inline]
fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() } fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
} }
@ -933,11 +977,11 @@ impl<T> Vec<T> {
/// ///
/// ``` /// ```
/// let vec = vec![1i, 2, 3, 4]; /// let vec = vec![1i, 2, 3, 4];
/// assert!(vec.slice(0, 2) == [1, 2]); /// assert!(vec[0..2] == [1, 2]);
/// ``` /// ```
#[inline] #[inline]
pub fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T] { pub fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T] {
self.as_slice().slice(start, end) self[start..end]
} }
/// Returns a slice containing all but the first element of the vector. /// Returns a slice containing all but the first element of the vector.
@ -954,7 +998,7 @@ impl<T> Vec<T> {
/// ``` /// ```
#[inline] #[inline]
pub fn tail<'a>(&'a self) -> &'a [T] { pub fn tail<'a>(&'a self) -> &'a [T] {
self.as_slice().tail() self[].tail()
} }
/// Returns all but the first `n' elements of a vector. /// Returns all but the first `n' elements of a vector.
@ -973,7 +1017,7 @@ impl<T> Vec<T> {
#[inline] #[inline]
#[deprecated = "use slice_from"] #[deprecated = "use slice_from"]
pub fn tailn<'a>(&'a self, n: uint) -> &'a [T] { pub fn tailn<'a>(&'a self, n: uint) -> &'a [T] {
self.as_slice().slice_from(n) self[n..]
} }
/// Returns a reference to the last element of a vector, or `None` if it is /// Returns a reference to the last element of a vector, or `None` if it is
@ -987,7 +1031,7 @@ impl<T> Vec<T> {
/// ``` /// ```
#[inline] #[inline]
pub fn last<'a>(&'a self) -> Option<&'a T> { pub fn last<'a>(&'a self) -> Option<&'a T> {
self.as_slice().last() self[].last()
} }
/// Deprecated: use `last_mut`. /// Deprecated: use `last_mut`.
@ -1184,7 +1228,7 @@ impl<T> Vec<T> {
#[deprecated = "use slice_mut"] #[deprecated = "use slice_mut"]
pub fn mut_slice<'a>(&'a mut self, start: uint, end: uint) pub fn mut_slice<'a>(&'a mut self, start: uint, end: uint)
-> &'a mut [T] { -> &'a mut [T] {
self.slice_mut(start, end) self[mut start..end]
} }
/// Returns a mutable slice of `self` between `start` and `end`. /// Returns a mutable slice of `self` between `start` and `end`.
@ -1198,18 +1242,18 @@ impl<T> Vec<T> {
/// ///
/// ``` /// ```
/// let mut vec = vec![1i, 2, 3, 4]; /// let mut vec = vec![1i, 2, 3, 4];
/// assert!(vec.slice_mut(0, 2) == [1, 2]); /// assert!(vec[mut 0..2] == [1, 2]);
/// ``` /// ```
#[inline] #[inline]
pub fn slice_mut<'a>(&'a mut self, start: uint, end: uint) pub fn slice_mut<'a>(&'a mut self, start: uint, end: uint)
-> &'a mut [T] { -> &'a mut [T] {
self.as_mut_slice().slice_mut(start, end) self[mut start..end]
} }
/// Deprecated: use "slice_from_mut". /// Deprecated: use "slice_from_mut".
#[deprecated = "use slice_from_mut"] #[deprecated = "use slice_from_mut"]
pub fn mut_slice_from<'a>(&'a mut self, start: uint) -> &'a mut [T] { pub fn mut_slice_from<'a>(&'a mut self, start: uint) -> &'a mut [T] {
self.slice_from_mut(start) self[mut start..]
} }
/// Returns a mutable slice of `self` from `start` to the end of the `Vec`. /// Returns a mutable slice of `self` from `start` to the end of the `Vec`.
@ -1222,17 +1266,17 @@ impl<T> Vec<T> {
/// ///
/// ``` /// ```
/// let mut vec = vec![1i, 2, 3, 4]; /// let mut vec = vec![1i, 2, 3, 4];
/// assert!(vec.slice_from_mut(2) == [3, 4]); /// assert!(vec[mut 2..] == [3, 4]);
/// ``` /// ```
#[inline] #[inline]
pub fn slice_from_mut<'a>(&'a mut self, start: uint) -> &'a mut [T] { pub fn slice_from_mut<'a>(&'a mut self, start: uint) -> &'a mut [T] {
self.as_mut_slice().slice_from_mut(start) self[mut start..]
} }
/// Deprecated: use `slice_to_mut`. /// Deprecated: use `slice_to_mut`.
#[deprecated = "use slice_to_mut"] #[deprecated = "use slice_to_mut"]
pub fn mut_slice_to<'a>(&'a mut self, end: uint) -> &'a mut [T] { pub fn mut_slice_to<'a>(&'a mut self, end: uint) -> &'a mut [T] {
self.slice_to_mut(end) self[mut ..end]
} }
/// Returns a mutable slice of `self` from the start of the `Vec` to `end`. /// Returns a mutable slice of `self` from the start of the `Vec` to `end`.
@ -1245,11 +1289,11 @@ impl<T> Vec<T> {
/// ///
/// ``` /// ```
/// let mut vec = vec![1i, 2, 3, 4]; /// let mut vec = vec![1i, 2, 3, 4];
/// assert!(vec.slice_to_mut(2) == [1, 2]); /// assert!(vec[mut ..2] == [1, 2]);
/// ``` /// ```
#[inline] #[inline]
pub fn slice_to_mut<'a>(&'a mut self, end: uint) -> &'a mut [T] { pub fn slice_to_mut<'a>(&'a mut self, end: uint) -> &'a mut [T] {
self.as_mut_slice().slice_to_mut(end) self[mut ..end]
} }
/// Deprecated: use `split_at_mut`. /// Deprecated: use `split_at_mut`.
@ -1294,7 +1338,7 @@ impl<T> Vec<T> {
/// ``` /// ```
#[inline] #[inline]
pub fn split_at_mut<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) { pub fn split_at_mut<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
self.as_mut_slice().split_at_mut(mid) self[mut].split_at_mut(mid)
} }
/// Reverses the order of elements in a vector, in place. /// Reverses the order of elements in a vector, in place.
@ -1308,7 +1352,7 @@ impl<T> Vec<T> {
/// ``` /// ```
#[inline] #[inline]
pub fn reverse(&mut self) { pub fn reverse(&mut self) {
self.as_mut_slice().reverse() self[mut].reverse()
} }
/// Returns a slice of `self` from `start` to the end of the vec. /// Returns a slice of `self` from `start` to the end of the vec.
@ -1321,11 +1365,11 @@ impl<T> Vec<T> {
/// ///
/// ``` /// ```
/// let vec = vec![1i, 2, 3]; /// let vec = vec![1i, 2, 3];
/// assert!(vec.slice_from(1) == [2, 3]); /// assert!(vec[1..] == [2, 3]);
/// ``` /// ```
#[inline] #[inline]
pub fn slice_from<'a>(&'a self, start: uint) -> &'a [T] { pub fn slice_from<'a>(&'a self, start: uint) -> &'a [T] {
self.as_slice().slice_from(start) self[start..]
} }
/// Returns a slice of self from the start of the vec to `end`. /// Returns a slice of self from the start of the vec to `end`.
@ -1338,11 +1382,11 @@ impl<T> Vec<T> {
/// ///
/// ``` /// ```
/// let vec = vec![1i, 2, 3, 4]; /// let vec = vec![1i, 2, 3, 4];
/// assert!(vec.slice_to(2) == [1, 2]); /// assert!(vec[..2] == [1, 2]);
/// ``` /// ```
#[inline] #[inline]
pub fn slice_to<'a>(&'a self, end: uint) -> &'a [T] { pub fn slice_to<'a>(&'a self, end: uint) -> &'a [T] {
self.as_slice().slice_to(end) self[..end]
} }
/// Returns a slice containing all but the last element of the vector. /// Returns a slice containing all but the last element of the vector.
@ -1359,7 +1403,7 @@ impl<T> Vec<T> {
/// ``` /// ```
#[inline] #[inline]
pub fn init<'a>(&'a self) -> &'a [T] { pub fn init<'a>(&'a self) -> &'a [T] {
self.slice(0, self.len() - 1) self[0..self.len() - 1]
} }
@ -1605,7 +1649,7 @@ impl<T: PartialEq> Vec<T> {
} }
} }
impl<T> Slice<T> for Vec<T> { impl<T> AsSlice<T> for Vec<T> {
/// Returns a slice into `self`. /// Returns a slice into `self`.
/// ///
/// # Example /// # Example
@ -1623,7 +1667,7 @@ impl<T> Slice<T> for Vec<T> {
} }
} }
impl<T: Clone, V: Slice<T>> Add<V, Vec<T>> for Vec<T> { impl<T: Clone, V: AsSlice<T>> Add<V, Vec<T>> for Vec<T> {
#[inline] #[inline]
fn add(&self, rhs: &V) -> Vec<T> { fn add(&self, rhs: &V) -> Vec<T> {
let mut res = Vec::with_capacity(self.len() + rhs.as_slice().len()); let mut res = Vec::with_capacity(self.len() + rhs.as_slice().len());
@ -2244,12 +2288,18 @@ mod tests {
let mut values = Vec::from_slice([1u8,2,3,4,5]); let mut values = Vec::from_slice([1u8,2,3,4,5]);
{ {
let (left, right) = values.split_at_mut(2); let (left, right) = values.split_at_mut(2);
assert!(left.slice(0, left.len()) == [1, 2]); {
let left: &[_] = left;
assert!(left[0..left.len()] == [1, 2]);
}
for p in left.iter_mut() { for p in left.iter_mut() {
*p += 1; *p += 1;
} }
assert!(right.slice(0, right.len()) == [3, 4, 5]); {
let right: &[_] = right;
assert!(right[0..right.len()] == [3, 4, 5]);
}
for p in right.iter_mut() { for p in right.iter_mut() {
*p += 2; *p += 2;
} }

View file

@ -17,7 +17,7 @@ use iter::{range, DoubleEndedIterator};
use num::{Float, FPNaN, FPInfinite, ToPrimitive, Primitive}; use num::{Float, FPNaN, FPInfinite, ToPrimitive, Primitive};
use num::{Zero, One, cast}; use num::{Zero, One, cast};
use result::Ok; use result::Ok;
use slice::{ImmutableSlice, MutableSlice}; use slice::MutableSlice;
use slice; use slice;
use str::StrSlice; use str::StrSlice;
@ -173,7 +173,7 @@ pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
_ => () _ => ()
} }
buf.slice_to_mut(end).reverse(); buf[mut ..end].reverse();
// Remember start of the fractional digits. // Remember start of the fractional digits.
// Points one beyond end of buf if none get generated, // Points one beyond end of buf if none get generated,
@ -310,7 +310,7 @@ pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
impl<'a> fmt::FormatWriter for Filler<'a> { impl<'a> fmt::FormatWriter for Filler<'a> {
fn write(&mut self, bytes: &[u8]) -> fmt::Result { fn write(&mut self, bytes: &[u8]) -> fmt::Result {
slice::bytes::copy_memory(self.buf.slice_from_mut(*self.end), slice::bytes::copy_memory(self.buf[mut *self.end..],
bytes); bytes);
*self.end += bytes.len(); *self.end += bytes.len();
Ok(()) Ok(())
@ -328,5 +328,5 @@ pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
} }
} }
f(buf.slice_to(end)) f(buf[..end])
} }

View file

@ -22,7 +22,7 @@ use option::{Option, Some, None};
use ops::Deref; use ops::Deref;
use result::{Ok, Err}; use result::{Ok, Err};
use result; use result;
use slice::{Slice, ImmutableSlice}; use slice::{AsSlice, ImmutableSlice};
use slice; use slice;
use str::StrSlice; use str::StrSlice;
use str; use str;
@ -423,7 +423,7 @@ impl<'a> Formatter<'a> {
for c in sign.into_iter() { for c in sign.into_iter() {
let mut b = [0, ..4]; let mut b = [0, ..4];
let n = c.encode_utf8(b).unwrap_or(0); let n = c.encode_utf8(b).unwrap_or(0);
try!(f.buf.write(b.slice_to(n))); try!(f.buf.write(b[..n]));
} }
if prefixed { f.buf.write(prefix.as_bytes()) } if prefixed { f.buf.write(prefix.as_bytes()) }
else { Ok(()) } else { Ok(()) }
@ -530,13 +530,13 @@ impl<'a> Formatter<'a> {
let len = self.fill.encode_utf8(fill).unwrap_or(0); let len = self.fill.encode_utf8(fill).unwrap_or(0);
for _ in range(0, pre_pad) { for _ in range(0, pre_pad) {
try!(self.buf.write(fill.slice_to(len))); try!(self.buf.write(fill[..len]));
} }
try!(f(self)); try!(f(self));
for _ in range(0, post_pad) { for _ in range(0, post_pad) {
try!(self.buf.write(fill.slice_to(len))); try!(self.buf.write(fill[..len]));
} }
Ok(()) Ok(())
@ -611,7 +611,7 @@ impl Char for char {
let mut utf8 = [0u8, ..4]; let mut utf8 = [0u8, ..4];
let amt = self.encode_utf8(utf8).unwrap_or(0); let amt = self.encode_utf8(utf8).unwrap_or(0);
let s: &str = unsafe { mem::transmute(utf8.slice_to(amt)) }; let s: &str = unsafe { mem::transmute(utf8[..amt]) };
secret_string(&s, f) secret_string(&s, f)
} }
} }

View file

@ -18,7 +18,7 @@ use collections::Collection;
use fmt; use fmt;
use iter::DoubleEndedIterator; use iter::DoubleEndedIterator;
use num::{Int, cast, zero}; use num::{Int, cast, zero};
use slice::{ImmutableSlice, MutableSlice}; use slice::{MutableSlice};
/// A type that represents a specific radix /// A type that represents a specific radix
#[doc(hidden)] #[doc(hidden)]
@ -60,7 +60,7 @@ trait GenericRadix {
if x == zero() { break; } // No more digits left to accumulate. if x == zero() { break; } // No more digits left to accumulate.
} }
} }
f.pad_integral(is_positive, self.prefix(), buf.slice_from(curr)) f.pad_integral(is_positive, self.prefix(), buf[curr..])
} }
} }

View file

@ -57,8 +57,9 @@
html_playground_url = "http://play.rust-lang.org/")] html_playground_url = "http://play.rust-lang.org/")]
#![no_std] #![no_std]
#![allow(unknown_features)]
#![feature(globs, intrinsics, lang_items, macro_rules, phase)] #![feature(globs, intrinsics, lang_items, macro_rules, phase)]
#![feature(simd, unsafe_destructor)] #![feature(simd, unsafe_destructor, slicing_syntax)]
#![deny(missing_doc)] #![deny(missing_doc)]
mod macros; mod macros;

View file

@ -684,7 +684,7 @@ pub trait IndexMut<Index, Result> {
* A trivial implementation of `Slice`. When `Foo[..Foo]` happens, it ends up * A trivial implementation of `Slice`. When `Foo[..Foo]` happens, it ends up
* calling `slice_to`, and therefore, `main` prints `Slicing!`. * calling `slice_to`, and therefore, `main` prints `Slicing!`.
* *
* ``` * ```ignore
* struct Foo; * struct Foo;
* *
* impl ::core::ops::Slice<Foo, Foo> for Foo { * impl ::core::ops::Slice<Foo, Foo> for Foo {
@ -692,15 +692,15 @@ pub trait IndexMut<Index, Result> {
* println!("Slicing!"); * println!("Slicing!");
* self * self
* } * }
* fn slice_from_<'a>(&'a self, from: &Foo) -> &'a Foo { * fn slice_from_or_fail<'a>(&'a self, from: &Foo) -> &'a Foo {
* println!("Slicing!"); * println!("Slicing!");
* self * self
* } * }
* fn slice_to_<'a>(&'a self, to: &Foo) -> &'a Foo { * fn slice_to_or_fail<'a>(&'a self, to: &Foo) -> &'a Foo {
* println!("Slicing!"); * println!("Slicing!");
* self * self
* } * }
* fn slice_<'a>(&'a self, from: &Foo, to: &Foo) -> &'a Foo { * fn slice_or_fail<'a>(&'a self, from: &Foo, to: &Foo) -> &'a Foo {
* println!("Slicing!"); * println!("Slicing!");
* self * self
* } * }
@ -711,7 +711,22 @@ pub trait IndexMut<Index, Result> {
* } * }
* ``` * ```
*/ */
// FIXME(#17273) remove the postscript _s #[cfg(not(stage0))]
#[lang="slice"]
pub trait Slice<Idx, Sized? Result> for Sized? {
/// The method for the slicing operation foo[]
fn as_slice_<'a>(&'a self) -> &'a Result;
/// The method for the slicing operation foo[from..]
fn slice_from_or_fail<'a>(&'a self, from: &Idx) -> &'a Result;
/// The method for the slicing operation foo[..to]
fn slice_to_or_fail<'a>(&'a self, to: &Idx) -> &'a Result;
/// The method for the slicing operation foo[from..to]
fn slice_or_fail<'a>(&'a self, from: &Idx, to: &Idx) -> &'a Result;
}
#[cfg(stage0)]
/**
*
*/
#[lang="slice"] #[lang="slice"]
pub trait Slice<Idx, Sized? Result> for Sized? { pub trait Slice<Idx, Sized? Result> for Sized? {
/// The method for the slicing operation foo[] /// The method for the slicing operation foo[]
@ -734,7 +749,7 @@ pub trait Slice<Idx, Sized? Result> for Sized? {
* A trivial implementation of `SliceMut`. When `Foo[Foo..]` happens, it ends up * A trivial implementation of `SliceMut`. When `Foo[Foo..]` happens, it ends up
* calling `slice_from_mut`, and therefore, `main` prints `Slicing!`. * calling `slice_from_mut`, and therefore, `main` prints `Slicing!`.
* *
* ``` * ```ignore
* struct Foo; * struct Foo;
* *
* impl ::core::ops::SliceMut<Foo, Foo> for Foo { * impl ::core::ops::SliceMut<Foo, Foo> for Foo {
@ -742,26 +757,41 @@ pub trait Slice<Idx, Sized? Result> for Sized? {
* println!("Slicing!"); * println!("Slicing!");
* self * self
* } * }
* fn slice_from_mut_<'a>(&'a mut self, from: &Foo) -> &'a mut Foo { * fn slice_from_or_fail_mut<'a>(&'a mut self, from: &Foo) -> &'a mut Foo {
* println!("Slicing!"); * println!("Slicing!");
* self * self
* } * }
* fn slice_to_mut_<'a>(&'a mut self, to: &Foo) -> &'a mut Foo { * fn slice_to_or_fail_mut<'a>(&'a mut self, to: &Foo) -> &'a mut Foo {
* println!("Slicing!"); * println!("Slicing!");
* self * self
* } * }
* fn slice_mut_<'a>(&'a mut self, from: &Foo, to: &Foo) -> &'a mut Foo { * fn slice_or_fail_mut<'a>(&'a mut self, from: &Foo, to: &Foo) -> &'a mut Foo {
* println!("Slicing!"); * println!("Slicing!");
* self * self
* } * }
* } * }
* *
* fn main() { * pub fn main() {
* Foo[mut Foo..]; * Foo[mut Foo..];
* } * }
* ``` * ```
*/ */
// FIXME(#17273) remove the postscript _s #[cfg(not(stage0))]
#[lang="slice_mut"]
pub trait SliceMut<Idx, Sized? Result> for Sized? {
/// The method for the slicing operation foo[]
fn as_mut_slice_<'a>(&'a mut self) -> &'a mut Result;
/// The method for the slicing operation foo[from..]
fn slice_from_or_fail_mut<'a>(&'a mut self, from: &Idx) -> &'a mut Result;
/// The method for the slicing operation foo[..to]
fn slice_to_or_fail_mut<'a>(&'a mut self, to: &Idx) -> &'a mut Result;
/// The method for the slicing operation foo[from..to]
fn slice_or_fail_mut<'a>(&'a mut self, from: &Idx, to: &Idx) -> &'a mut Result;
}
#[cfg(stage0)]
/**
*
*/
#[lang="slice_mut"] #[lang="slice_mut"]
pub trait SliceMut<Idx, Sized? Result> for Sized? { pub trait SliceMut<Idx, Sized? Result> for Sized? {
/// The method for the slicing operation foo[mut] /// The method for the slicing operation foo[mut]

View file

@ -149,7 +149,7 @@ use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
use mem; use mem;
use result::{Result, Ok, Err}; use result::{Result, Ok, Err};
use slice; use slice;
use slice::Slice; use slice::AsSlice;
// Note that this is not a lang item per se, but it has a hidden dependency on // Note that this is not a lang item per se, but it has a hidden dependency on
// `Iterator`, which is one. The compiler assumes that the `next` method of // `Iterator`, which is one. The compiler assumes that the `next` method of
@ -846,7 +846,7 @@ impl<T: Default> Option<T> {
// Trait implementations // Trait implementations
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
impl<T> Slice<T> for Option<T> { impl<T> AsSlice<T> for Option<T> {
/// Convert from `Option<T>` to `&[T]` (without copying) /// Convert from `Option<T>` to `&[T]` (without copying)
#[inline] #[inline]
#[stable] #[stable]

View file

@ -35,6 +35,7 @@ pub use ops::{BitAnd, BitOr, BitXor};
pub use ops::{Drop, Deref, DerefMut}; pub use ops::{Drop, Deref, DerefMut};
pub use ops::{Shl, Shr}; pub use ops::{Shl, Shr};
pub use ops::{Index, IndexMut}; pub use ops::{Index, IndexMut};
pub use ops::{Slice, SliceMut};
pub use ops::{Fn, FnMut, FnOnce}; pub use ops::{Fn, FnMut, FnOnce};
pub use option::{Option, Some, None}; pub use option::{Option, Some, None};
pub use result::{Result, Ok, Err}; pub use result::{Result, Ok, Err};
@ -62,5 +63,4 @@ pub use tuple::{Tuple1, Tuple2, Tuple3, Tuple4};
pub use tuple::{Tuple5, Tuple6, Tuple7, Tuple8}; pub use tuple::{Tuple5, Tuple6, Tuple7, Tuple8};
pub use tuple::{Tuple9, Tuple10, Tuple11, Tuple12}; pub use tuple::{Tuple9, Tuple10, Tuple11, Tuple12};
pub use slice::{ImmutablePartialEqSlice, ImmutableOrdSlice}; pub use slice::{ImmutablePartialEqSlice, ImmutableOrdSlice};
pub use slice::{MutableSlice}; pub use slice::{AsSlice, ImmutableSlice, MutableSlice};
pub use slice::{Slice, ImmutableSlice};

View file

@ -280,7 +280,7 @@ use clone::Clone;
use cmp::PartialEq; use cmp::PartialEq;
use std::fmt::Show; use std::fmt::Show;
use slice; use slice;
use slice::Slice; use slice::AsSlice;
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize}; use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
use option::{None, Option, Some}; use option::{None, Option, Some};
@ -844,7 +844,7 @@ impl<T: Show, E> Result<T, E> {
// Trait implementations // Trait implementations
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
impl<T, E> Slice<T> for Result<T, E> { impl<T, E> AsSlice<T> for Result<T, E> {
/// Convert from `Result<T, E>` to `&[T]` (without copying) /// Convert from `Result<T, E>` to `&[T]` (without copying)
#[inline] #[inline]
#[stable] #[stable]

View file

@ -67,7 +67,7 @@ pub trait ImmutableSlice<'a, T> {
/// original slice (i.e. when `end > self.len()`) or when `start > end`. /// original slice (i.e. when `end > self.len()`) or when `start > end`.
/// ///
/// Slicing with `start` equal to `end` yields an empty slice. /// Slicing with `start` equal to `end` yields an empty slice.
#[unstable = "waiting on final error conventions"] #[unstable = "waiting on final error conventions/slicing syntax"]
fn slice(&self, start: uint, end: uint) -> &'a [T]; fn slice(&self, start: uint, end: uint) -> &'a [T];
/// Returns a subslice from `start` to the end of the slice. /// Returns a subslice from `start` to the end of the slice.
@ -75,7 +75,7 @@ pub trait ImmutableSlice<'a, T> {
/// Fails when `start` is strictly greater than the length of the original slice. /// Fails when `start` is strictly greater than the length of the original slice.
/// ///
/// Slicing from `self.len()` yields an empty slice. /// Slicing from `self.len()` yields an empty slice.
#[unstable = "waiting on final error conventions"] #[unstable = "waiting on final error conventions/slicing syntax"]
fn slice_from(&self, start: uint) -> &'a [T]; fn slice_from(&self, start: uint) -> &'a [T];
/// Returns a subslice from the start of the slice to `end`. /// Returns a subslice from the start of the slice to `end`.
@ -83,7 +83,7 @@ pub trait ImmutableSlice<'a, T> {
/// Fails when `end` is strictly greater than the length of the original slice. /// Fails when `end` is strictly greater than the length of the original slice.
/// ///
/// Slicing to `0` yields an empty slice. /// Slicing to `0` yields an empty slice.
#[unstable = "waiting on final error conventions"] #[unstable = "waiting on final error conventions/slicing syntax"]
fn slice_to(&self, end: uint) -> &'a [T]; fn slice_to(&self, end: uint) -> &'a [T];
/// Divides one slice into two at an index. /// Divides one slice into two at an index.
@ -262,7 +262,7 @@ pub trait ImmutableSlice<'a, T> {
* ```ignore * ```ignore
* if self.len() == 0 { return None } * if self.len() == 0 { return None }
* let head = &self[0]; * let head = &self[0];
* *self = self.slice_from(1); * *self = self[1..];
* Some(head) * Some(head)
* ``` * ```
* *
@ -281,7 +281,7 @@ pub trait ImmutableSlice<'a, T> {
* ```ignore * ```ignore
* if self.len() == 0 { return None; } * if self.len() == 0 { return None; }
* let tail = &self[self.len() - 1]; * let tail = &self[self.len() - 1];
* *self = self.slice_to(self.len() - 1); * *self = self[..self.len() - 1];
* Some(tail) * Some(tail)
* ``` * ```
* *
@ -299,9 +299,9 @@ impl<'a,T> ImmutableSlice<'a, T> for &'a [T] {
assert!(end <= self.len()); assert!(end <= self.len());
unsafe { unsafe {
transmute(RawSlice { transmute(RawSlice {
data: self.as_ptr().offset(start as int), data: self.as_ptr().offset(start as int),
len: (end - start) len: (end - start)
}) })
} }
} }
@ -317,7 +317,7 @@ impl<'a,T> ImmutableSlice<'a, T> for &'a [T] {
#[inline] #[inline]
fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]) { fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]) {
(self.slice(0, mid), self.slice(mid, self.len())) ((*self)[..mid], (*self)[mid..])
} }
#[inline] #[inline]
@ -386,21 +386,21 @@ impl<'a,T> ImmutableSlice<'a, T> for &'a [T] {
} }
#[inline] #[inline]
fn tail(&self) -> &'a [T] { self.slice(1, self.len()) } fn tail(&self) -> &'a [T] { (*self)[1..] }
#[inline] #[inline]
#[deprecated = "use slice_from"] #[deprecated = "use slice_from"]
fn tailn(&self, n: uint) -> &'a [T] { self.slice(n, self.len()) } fn tailn(&self, n: uint) -> &'a [T] { (*self)[n..] }
#[inline] #[inline]
fn init(&self) -> &'a [T] { fn init(&self) -> &'a [T] {
self.slice(0, self.len() - 1) (*self)[..self.len() - 1]
} }
#[inline] #[inline]
#[deprecated = "use slice_to but note the arguments are different"] #[deprecated = "use slice_to but note the arguments are different"]
fn initn(&self, n: uint) -> &'a [T] { fn initn(&self, n: uint) -> &'a [T] {
self.slice(0, self.len() - n) (*self)[..self.len() - n]
} }
#[inline] #[inline]
@ -486,6 +486,37 @@ impl<'a,T> ImmutableSlice<'a, T> for &'a [T] {
} }
} }
#[cfg(not(stage0))]
impl<T> ops::Slice<uint, [T]> for [T] {
#[inline]
fn as_slice_<'a>(&'a self) -> &'a [T] {
self
}
#[inline]
fn slice_from_or_fail<'a>(&'a self, start: &uint) -> &'a [T] {
self.slice_or_fail(start, &self.len())
}
#[inline]
fn slice_to_or_fail<'a>(&'a self, end: &uint) -> &'a [T] {
self.slice_or_fail(&0, end)
}
#[inline]
fn slice_or_fail<'a>(&'a self, start: &uint, end: &uint) -> &'a [T] {
assert!(*start <= *end);
assert!(*end <= self.len());
unsafe {
transmute(RawSlice {
data: self.as_ptr().offset(*start as int),
len: (*end - *start)
})
}
}
}
#[cfg(stage0)]
impl<T> ops::Slice<uint, [T]> for [T] { impl<T> ops::Slice<uint, [T]> for [T] {
#[inline] #[inline]
fn as_slice_<'a>(&'a self) -> &'a [T] { fn as_slice_<'a>(&'a self) -> &'a [T] {
@ -514,6 +545,36 @@ impl<T> ops::Slice<uint, [T]> for [T] {
} }
} }
#[cfg(not(stage0))]
impl<T> ops::SliceMut<uint, [T]> for [T] {
#[inline]
fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] {
self
}
#[inline]
fn slice_from_or_fail_mut<'a>(&'a mut self, start: &uint) -> &'a mut [T] {
let len = &self.len();
self.slice_or_fail_mut(start, len)
}
#[inline]
fn slice_to_or_fail_mut<'a>(&'a mut self, end: &uint) -> &'a mut [T] {
self.slice_or_fail_mut(&0, end)
}
#[inline]
fn slice_or_fail_mut<'a>(&'a mut self, start: &uint, end: &uint) -> &'a mut [T] {
assert!(*start <= *end);
assert!(*end <= self.len());
unsafe {
transmute(RawSlice {
data: self.as_ptr().offset(*start as int),
len: (*end - *start)
})
}
}
}
#[cfg(stage0)]
impl<T> ops::SliceMut<uint, [T]> for [T] { impl<T> ops::SliceMut<uint, [T]> for [T] {
#[inline] #[inline]
fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] { fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] {
@ -681,7 +742,7 @@ pub trait MutableSlice<'a, T> {
* ```ignore * ```ignore
* if self.len() == 0 { return None; } * if self.len() == 0 { return None; }
* let head = &mut self[0]; * let head = &mut self[0];
* *self = self.slice_from_mut(1); * *self = self[mut 1..];
* Some(head) * Some(head)
* ``` * ```
* *
@ -700,7 +761,7 @@ pub trait MutableSlice<'a, T> {
* ```ignore * ```ignore
* if self.len() == 0 { return None; } * if self.len() == 0 { return None; }
* let tail = &mut self[self.len() - 1]; * let tail = &mut self[self.len() - 1];
* *self = self.slice_to_mut(self.len() - 1); * *self = self[mut ..self.len() - 1];
* Some(tail) * Some(tail)
* ``` * ```
* *
@ -826,33 +887,24 @@ impl<'a,T> MutableSlice<'a, T> for &'a mut [T] {
fn as_mut_slice(self) -> &'a mut [T] { self } fn as_mut_slice(self) -> &'a mut [T] { self }
fn slice_mut(self, start: uint, end: uint) -> &'a mut [T] { fn slice_mut(self, start: uint, end: uint) -> &'a mut [T] {
assert!(start <= end); self[mut start..end]
assert!(end <= self.len());
unsafe {
transmute(RawSlice {
data: self.as_mut_ptr().offset(start as int) as *const T,
len: (end - start)
})
}
} }
#[inline] #[inline]
fn slice_from_mut(self, start: uint) -> &'a mut [T] { fn slice_from_mut(self, start: uint) -> &'a mut [T] {
let len = self.len(); self[mut start..]
self.slice_mut(start, len)
} }
#[inline] #[inline]
fn slice_to_mut(self, end: uint) -> &'a mut [T] { fn slice_to_mut(self, end: uint) -> &'a mut [T] {
self.slice_mut(0, end) self[mut ..end]
} }
#[inline] #[inline]
fn split_at_mut(self, mid: uint) -> (&'a mut [T], &'a mut [T]) { fn split_at_mut(self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
unsafe { unsafe {
let len = self.len();
let self2: &'a mut [T] = mem::transmute_copy(&self); let self2: &'a mut [T] = mem::transmute_copy(&self);
(self.slice_mut(0, mid), self2.slice_mut(mid, len)) (self[mut ..mid], self2[mut mid..])
} }
} }
@ -889,13 +941,13 @@ impl<'a,T> MutableSlice<'a, T> for &'a mut [T] {
#[inline] #[inline]
fn tail_mut(self) -> &'a mut [T] { fn tail_mut(self) -> &'a mut [T] {
let len = self.len(); let len = self.len();
self.slice_mut(1, len) self[mut 1..len]
} }
#[inline] #[inline]
fn init_mut(self) -> &'a mut [T] { fn init_mut(self) -> &'a mut [T] {
let len = self.len(); let len = self.len();
self.slice_mut(0, len - 1) self[mut 0..len - 1]
} }
#[inline] #[inline]
@ -1042,13 +1094,13 @@ impl<'a,T:PartialEq> ImmutablePartialEqSlice<T> for &'a [T] {
#[inline] #[inline]
fn starts_with(&self, needle: &[T]) -> bool { fn starts_with(&self, needle: &[T]) -> bool {
let n = needle.len(); let n = needle.len();
self.len() >= n && needle == self.slice_to(n) self.len() >= n && needle == (*self)[..n]
} }
#[inline] #[inline]
fn ends_with(&self, needle: &[T]) -> bool { fn ends_with(&self, needle: &[T]) -> bool {
let (m, n) = (self.len(), needle.len()); let (m, n) = (self.len(), needle.len());
m >= n && needle == self.slice_from(m - n) m >= n && needle == (*self)[m-n..]
} }
} }
@ -1152,13 +1204,13 @@ impl<'a, T:Clone> MutableCloneableSlice<T> for &'a mut [T] {
/// Data that is viewable as a slice. /// Data that is viewable as a slice.
#[unstable = "may merge with other traits"] #[unstable = "may merge with other traits"]
pub trait Slice<T> { pub trait AsSlice<T> {
/// Work with `self` as a slice. /// Work with `self` as a slice.
fn as_slice<'a>(&'a self) -> &'a [T]; fn as_slice<'a>(&'a self) -> &'a [T];
} }
#[unstable = "trait is unstable"] #[unstable = "trait is unstable"]
impl<'a,T> Slice<T> for &'a [T] { impl<'a,T> AsSlice<T> for &'a [T] {
#[inline(always)] #[inline(always)]
fn as_slice<'a>(&'a self) -> &'a [T] { *self } fn as_slice<'a>(&'a self) -> &'a [T] { *self }
} }
@ -1339,8 +1391,8 @@ impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
match self.v.iter().position(|x| (self.pred)(x)) { match self.v.iter().position(|x| (self.pred)(x)) {
None => self.finish(), None => self.finish(),
Some(idx) => { Some(idx) => {
let ret = Some(self.v.slice(0, idx)); let ret = Some(self.v[..idx]);
self.v = self.v.slice(idx + 1, self.v.len()); self.v = self.v[idx + 1..];
ret ret
} }
} }
@ -1365,8 +1417,8 @@ impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> {
match self.v.iter().rposition(|x| (self.pred)(x)) { match self.v.iter().rposition(|x| (self.pred)(x)) {
None => self.finish(), None => self.finish(),
Some(idx) => { Some(idx) => {
let ret = Some(self.v.slice(idx + 1, self.v.len())); let ret = Some(self.v[idx + 1..]);
self.v = self.v.slice(0, idx); self.v = self.v[..idx];
ret ret
} }
} }
@ -1416,7 +1468,7 @@ impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
Some(idx) => { Some(idx) => {
let tmp = mem::replace(&mut self.v, &mut []); let tmp = mem::replace(&mut self.v, &mut []);
let (head, tail) = tmp.split_at_mut(idx); let (head, tail) = tmp.split_at_mut(idx);
self.v = tail.slice_from_mut(1); self.v = tail[mut 1..];
Some(head) Some(head)
} }
} }
@ -1450,7 +1502,7 @@ impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
let tmp = mem::replace(&mut self.v, &mut []); let tmp = mem::replace(&mut self.v, &mut []);
let (head, tail) = tmp.split_at_mut(idx); let (head, tail) = tmp.split_at_mut(idx);
self.v = head; self.v = head;
Some(tail.slice_from_mut(1)) Some(tail[mut 1..])
} }
} }
} }
@ -1498,8 +1550,8 @@ impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
if self.size > self.v.len() { if self.size > self.v.len() {
None None
} else { } else {
let ret = Some(self.v.slice(0, self.size)); let ret = Some(self.v[..self.size]);
self.v = self.v.slice(1, self.v.len()); self.v = self.v[1..];
ret ret
} }
} }
@ -1583,7 +1635,7 @@ impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
let mut hi = lo + self.size; let mut hi = lo + self.size;
if hi < lo || hi > self.v.len() { hi = self.v.len(); } if hi < lo || hi > self.v.len() { hi = self.v.len(); }
Some(self.v.slice(lo, hi)) Some(self.v[lo..hi])
} else { } else {
None None
} }
@ -1837,7 +1889,7 @@ impl<'a,T:PartialEq> PartialEq for &'a [T] {
impl<'a,T:Eq> Eq for &'a [T] {} impl<'a,T:Eq> Eq for &'a [T] {}
#[unstable = "waiting for DST"] #[unstable = "waiting for DST"]
impl<'a,T:PartialEq, V: Slice<T>> Equiv<V> for &'a [T] { impl<'a,T:PartialEq, V: AsSlice<T>> Equiv<V> for &'a [T] {
#[inline] #[inline]
fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() } fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
} }
@ -1858,7 +1910,7 @@ impl<'a,T:PartialEq> PartialEq for &'a mut [T] {
impl<'a,T:Eq> Eq for &'a mut [T] {} impl<'a,T:Eq> Eq for &'a mut [T] {}
#[unstable = "waiting for DST"] #[unstable = "waiting for DST"]
impl<'a,T:PartialEq, V: Slice<T>> Equiv<V> for &'a mut [T] { impl<'a,T:PartialEq, V: AsSlice<T>> Equiv<V> for &'a mut [T] {
#[inline] #[inline]
fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() } fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
} }

View file

@ -30,7 +30,7 @@ use iter::range;
use num::{CheckedMul, Saturating}; use num::{CheckedMul, Saturating};
use option::{Option, None, Some}; use option::{Option, None, Some};
use raw::Repr; use raw::Repr;
use slice::{ImmutableSlice, MutableSlice}; use slice::ImmutableSlice;
use slice; use slice;
use uint; use uint;
@ -393,7 +393,7 @@ impl NaiveSearcher {
fn next(&mut self, haystack: &[u8], needle: &[u8]) -> Option<(uint, uint)> { fn next(&mut self, haystack: &[u8], needle: &[u8]) -> Option<(uint, uint)> {
while self.position + needle.len() <= haystack.len() { while self.position + needle.len() <= haystack.len() {
if haystack.slice(self.position, self.position + needle.len()) == needle { if haystack[self.position .. self.position + needle.len()] == needle {
let match_pos = self.position; let match_pos = self.position;
self.position += needle.len(); // add 1 for all matches self.position += needle.len(); // add 1 for all matches
return Some((match_pos, match_pos + needle.len())); return Some((match_pos, match_pos + needle.len()));
@ -514,10 +514,10 @@ impl TwoWaySearcher {
// //
// What's going on is we have some critical factorization (u, v) of the // What's going on is we have some critical factorization (u, v) of the
// needle, and we want to determine whether u is a suffix of // needle, and we want to determine whether u is a suffix of
// v.slice_to(period). If it is, we use "Algorithm CP1". Otherwise we use // v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
// "Algorithm CP2", which is optimized for when the period of the needle // "Algorithm CP2", which is optimized for when the period of the needle
// is large. // is large.
if needle.slice_to(crit_pos) == needle.slice(period, period + crit_pos) { if needle[..crit_pos] == needle[period.. period + crit_pos] {
TwoWaySearcher { TwoWaySearcher {
crit_pos: crit_pos, crit_pos: crit_pos,
period: period, period: period,
@ -741,7 +741,7 @@ impl<'a> Iterator<u16> for Utf16CodeUnits<'a> {
let mut buf = [0u16, ..2]; let mut buf = [0u16, ..2];
self.chars.next().map(|ch| { self.chars.next().map(|ch| {
let n = ch.encode_utf16(buf.as_mut_slice()).unwrap_or(0); let n = ch.encode_utf16(buf[mut]).unwrap_or(0);
if n == 2 { self.extra = buf[1]; } if n == 2 { self.extra = buf[1]; }
buf[0] buf[0]
}) })
@ -1007,7 +1007,7 @@ pub fn utf16_items<'a>(v: &'a [u16]) -> Utf16Items<'a> {
pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] { pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] {
match v.iter().position(|c| *c == 0) { match v.iter().position(|c| *c == 0) {
// don't include the 0 // don't include the 0
Some(i) => v.slice_to(i), Some(i) => v[..i],
None => v None => v
} }
} }
@ -1164,6 +1164,7 @@ pub mod traits {
fn equiv(&self, other: &S) -> bool { eq_slice(*self, other.as_slice()) } fn equiv(&self, other: &S) -> bool { eq_slice(*self, other.as_slice()) }
} }
#[cfg(stage0)]
impl ops::Slice<uint, str> for str { impl ops::Slice<uint, str> for str {
#[inline] #[inline]
fn as_slice_<'a>(&'a self) -> &'a str { fn as_slice_<'a>(&'a self) -> &'a str {
@ -1185,6 +1186,28 @@ pub mod traits {
self.slice(*from, *to) self.slice(*from, *to)
} }
} }
#[cfg(not(stage0))]
impl ops::Slice<uint, str> for str {
#[inline]
fn as_slice_<'a>(&'a self) -> &'a str {
self
}
#[inline]
fn slice_from_or_fail<'a>(&'a self, from: &uint) -> &'a str {
self.slice_from(*from)
}
#[inline]
fn slice_to_or_fail<'a>(&'a self, to: &uint) -> &'a str {
self.slice_to(*to)
}
#[inline]
fn slice_or_fail<'a>(&'a self, from: &uint, to: &uint) -> &'a str {
self.slice(*from, *to)
}
}
} }
/// Any string that can be represented as a slice /// Any string that can be represented as a slice
@ -1994,13 +2017,13 @@ impl<'a> StrSlice<'a> for &'a str {
#[inline] #[inline]
fn starts_with<'a>(&self, needle: &'a str) -> bool { fn starts_with<'a>(&self, needle: &'a str) -> bool {
let n = needle.len(); let n = needle.len();
self.len() >= n && needle.as_bytes() == self.as_bytes().slice_to(n) self.len() >= n && needle.as_bytes() == self.as_bytes()[..n]
} }
#[inline] #[inline]
fn ends_with(&self, needle: &str) -> bool { fn ends_with(&self, needle: &str) -> bool {
let (m, n) = (self.len(), needle.len()); let (m, n) = (self.len(), needle.len());
m >= n && needle.as_bytes() == self.as_bytes().slice_from(m - n) m >= n && needle.as_bytes() == self.as_bytes()[m-n..]
} }
#[inline] #[inline]

View file

@ -174,7 +174,7 @@ fn test_encode_utf8() {
fn check(input: char, expect: &[u8]) { fn check(input: char, expect: &[u8]) {
let mut buf = [0u8, ..4]; let mut buf = [0u8, ..4];
let n = input.encode_utf8(buf.as_mut_slice()).unwrap_or(0); let n = input.encode_utf8(buf.as_mut_slice()).unwrap_or(0);
assert_eq!(buf.slice_to(n), expect); assert_eq!(buf[..n], expect);
} }
check('x', [0x78]); check('x', [0x78]);
@ -188,7 +188,7 @@ fn test_encode_utf16() {
fn check(input: char, expect: &[u16]) { fn check(input: char, expect: &[u16]) {
let mut buf = [0u16, ..2]; let mut buf = [0u16, ..2];
let n = input.encode_utf16(buf.as_mut_slice()).unwrap_or(0); let n = input.encode_utf16(buf.as_mut_slice()).unwrap_or(0);
assert_eq!(buf.slice_to(n), expect); assert_eq!(buf[..n], expect);
} }
check('x', [0x0078]); check('x', [0x0078]);

View file

@ -13,6 +13,7 @@ use core::iter::order::*;
use core::uint; use core::uint;
use core::cmp; use core::cmp;
use core::num; use core::num;
use core::ops::Slice;
use test::Bencher; use test::Bencher;
@ -228,7 +229,7 @@ fn test_inspect() {
.collect::<Vec<uint>>(); .collect::<Vec<uint>>();
assert_eq!(n, xs.len()); assert_eq!(n, xs.len());
assert_eq!(xs.as_slice(), ys.as_slice()); assert_eq!(xs[], ys[]);
} }
#[test] #[test]
@ -268,7 +269,7 @@ fn test_cycle() {
#[test] #[test]
fn test_iterator_nth() { fn test_iterator_nth() {
let v = &[0i, 1, 2, 3, 4]; let v: &[_] = &[0i, 1, 2, 3, 4];
for i in range(0u, v.len()) { for i in range(0u, v.len()) {
assert_eq!(v.iter().nth(i).unwrap(), &v[i]); assert_eq!(v.iter().nth(i).unwrap(), &v[i]);
} }
@ -277,55 +278,55 @@ fn test_iterator_nth() {
#[test] #[test]
fn test_iterator_last() { fn test_iterator_last() {
let v = &[0i, 1, 2, 3, 4]; let v: &[_] = &[0i, 1, 2, 3, 4];
assert_eq!(v.iter().last().unwrap(), &4); assert_eq!(v.iter().last().unwrap(), &4);
assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0); assert_eq!(v[0..1].iter().last().unwrap(), &0);
} }
#[test] #[test]
fn test_iterator_len() { fn test_iterator_len() {
let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().count(), 4); assert_eq!(v[0..4].iter().count(), 4);
assert_eq!(v.slice(0, 10).iter().count(), 10); assert_eq!(v[0..10].iter().count(), 10);
assert_eq!(v.slice(0, 0).iter().count(), 0); assert_eq!(v[0..0].iter().count(), 0);
} }
#[test] #[test]
fn test_iterator_sum() { fn test_iterator_sum() {
let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).sum(), 6); assert_eq!(v[0..4].iter().map(|&x| x).sum(), 6);
assert_eq!(v.iter().map(|&x| x).sum(), 55); assert_eq!(v.iter().map(|&x| x).sum(), 55);
assert_eq!(v.slice(0, 0).iter().map(|&x| x).sum(), 0); assert_eq!(v[0..0].iter().map(|&x| x).sum(), 0);
} }
#[test] #[test]
fn test_iterator_product() { fn test_iterator_product() {
let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).product(), 0); assert_eq!(v[0..4].iter().map(|&x| x).product(), 0);
assert_eq!(v.slice(1, 5).iter().map(|&x| x).product(), 24); assert_eq!(v[1..5].iter().map(|&x| x).product(), 24);
assert_eq!(v.slice(0, 0).iter().map(|&x| x).product(), 1); assert_eq!(v[0..0].iter().map(|&x| x).product(), 1);
} }
#[test] #[test]
fn test_iterator_max() { fn test_iterator_max() {
let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).max(), Some(3)); assert_eq!(v[0..4].iter().map(|&x| x).max(), Some(3));
assert_eq!(v.iter().map(|&x| x).max(), Some(10)); assert_eq!(v.iter().map(|&x| x).max(), Some(10));
assert_eq!(v.slice(0, 0).iter().map(|&x| x).max(), None); assert_eq!(v[0..0].iter().map(|&x| x).max(), None);
} }
#[test] #[test]
fn test_iterator_min() { fn test_iterator_min() {
let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).min(), Some(0)); assert_eq!(v[0..4].iter().map(|&x| x).min(), Some(0));
assert_eq!(v.iter().map(|&x| x).min(), Some(0)); assert_eq!(v.iter().map(|&x| x).min(), Some(0));
assert_eq!(v.slice(0, 0).iter().map(|&x| x).min(), None); assert_eq!(v[0..0].iter().map(|&x| x).min(), None);
} }
#[test] #[test]
fn test_iterator_size_hint() { fn test_iterator_size_hint() {
let c = count(0i, 1); let c = count(0i, 1);
let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let v2 = &[10i, 11, 12]; let v2 = &[10i, 11, 12];
let vi = v.iter(); let vi = v.iter();
@ -372,7 +373,7 @@ fn test_all() {
assert!(v.iter().all(|&x| x < 10)); assert!(v.iter().all(|&x| x < 10));
assert!(!v.iter().all(|&x| x % 2 == 0)); assert!(!v.iter().all(|&x| x % 2 == 0));
assert!(!v.iter().all(|&x| x > 100)); assert!(!v.iter().all(|&x| x > 100));
assert!(v.slice(0, 0).iter().all(|_| fail!())); assert!(v.slice_or_fail(&0, &0).iter().all(|_| fail!()));
} }
#[test] #[test]
@ -381,7 +382,7 @@ fn test_any() {
assert!(v.iter().any(|&x| x < 10)); assert!(v.iter().any(|&x| x < 10));
assert!(v.iter().any(|&x| x % 2 == 0)); assert!(v.iter().any(|&x| x % 2 == 0));
assert!(!v.iter().any(|&x| x > 100)); assert!(!v.iter().any(|&x| x > 100));
assert!(!v.slice(0, 0).iter().any(|_| fail!())); assert!(!v.slice_or_fail(&0, &0).iter().any(|_| fail!()));
} }
#[test] #[test]
@ -565,7 +566,7 @@ fn check_randacc_iter<A: PartialEq, T: Clone + RandomAccessIterator<A>>(a: T, le
fn test_double_ended_flat_map() { fn test_double_ended_flat_map() {
let u = [0u,1]; let u = [0u,1];
let v = [5u,6,7,8]; let v = [5u,6,7,8];
let mut it = u.iter().flat_map(|x| v.slice(*x, v.len()).iter()); let mut it = u.iter().flat_map(|x| v[*x..v.len()].iter());
assert_eq!(it.next_back().unwrap(), &8); assert_eq!(it.next_back().unwrap(), &8);
assert_eq!(it.next().unwrap(), &5); assert_eq!(it.next().unwrap(), &5);
assert_eq!(it.next_back().unwrap(), &7); assert_eq!(it.next_back().unwrap(), &7);

View file

@ -7,7 +7,7 @@
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // except according to those terms.
#![feature(globs, unsafe_destructor, macro_rules)] #![feature(globs, unsafe_destructor, macro_rules, slicing_syntax)]
extern crate core; extern crate core;
extern crate test; extern crate test;

View file

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

View file

@ -1012,7 +1012,7 @@ pub fn write<T>(fd: sock_t,
// Also as with read(), we use MSG_DONTWAIT to guard ourselves // Also as with read(), we use MSG_DONTWAIT to guard ourselves
// against unforeseen circumstances. // against unforeseen circumstances.
let _guard = lock(); let _guard = lock();
let ptr = buf.slice_from(written).as_ptr(); let ptr = buf[written..].as_ptr();
let len = buf.len() - written; let len = buf.len() - written;
match retry(|| write(deadline.is_some(), ptr, len)) { match retry(|| write(deadline.is_some(), ptr, len)) {
-1 if util::wouldblock() => {} -1 if util::wouldblock() => {}

View file

@ -448,7 +448,7 @@ impl rtio::RtioPipe for UnixStream {
} }
let ret = unsafe { let ret = unsafe {
libc::WriteFile(self.handle(), libc::WriteFile(self.handle(),
buf.slice_from(offset).as_ptr() as libc::LPVOID, buf[offset..].as_ptr() as libc::LPVOID,
(buf.len() - offset) as libc::DWORD, (buf.len() - offset) as libc::DWORD,
&mut bytes_written, &mut bytes_written,
&mut overlapped) &mut overlapped)

View file

@ -57,7 +57,8 @@
#![deny(unused_result, unused_must_use)] #![deny(unused_result, unused_must_use)]
#![allow(non_camel_case_types, deprecated)] #![allow(non_camel_case_types, deprecated)]
#![feature(default_type_params, lang_items)] #![allow(unknown_features)]
#![feature(default_type_params, lang_items, slicing_syntax)]
// NB this crate explicitly does *not* allow glob imports, please seriously // NB this crate explicitly does *not* allow glob imports, please seriously
// consider whether they're needed before adding that feature here (the // consider whether they're needed before adding that feature here (the

View file

@ -738,7 +738,7 @@ impl BigUint {
let mut power: BigUint = One::one(); let mut power: BigUint = One::one();
loop { loop {
let start = cmp::max(end, unit_len) - unit_len; let start = cmp::max(end, unit_len) - unit_len;
match uint::parse_bytes(buf.slice(start, end), radix) { match uint::parse_bytes(buf[start..end], radix) {
Some(d) => { Some(d) => {
let d: Option<BigUint> = FromPrimitive::from_uint(d); let d: Option<BigUint> = FromPrimitive::from_uint(d);
match d { match d {
@ -1409,7 +1409,7 @@ impl BigInt {
sign = Minus; sign = Minus;
start = 1; start = 1;
} }
return BigUint::parse_bytes(buf.slice(start, buf.len()), radix) return BigUint::parse_bytes(buf[start..], radix)
.map(|bu| BigInt::from_biguint(sign, bu)); .map(|bu| BigInt::from_biguint(sign, bu));
} }

View file

@ -43,7 +43,8 @@
//! //!
//! [newt]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method //! [newt]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
#![feature(macro_rules)] #![allow(unknown_features)]
#![feature(macro_rules, slicing_syntax)]
#![feature(default_type_params)] #![feature(default_type_params)]
#![crate_name = "num"] #![crate_name = "num"]

View file

@ -230,7 +230,7 @@ pub trait Rng {
/// let choices = [1i, 2, 4, 8, 16, 32]; /// let choices = [1i, 2, 4, 8, 16, 32];
/// let mut rng = task_rng(); /// let mut rng = task_rng();
/// println!("{}", rng.choose(choices)); /// println!("{}", rng.choose(choices));
/// assert_eq!(rng.choose(choices.slice_to(0)), None); /// assert_eq!(rng.choose(choices[..0]), None);
/// ``` /// ```
fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> { fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
if values.is_empty() { if values.is_empty() {

View file

@ -94,7 +94,7 @@ impl Writer for SeekableMemWriter {
// there (left), and what will be appended on the end (right) // there (left), and what will be appended on the end (right)
let cap = self.buf.len() - self.pos; let cap = self.buf.len() - self.pos;
let (left, right) = if cap <= buf.len() { let (left, right) = if cap <= buf.len() {
(buf.slice_to(cap), buf.slice_from(cap)) (buf[..cap], buf[cap..])
} else { } else {
let result: (_, &[_]) = (buf, &[]); let result: (_, &[_]) = (buf, &[]);
result result
@ -102,7 +102,7 @@ impl Writer for SeekableMemWriter {
// Do the necessary writes // Do the necessary writes
if left.len() > 0 { if left.len() > 0 {
slice::bytes::copy_memory(self.buf.slice_from_mut(self.pos), left); slice::bytes::copy_memory(self.buf[mut self.pos..], left);
} }
if right.len() > 0 { if right.len() > 0 {
self.buf.push_all(right); self.buf.push_all(right);

View file

@ -24,7 +24,8 @@
html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/", html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")] html_playground_url = "http://play.rust-lang.org/")]
#![feature(macro_rules, phase)] #![allow(unknown_features)]
#![feature(macro_rules, phase, slicing_syntax)]
#![allow(missing_doc)] #![allow(missing_doc)]
extern crate serialize; extern crate serialize;
@ -54,7 +55,7 @@ impl<'doc> Doc<'doc> {
} }
pub fn as_str_slice<'a>(&'a self) -> &'a str { pub fn as_str_slice<'a>(&'a self) -> &'a str {
str::from_utf8(self.data.slice(self.start, self.end)).unwrap() str::from_utf8(self.data[self.start..self.end]).unwrap()
} }
pub fn as_str(&self) -> String { pub fn as_str(&self) -> String {
@ -280,7 +281,7 @@ pub mod reader {
} }
pub fn with_doc_data<'a, T>(d: Doc<'a>, f: |x: &'a [u8]| -> T) -> T { pub fn with_doc_data<'a, T>(d: Doc<'a>, f: |x: &'a [u8]| -> T) -> T {
f(d.data.slice(d.start, d.end)) f(d.data[d.start..d.end])
} }

View file

@ -102,7 +102,7 @@ impl Program {
// This is a bit hacky since we have to skip over the initial // This is a bit hacky since we have to skip over the initial
// 'Save' instruction. // 'Save' instruction.
let mut pre = String::with_capacity(5); let mut pre = String::with_capacity(5);
for inst in c.insts.slice_from(1).iter() { for inst in c.insts[1..].iter() {
match *inst { match *inst {
OneChar(c, FLAG_EMPTY) => pre.push(c), OneChar(c, FLAG_EMPTY) => pre.push(c),
_ => break _ => break

View file

@ -368,7 +368,8 @@
html_root_url = "http://doc.rust-lang.org/master/", html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")] html_playground_url = "http://play.rust-lang.org/")]
#![feature(macro_rules, phase)] #![allow(unknown_features)]
#![feature(macro_rules, phase, slicing_syntax)]
#![deny(missing_doc)] #![deny(missing_doc)]
#[cfg(test)] #[cfg(test)]

View file

@ -511,7 +511,7 @@ impl<'a> Parser<'a> {
self.chari = closer; self.chari = closer;
let greed = try!(self.get_next_greedy()); let greed = try!(self.get_next_greedy());
let inner = String::from_chars( let inner = String::from_chars(
self.chars.as_slice().slice(start + 1, closer)); self.chars[start+1..closer]);
// Parse the min and max values from the regex. // Parse the min and max values from the regex.
let (mut min, mut max): (uint, Option<uint>); let (mut min, mut max): (uint, Option<uint>);
@ -944,7 +944,7 @@ impl<'a> Parser<'a> {
} }
fn slice(&self, start: uint, end: uint) -> String { fn slice(&self, start: uint, end: uint) -> String {
String::from_chars(self.chars.as_slice().slice(start, end)) String::from_chars(self.chars[start..end])
} }
} }

View file

@ -130,7 +130,7 @@ macro_rules! mat(
// actual capture groups to match test set. // actual capture groups to match test set.
let (sexpect, mut sgot) = (expected.as_slice(), got.as_slice()); let (sexpect, mut sgot) = (expected.as_slice(), got.as_slice());
if sgot.len() > sexpect.len() { if sgot.len() > sexpect.len() {
sgot = sgot.slice(0, sexpect.len()) sgot = sgot[0..sexpect.len()]
} }
if sexpect != sgot { if sexpect != sgot {
fail!("For RE '{}' against '{}', expected '{}' but got '{}'", fail!("For RE '{}' against '{}', expected '{}' but got '{}'",

View file

@ -145,7 +145,7 @@ impl<'r, 't> Nfa<'r, 't> {
// out early. // out early.
if self.prog.prefix.len() > 0 && clist.size == 0 { if self.prog.prefix.len() > 0 && clist.size == 0 {
let needle = self.prog.prefix.as_slice().as_bytes(); let needle = self.prog.prefix.as_slice().as_bytes();
let haystack = self.input.as_bytes().slice_from(self.ic); let haystack = self.input.as_bytes()[self.ic..];
match find_prefix(needle, haystack) { match find_prefix(needle, haystack) {
None => break, None => break,
Some(i) => { Some(i) => {

View file

@ -550,7 +550,7 @@ fn exec<'t>(which: ::regex::native::MatchKind, input: &'t str,
} else { } else {
quote_expr!(self.cx, quote_expr!(self.cx,
if clist.size == 0 { if clist.size == 0 {
let haystack = self.input.as_bytes().slice_from(self.ic); let haystack = self.input.as_bytes()[self.ic..];
match find_prefix(prefix_bytes, haystack) { match find_prefix(prefix_bytes, haystack) {
None => break, None => break,
Some(i) => { Some(i) => {

View file

@ -89,9 +89,9 @@ pub fn run(sess: &session::Session, llmod: ModuleRef,
if version == 1 { if version == 1 {
// The only version existing so far // The only version existing so far
let data_size = extract_compressed_bytecode_size_v1(bc_encoded); let data_size = extract_compressed_bytecode_size_v1(bc_encoded);
let compressed_data = bc_encoded.slice( let compressed_data = bc_encoded[
link::RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET, link::RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET..
link::RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET + data_size as uint); link::RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET + data_size as uint];
match flate::inflate_bytes(compressed_data) { match flate::inflate_bytes(compressed_data) {
Some(inflated) => inflated, Some(inflated) => inflated,
@ -188,7 +188,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef,
fn is_versioned_bytecode_format(bc: &[u8]) -> bool { fn is_versioned_bytecode_format(bc: &[u8]) -> bool {
let magic_id_byte_count = link::RLIB_BYTECODE_OBJECT_MAGIC.len(); let magic_id_byte_count = link::RLIB_BYTECODE_OBJECT_MAGIC.len();
return bc.len() > magic_id_byte_count && return bc.len() > magic_id_byte_count &&
bc.slice(0, magic_id_byte_count) == link::RLIB_BYTECODE_OBJECT_MAGIC; bc[..magic_id_byte_count] == link::RLIB_BYTECODE_OBJECT_MAGIC;
} }
fn extract_bytecode_format_version(bc: &[u8]) -> u32 { fn extract_bytecode_format_version(bc: &[u8]) -> u32 {
@ -200,8 +200,8 @@ fn extract_compressed_bytecode_size_v1(bc: &[u8]) -> u64 {
} }
fn read_from_le_bytes<T: Int>(bytes: &[u8], position_in_bytes: uint) -> T { fn read_from_le_bytes<T: Int>(bytes: &[u8], position_in_bytes: uint) -> T {
let byte_data = bytes.slice(position_in_bytes, let byte_data = bytes[position_in_bytes..
position_in_bytes + mem::size_of::<T>()); position_in_bytes + mem::size_of::<T>()];
let data = unsafe { let data = unsafe {
*(byte_data.as_ptr() as *const T) *(byte_data.as_ptr() as *const T)
}; };

View file

@ -29,8 +29,9 @@ This API is completely unstable and subject to change.
html_root_url = "http://doc.rust-lang.org/master/")] html_root_url = "http://doc.rust-lang.org/master/")]
#![allow(deprecated)] #![allow(deprecated)]
#![allow(unknown_features)]
#![feature(macro_rules, globs, struct_variant, quote)] #![feature(macro_rules, globs, struct_variant, quote)]
#![feature(default_type_params, phase, unsafe_destructor)] #![feature(default_type_params, phase, unsafe_destructor, slicing_syntax)]
#![feature(rustc_diagnostic_macros)] #![feature(rustc_diagnostic_macros)]
#![feature(import_shadowing)] #![feature(import_shadowing)]

View file

@ -70,7 +70,7 @@ fn lookup_hash<'a>(d: rbml::Doc<'a>, eq_fn: |&[u8]| -> bool,
let mut ret = None; let mut ret = None;
reader::tagged_docs(tagged_doc.doc, belt, |elt| { reader::tagged_docs(tagged_doc.doc, belt, |elt| {
let pos = u64_from_be_bytes(elt.data, elt.start, 4) as uint; let pos = u64_from_be_bytes(elt.data, elt.start, 4) as uint;
if eq_fn(elt.data.slice(elt.start + 4, elt.end)) { if eq_fn(elt.data[elt.start + 4 .. elt.end]) {
ret = Some(reader::doc_at(d.data, pos).unwrap().doc); ret = Some(reader::doc_at(d.data, pos).unwrap().doc);
false false
} else { } else {
@ -84,7 +84,7 @@ pub fn maybe_find_item<'a>(item_id: ast::NodeId,
items: rbml::Doc<'a>) -> Option<rbml::Doc<'a>> { items: rbml::Doc<'a>) -> Option<rbml::Doc<'a>> {
fn eq_item(bytes: &[u8], item_id: ast::NodeId) -> bool { fn eq_item(bytes: &[u8], item_id: ast::NodeId) -> bool {
return u64_from_be_bytes( return u64_from_be_bytes(
bytes.slice(0u, 4u), 0u, 4u) as ast::NodeId bytes[0u..4u], 0u, 4u) as ast::NodeId
== item_id; == item_id;
} }
lookup_hash(items, lookup_hash(items,

View file

@ -91,7 +91,7 @@ fn scan<R>(st: &mut PState, is_last: |char| -> bool, op: |&[u8]| -> R) -> R {
} }
let end_pos = st.pos; let end_pos = st.pos;
st.pos += 1; st.pos += 1;
return op(st.data.slice(start_pos, end_pos)); return op(st.data[start_pos..end_pos]);
} }
pub fn parse_ident(st: &mut PState, last: char) -> ast::Ident { pub fn parse_ident(st: &mut PState, last: char) -> ast::Ident {
@ -598,8 +598,8 @@ pub fn parse_def_id(buf: &[u8]) -> ast::DefId {
fail!(); fail!();
} }
let crate_part = buf.slice(0u, colon_idx); let crate_part = buf[0u..colon_idx];
let def_part = buf.slice(colon_idx + 1u, len); let def_part = buf[colon_idx + 1u..len];
let crate_num = match uint::parse_bytes(crate_part, 10u) { let crate_num = match uint::parse_bytes(crate_part, 10u) {
Some(cn) => cn as ast::CrateNum, Some(cn) => cn as ast::CrateNum,

View file

@ -865,7 +865,7 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
None None
} }
}; };
head.map(|head| head.append(r.slice_to(col)).append(r.slice_from(col + 1))) head.map(|head| head.append(r[..col]).append(r[col + 1..]))
} }
fn check_local(cx: &mut MatchCheckCtxt, loc: &Local) { fn check_local(cx: &mut MatchCheckCtxt, loc: &Local) {

View file

@ -4019,7 +4019,7 @@ impl<'a> Resolver<'a> {
for (i, rib) in ribs.iter().enumerate().rev() { for (i, rib) in ribs.iter().enumerate().rev() {
match rib.bindings.find_copy(&name) { match rib.bindings.find_copy(&name) {
Some(def_like) => { Some(def_like) => {
return self.upvarify(ribs.slice_from(i + 1), def_like, span); return self.upvarify(ribs[i + 1..], def_like, span);
} }
None => { None => {
// Continue. // Continue.

View file

@ -193,7 +193,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
if len <= 2 { if len <= 2 {
return; return;
} }
let sub_paths = sub_paths.slice(0, len-2); let sub_paths = sub_paths[..len-2];
for &(ref span, ref qualname) in sub_paths.iter() { for &(ref span, ref qualname) in sub_paths.iter() {
self.fmt.sub_mod_ref_str(path.span, self.fmt.sub_mod_ref_str(path.span,
*span, *span,

View file

@ -473,7 +473,7 @@ fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
// Collect all of the matches that can match against anything. // Collect all of the matches that can match against anything.
enter_match(bcx, dm, m, col, val, |pats| { enter_match(bcx, dm, m, col, val, |pats| {
if pat_is_binding_or_wild(dm, &*pats[col]) { if pat_is_binding_or_wild(dm, &*pats[col]) {
Some(Vec::from_slice(pats.slice_to(col)).append(pats.slice_from(col + 1))) Some(Vec::from_slice(pats[..col]).append(pats[col + 1..]))
} else { } else {
None None
} }
@ -948,7 +948,7 @@ fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
bcx = compile_guard(bcx, bcx = compile_guard(bcx,
&**guard_expr, &**guard_expr,
m[0].data, m[0].data,
m.slice(1, m.len()), m[1..m.len()],
vals, vals,
chk, chk,
has_genuine_default); has_genuine_default);
@ -987,7 +987,7 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
let tcx = bcx.tcx(); let tcx = bcx.tcx();
let dm = &tcx.def_map; let dm = &tcx.def_map;
let vals_left = Vec::from_slice(vals.slice(0u, col)).append(vals.slice(col + 1u, vals.len())); let vals_left = Vec::from_slice(vals[0u..col]).append(vals[col + 1u..vals.len()]);
let ccx = bcx.fcx.ccx; let ccx = bcx.fcx.ccx;
// Find a real id (we're adding placeholder wildcard patterns, but // Find a real id (we're adding placeholder wildcard patterns, but

View file

@ -550,7 +550,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
for (small_vec_e, &ix) in small_vec.iter_mut().zip(ixs.iter()) { for (small_vec_e, &ix) in small_vec.iter_mut().zip(ixs.iter()) {
*small_vec_e = C_i32(self.ccx, ix as i32); *small_vec_e = C_i32(self.ccx, ix as i32);
} }
self.inbounds_gep(base, small_vec.slice(0, ixs.len())) self.inbounds_gep(base, small_vec[..ixs.len()])
} else { } else {
let v = ixs.iter().map(|i| C_i32(self.ccx, *i as i32)).collect::<Vec<ValueRef>>(); let v = ixs.iter().map(|i| C_i32(self.ccx, *i as i32)).collect::<Vec<ValueRef>>();
self.count_insn("gepi"); self.count_insn("gepi");

View file

@ -937,7 +937,7 @@ pub fn create_captured_var_metadata(bcx: Block,
let variable_access = IndirectVariable { let variable_access = IndirectVariable {
alloca: env_pointer, alloca: env_pointer,
address_operations: address_operations.slice_to(address_op_count) address_operations: address_operations[..address_op_count]
}; };
declare_local(bcx, declare_local(bcx,

View file

@ -330,7 +330,7 @@ fn ast_path_substs<'tcx,AC,RS>(
} }
} }
for param in ty_param_defs.slice_from(supplied_ty_param_count).iter() { for param in ty_param_defs[supplied_ty_param_count..].iter() {
match param.default { match param.default {
Some(default) => { Some(default) => {
// This is a default type parameter. // This is a default type parameter.

View file

@ -2272,9 +2272,9 @@ fn try_overloaded_slice(fcx: &FnCtxt,
match fcx.tcx().lang_items.slice_mut_trait() { match fcx.tcx().lang_items.slice_mut_trait() {
Some(trait_did) => { Some(trait_did) => {
let method_name = match (start_expr, end_expr) { let method_name = match (start_expr, end_expr) {
(&Some(_), &Some(_)) => "slice_mut_", (&Some(_), &Some(_)) => "slice_or_fail_mut",
(&Some(_), &None) => "slice_from_mut_", (&Some(_), &None) => "slice_from_or_fail_mut",
(&None, &Some(_)) => "slice_to_mut_", (&None, &Some(_)) => "slice_to_or_fail_mut",
(&None, &None) => "as_mut_slice_", (&None, &None) => "as_mut_slice_",
}; };
@ -2297,9 +2297,9 @@ fn try_overloaded_slice(fcx: &FnCtxt,
match fcx.tcx().lang_items.slice_trait() { match fcx.tcx().lang_items.slice_trait() {
Some(trait_did) => { Some(trait_did) => {
let method_name = match (start_expr, end_expr) { let method_name = match (start_expr, end_expr) {
(&Some(_), &Some(_)) => "slice_", (&Some(_), &Some(_)) => "slice_or_fail",
(&Some(_), &None) => "slice_from_", (&Some(_), &None) => "slice_from_or_fail",
(&None, &Some(_)) => "slice_to_", (&None, &Some(_)) => "slice_to_or_fail",
(&None, &None) => "as_slice_", (&None, &None) => "as_slice_",
}; };
@ -3033,7 +3033,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
}; };
// Call the generic checker. // Call the generic checker.
let args: Vec<_> = args.slice_from(1).iter().map(|x| x).collect(); let args: Vec<_> = args[1..].iter().map(|x| x).collect();
let ret_ty = check_method_argument_types(fcx, let ret_ty = check_method_argument_types(fcx,
method_name.span, method_name.span,
fn_ty, fn_ty,

View file

@ -489,7 +489,7 @@ pub fn parameterized(cx: &ctxt,
0 0
}; };
for t in tps.slice_to(tps.len() - num_defaults).iter() { for t in tps[..tps.len() - num_defaults].iter() {
strs.push(ty_to_string(cx, *t)) strs.push(ty_to_string(cx, *t))
} }

View file

@ -31,7 +31,8 @@
html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/")] html_root_url = "http://doc.rust-lang.org/")]
#![feature(globs, phase, macro_rules)] #![allow(unknown_features)]
#![feature(globs, phase, macro_rules, slicing_syntax)]
#[phase(plugin, link)] #[phase(plugin, link)]
extern crate log; extern crate log;

View file

@ -136,14 +136,14 @@ impl FixedBuffer for FixedBuffer64 {
let buffer_remaining = size - self.buffer_idx; let buffer_remaining = size - self.buffer_idx;
if input.len() >= buffer_remaining { if input.len() >= buffer_remaining {
copy_memory( copy_memory(
self.buffer.slice_mut(self.buffer_idx, size), self.buffer[mut self.buffer_idx..size],
input.slice_to(buffer_remaining)); input[..buffer_remaining]);
self.buffer_idx = 0; self.buffer_idx = 0;
func(self.buffer); func(self.buffer);
i += buffer_remaining; i += buffer_remaining;
} else { } else {
copy_memory( copy_memory(
self.buffer.slice_mut(self.buffer_idx, self.buffer_idx + input.len()), self.buffer[mut self.buffer_idx..self.buffer_idx + input.len()],
input); input);
self.buffer_idx += input.len(); self.buffer_idx += input.len();
return; return;
@ -153,7 +153,7 @@ impl FixedBuffer for FixedBuffer64 {
// While we have at least a full buffer size chunk's worth of data, process that data // While we have at least a full buffer size chunk's worth of data, process that data
// without copying it into the buffer // without copying it into the buffer
while input.len() - i >= size { while input.len() - i >= size {
func(input.slice(i, i + size)); func(input[i..i + size]);
i += size; i += size;
} }
@ -162,8 +162,8 @@ impl FixedBuffer for FixedBuffer64 {
// be empty. // be empty.
let input_remaining = input.len() - i; let input_remaining = input.len() - i;
copy_memory( copy_memory(
self.buffer.slice_mut(0, input_remaining), self.buffer[mut ..input_remaining],
input.slice_from(i)); input[i..]);
self.buffer_idx += input_remaining; self.buffer_idx += input_remaining;
} }
@ -173,19 +173,19 @@ impl FixedBuffer for FixedBuffer64 {
fn zero_until(&mut self, idx: uint) { fn zero_until(&mut self, idx: uint) {
assert!(idx >= self.buffer_idx); assert!(idx >= self.buffer_idx);
self.buffer.slice_mut(self.buffer_idx, idx).set_memory(0); self.buffer[mut self.buffer_idx..idx].set_memory(0);
self.buffer_idx = idx; self.buffer_idx = idx;
} }
fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] { fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] {
self.buffer_idx += len; self.buffer_idx += len;
return self.buffer.slice_mut(self.buffer_idx - len, self.buffer_idx); return self.buffer[mut self.buffer_idx - len..self.buffer_idx];
} }
fn full_buffer<'s>(&'s mut self) -> &'s [u8] { fn full_buffer<'s>(&'s mut self) -> &'s [u8] {
assert!(self.buffer_idx == 64); assert!(self.buffer_idx == 64);
self.buffer_idx = 0; self.buffer_idx = 0;
return self.buffer.slice_to(64); return self.buffer[..64];
} }
fn position(&self) -> uint { self.buffer_idx } fn position(&self) -> uint { self.buffer_idx }
@ -359,7 +359,7 @@ impl Engine256State {
) )
) )
read_u32v_be(w.slice_mut(0, 16), data); read_u32v_be(w[mut 0..16], data);
// Putting the message schedule inside the same loop as the round calculations allows for // Putting the message schedule inside the same loop as the round calculations allows for
// the compiler to generate better code. // the compiler to generate better code.
@ -495,14 +495,14 @@ impl Digest for Sha256 {
fn result(&mut self, out: &mut [u8]) { fn result(&mut self, out: &mut [u8]) {
self.engine.finish(); self.engine.finish();
write_u32_be(out.slice_mut(0, 4), self.engine.state.h0); write_u32_be(out[mut 0..4], self.engine.state.h0);
write_u32_be(out.slice_mut(4, 8), self.engine.state.h1); write_u32_be(out[mut 4..8], self.engine.state.h1);
write_u32_be(out.slice_mut(8, 12), self.engine.state.h2); write_u32_be(out[mut 8..12], self.engine.state.h2);
write_u32_be(out.slice_mut(12, 16), self.engine.state.h3); write_u32_be(out[mut 12..16], self.engine.state.h3);
write_u32_be(out.slice_mut(16, 20), self.engine.state.h4); write_u32_be(out[mut 16..20], self.engine.state.h4);
write_u32_be(out.slice_mut(20, 24), self.engine.state.h5); write_u32_be(out[mut 20..24], self.engine.state.h5);
write_u32_be(out.slice_mut(24, 28), self.engine.state.h6); write_u32_be(out[mut 24..28], self.engine.state.h6);
write_u32_be(out.slice_mut(28, 32), self.engine.state.h7); write_u32_be(out[mut 28..32], self.engine.state.h7);
} }
fn reset(&mut self) { fn reset(&mut self) {

View file

@ -720,7 +720,7 @@ impl Clean<Item> for ast::Method {
let all_inputs = &self.pe_fn_decl().inputs; let all_inputs = &self.pe_fn_decl().inputs;
let inputs = match self.pe_explicit_self().node { let inputs = match self.pe_explicit_self().node {
ast::SelfStatic => all_inputs.as_slice(), ast::SelfStatic => all_inputs.as_slice(),
_ => all_inputs.slice_from(1) _ => all_inputs[1..]
}; };
let decl = FnDecl { let decl = FnDecl {
inputs: Arguments { inputs: Arguments {
@ -759,7 +759,7 @@ impl Clean<Item> for ast::TypeMethod {
fn clean(&self, cx: &DocContext) -> Item { fn clean(&self, cx: &DocContext) -> Item {
let inputs = match self.explicit_self.node { let inputs = match self.explicit_self.node {
ast::SelfStatic => self.decl.inputs.as_slice(), ast::SelfStatic => self.decl.inputs.as_slice(),
_ => self.decl.inputs.slice_from(1) _ => self.decl.inputs[1..]
}; };
let decl = FnDecl { let decl = FnDecl {
inputs: Arguments { inputs: Arguments {
@ -1031,7 +1031,7 @@ impl Clean<Item> for ty::Method {
self.fty.sig.clone()), self.fty.sig.clone()),
s => { s => {
let sig = ty::FnSig { let sig = ty::FnSig {
inputs: self.fty.sig.inputs.slice_from(1).to_vec(), inputs: self.fty.sig.inputs[1..].to_vec(),
..self.fty.sig.clone() ..self.fty.sig.clone()
}; };
let s = match s { let s = match s {

View file

@ -252,7 +252,7 @@ fn path(w: &mut fmt::Formatter, path: &clean::Path, print_all: bool,
match rel_root { match rel_root {
Some(root) => { Some(root) => {
let mut root = String::from_str(root.as_slice()); let mut root = String::from_str(root.as_slice());
for seg in path.segments.slice_to(amt).iter() { for seg in path.segments[..amt].iter() {
if "super" == seg.name.as_slice() || if "super" == seg.name.as_slice() ||
"self" == seg.name.as_slice() { "self" == seg.name.as_slice() {
try!(write!(w, "{}::", seg.name)); try!(write!(w, "{}::", seg.name));
@ -267,7 +267,7 @@ fn path(w: &mut fmt::Formatter, path: &clean::Path, print_all: bool,
} }
} }
None => { None => {
for seg in path.segments.slice_to(amt).iter() { for seg in path.segments[..amt].iter() {
try!(write!(w, "{}::", seg.name)); try!(write!(w, "{}::", seg.name));
} }
} }
@ -278,7 +278,7 @@ fn path(w: &mut fmt::Formatter, path: &clean::Path, print_all: bool,
// This is a documented path, link to it! // This is a documented path, link to it!
Some((ref fqp, shortty)) if abs_root.is_some() => { Some((ref fqp, shortty)) if abs_root.is_some() => {
let mut url = String::from_str(abs_root.unwrap().as_slice()); let mut url = String::from_str(abs_root.unwrap().as_slice());
let to_link = fqp.slice_to(fqp.len() - 1); let to_link = fqp[..fqp.len() - 1];
for component in to_link.iter() { for component in to_link.iter() {
url.push_str(component.as_slice()); url.push_str(component.as_slice());
url.push_str("/"); url.push_str("/");

View file

@ -394,7 +394,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult<String>
search_index.push(IndexItem { search_index.push(IndexItem {
ty: shortty(item), ty: shortty(item),
name: item.name.clone().unwrap(), name: item.name.clone().unwrap(),
path: fqp.slice_to(fqp.len() - 1).connect("::"), path: fqp[..fqp.len() - 1].connect("::"),
desc: shorter(item.doc_value()).to_string(), desc: shorter(item.doc_value()).to_string(),
parent: Some(did), parent: Some(did),
}); });
@ -549,7 +549,7 @@ fn write_shared(cx: &Context,
}; };
let mut mydst = dst.clone(); let mut mydst = dst.clone();
for part in remote_path.slice_to(remote_path.len() - 1).iter() { for part in remote_path[..remote_path.len() - 1].iter() {
mydst.push(part.as_slice()); mydst.push(part.as_slice());
try!(mkdir(&mydst)); try!(mkdir(&mydst));
} }
@ -829,7 +829,7 @@ impl DocFolder for Cache {
clean::StructFieldItem(..) | clean::StructFieldItem(..) |
clean::VariantItem(..) => { clean::VariantItem(..) => {
((Some(*self.parent_stack.last().unwrap()), ((Some(*self.parent_stack.last().unwrap()),
Some(self.stack.slice_to(self.stack.len() - 1))), Some(self.stack[..self.stack.len() - 1])),
false) false)
} }
clean::MethodItem(..) => { clean::MethodItem(..) => {
@ -840,13 +840,13 @@ impl DocFolder for Cache {
let did = *last; let did = *last;
let path = match self.paths.find(&did) { let path = match self.paths.find(&did) {
Some(&(_, item_type::Trait)) => Some(&(_, item_type::Trait)) =>
Some(self.stack.slice_to(self.stack.len() - 1)), Some(self.stack[..self.stack.len() - 1]),
// The current stack not necessarily has correlation for // The current stack not necessarily has correlation for
// where the type was defined. On the other hand, // where the type was defined. On the other hand,
// `paths` always has the right information if present. // `paths` always has the right information if present.
Some(&(ref fqp, item_type::Struct)) | Some(&(ref fqp, item_type::Struct)) |
Some(&(ref fqp, item_type::Enum)) => Some(&(ref fqp, item_type::Enum)) =>
Some(fqp.slice_to(fqp.len() - 1)), Some(fqp[..fqp.len() - 1]),
Some(..) => Some(self.stack.as_slice()), Some(..) => Some(self.stack.as_slice()),
None => None None => None
}; };
@ -1172,7 +1172,7 @@ impl Context {
let mut url = "../".repeat(cx.current.len()); let mut url = "../".repeat(cx.current.len());
match cache_key.get().unwrap().paths.find(&it.def_id) { match cache_key.get().unwrap().paths.find(&it.def_id) {
Some(&(ref names, _)) => { Some(&(ref names, _)) => {
for name in names.slice_to(names.len() - 1).iter() { for name in names[..names.len() - 1].iter() {
url.push_str(name.as_slice()); url.push_str(name.as_slice());
url.push_str("/"); url.push_str("/");
} }

View file

@ -15,7 +15,8 @@
#![crate_type = "dylib"] #![crate_type = "dylib"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![feature(globs, struct_variant, macro_rules, phase)] #![allow(unknown_features)]
#![feature(globs, struct_variant, macro_rules, phase, slicing_syntax)]
extern crate arena; extern crate arena;
extern crate debug; extern crate debug;

View file

@ -16,9 +16,10 @@
html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/")] html_root_url = "http://doc.rust-lang.org/master/")]
#![allow(unknown_features)]
#![feature(macro_rules, phase, globs, thread_local, asm)] #![feature(macro_rules, phase, globs, thread_local, asm)]
#![feature(linkage, lang_items, unsafe_destructor, default_type_params)] #![feature(linkage, lang_items, unsafe_destructor, default_type_params)]
#![feature(import_shadowing)] #![feature(import_shadowing, slicing_syntax)]
#![no_std] #![no_std]
#![experimental] #![experimental]

View file

@ -562,7 +562,7 @@ fn begin_unwind_inner(msg: Box<Any + Send>, file_line: &(&'static str, uint)) ->
// MAX_CALLBACKS, so we're sure to clamp it as necessary. // MAX_CALLBACKS, so we're sure to clamp it as necessary.
let callbacks = unsafe { let callbacks = unsafe {
let amt = CALLBACK_CNT.load(atomic::SeqCst); let amt = CALLBACK_CNT.load(atomic::SeqCst);
CALLBACKS.slice_to(cmp::min(amt, MAX_CALLBACKS)) CALLBACKS[..cmp::min(amt, MAX_CALLBACKS)]
}; };
for cb in callbacks.iter() { for cb in callbacks.iter() {
match cb.load(atomic::SeqCst) { match cb.load(atomic::SeqCst) {

View file

@ -64,8 +64,8 @@ pub fn abort(args: &fmt::Arguments) -> ! {
} }
impl<'a> FormatWriter for BufWriter<'a> { impl<'a> FormatWriter for BufWriter<'a> {
fn write(&mut self, bytes: &[u8]) -> fmt::Result { fn write(&mut self, bytes: &[u8]) -> fmt::Result {
let left = self.buf.slice_from_mut(self.pos); let left = self.buf[mut self.pos..];
let to_write = bytes.slice_to(cmp::min(bytes.len(), left.len())); let to_write = bytes[..cmp::min(bytes.len(), left.len())];
slice::bytes::copy_memory(left, to_write); slice::bytes::copy_memory(left, to_write);
self.pos += to_write.len(); self.pos += to_write.len();
Ok(()) Ok(())
@ -76,7 +76,7 @@ pub fn abort(args: &fmt::Arguments) -> ! {
let mut msg = [0u8, ..512]; let mut msg = [0u8, ..512];
let mut w = BufWriter { buf: msg, pos: 0 }; let mut w = BufWriter { buf: msg, pos: 0 };
let _ = write!(&mut w, "{}", args); let _ = write!(&mut w, "{}", args);
let msg = str::from_utf8(w.buf.slice_to(w.pos)).unwrap_or("aborted"); let msg = str::from_utf8(w.buf[mut ..w.pos]).unwrap_or("aborted");
let msg = if msg.is_empty() {"aborted"} else {msg}; let msg = if msg.is_empty() {"aborted"} else {msg};
// Give some context to the message // Give some context to the message

View file

@ -334,7 +334,7 @@ pub fn escape_bytes(wr: &mut io::Writer, bytes: &[u8]) -> Result<(), io::IoError
}; };
if start < i { if start < i {
try!(wr.write(bytes.slice(start, i))); try!(wr.write(bytes[start..i]));
} }
try!(wr.write_str(escaped)); try!(wr.write_str(escaped));
@ -343,7 +343,7 @@ pub fn escape_bytes(wr: &mut io::Writer, bytes: &[u8]) -> Result<(), io::IoError
} }
if start != bytes.len() { if start != bytes.len() {
try!(wr.write(bytes.slice_from(start))); try!(wr.write(bytes[start..]));
} }
wr.write_str("\"") wr.write_str("\"")
@ -371,7 +371,7 @@ fn spaces(wr: &mut io::Writer, mut n: uint) -> Result<(), io::IoError> {
} }
if n > 0 { if n > 0 {
wr.write(buf.slice_to(n)) wr.write(buf[..n])
} else { } else {
Ok(()) Ok(())
} }
@ -1151,7 +1151,7 @@ impl Stack {
InternalIndex(i) => { Index(i) } InternalIndex(i) => { Index(i) }
InternalKey(start, size) => { InternalKey(start, size) => {
Key(str::from_utf8( Key(str::from_utf8(
self.str_buffer.slice(start as uint, start as uint + size as uint)).unwrap()) self.str_buffer[start as uint .. start as uint + size as uint]).unwrap())
} }
} }
} }
@ -1193,7 +1193,7 @@ impl Stack {
Some(&InternalIndex(i)) => Some(Index(i)), Some(&InternalIndex(i)) => Some(Index(i)),
Some(&InternalKey(start, size)) => { Some(&InternalKey(start, size)) => {
Some(Key(str::from_utf8( Some(Key(str::from_utf8(
self.str_buffer.slice(start as uint, (start+size) as uint) self.str_buffer[start as uint .. (start+size) as uint]
).unwrap())) ).unwrap()))
} }
} }

View file

@ -23,7 +23,8 @@ Core encoding and decoding interfaces.
html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/", html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")] html_playground_url = "http://play.rust-lang.org/")]
#![feature(macro_rules, default_type_params, phase)] #![allow(unknown_features)]
#![feature(macro_rules, default_type_params, phase, slicing_syntax)]
// test harness access // test harness access
#[cfg(test)] #[cfg(test)]

View file

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

View file

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

View file

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

View file

@ -90,10 +90,10 @@ impl<R: Reader> BufferedReader<R> {
impl<R: Reader> Buffer for BufferedReader<R> { impl<R: Reader> Buffer for BufferedReader<R> {
fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> { fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> {
if self.pos == self.cap { if self.pos == self.cap {
self.cap = try!(self.inner.read(self.buf.as_mut_slice())); self.cap = try!(self.inner.read(self.buf[mut]));
self.pos = 0; self.pos = 0;
} }
Ok(self.buf.slice(self.pos, self.cap)) Ok(self.buf[self.pos..self.cap])
} }
fn consume(&mut self, amt: uint) { fn consume(&mut self, amt: uint) {
@ -107,7 +107,7 @@ impl<R: Reader> Reader for BufferedReader<R> {
let nread = { let nread = {
let available = try!(self.fill_buf()); let available = try!(self.fill_buf());
let nread = cmp::min(available.len(), buf.len()); let nread = cmp::min(available.len(), buf.len());
slice::bytes::copy_memory(buf, available.slice_to(nread)); slice::bytes::copy_memory(buf, available[..nread]);
nread nread
}; };
self.pos += nread; self.pos += nread;
@ -162,7 +162,7 @@ impl<W: Writer> BufferedWriter<W> {
fn flush_buf(&mut self) -> IoResult<()> { fn flush_buf(&mut self) -> IoResult<()> {
if self.pos != 0 { if self.pos != 0 {
let ret = self.inner.as_mut().unwrap().write(self.buf.slice_to(self.pos)); let ret = self.inner.as_mut().unwrap().write(self.buf[..self.pos]);
self.pos = 0; self.pos = 0;
ret ret
} else { } else {
@ -195,7 +195,7 @@ impl<W: Writer> Writer for BufferedWriter<W> {
if buf.len() > self.buf.len() { if buf.len() > self.buf.len() {
self.inner.as_mut().unwrap().write(buf) self.inner.as_mut().unwrap().write(buf)
} else { } else {
let dst = self.buf.slice_from_mut(self.pos); let dst = self.buf[mut self.pos..];
slice::bytes::copy_memory(dst, buf); slice::bytes::copy_memory(dst, buf);
self.pos += buf.len(); self.pos += buf.len();
Ok(()) Ok(())
@ -250,9 +250,9 @@ impl<W: Writer> Writer for LineBufferedWriter<W> {
fn write(&mut self, buf: &[u8]) -> IoResult<()> { fn write(&mut self, buf: &[u8]) -> IoResult<()> {
match buf.iter().rposition(|&b| b == b'\n') { match buf.iter().rposition(|&b| b == b'\n') {
Some(i) => { Some(i) => {
try!(self.inner.write(buf.slice_to(i + 1))); try!(self.inner.write(buf[..i + 1]));
try!(self.inner.flush()); try!(self.inner.flush());
try!(self.inner.write(buf.slice_from(i + 1))); try!(self.inner.write(buf[i + 1..]));
Ok(()) Ok(())
} }
None => self.inner.write(buf), None => self.inner.write(buf),

View file

@ -15,8 +15,7 @@ use comm::{Sender, Receiver};
use io; use io;
use option::{None, Option, Some}; use option::{None, Option, Some};
use result::{Ok, Err}; use result::{Ok, Err};
use slice::{bytes, MutableSlice, ImmutableSlice, CloneableVector}; use slice::{bytes, CloneableVector};
use str::StrSlice;
use super::{Reader, Writer, IoResult}; use super::{Reader, Writer, IoResult};
use vec::Vec; use vec::Vec;
@ -62,10 +61,10 @@ impl Reader for ChanReader {
loop { loop {
match self.buf { match self.buf {
Some(ref prev) => { Some(ref prev) => {
let dst = buf.slice_from_mut(num_read); let dst = buf[mut num_read..];
let src = prev.slice_from(self.pos); let src = prev[self.pos..];
let count = cmp::min(dst.len(), src.len()); let count = cmp::min(dst.len(), src.len());
bytes::copy_memory(dst, src.slice_to(count)); bytes::copy_memory(dst, src[..count]);
num_read += count; num_read += count;
self.pos += count; self.pos += count;
}, },

View file

@ -23,7 +23,7 @@ use num::Int;
use option::{Option, Some, None}; use option::{Option, Some, None};
use ptr::RawPtr; use ptr::RawPtr;
use result::{Ok, Err}; use result::{Ok, Err};
use slice::{ImmutableSlice, Slice}; use slice::{ImmutableSlice, AsSlice};
/// An iterator that reads a single byte on each iteration, /// An iterator that reads a single byte on each iteration,
/// until `.read_byte()` returns `EndOfFile`. /// until `.read_byte()` returns `EndOfFile`.

View file

@ -485,7 +485,7 @@ pub fn copy(from: &Path, to: &Path) -> IoResult<()> {
Err(ref e) if e.kind == io::EndOfFile => { break } Err(ref e) if e.kind == io::EndOfFile => { break }
Err(e) => return update_err(Err(e), from, to) Err(e) => return update_err(Err(e), from, to)
}; };
try!(writer.write(buf.slice_to(amt))); try!(writer.write(buf[..amt]));
} }
chmod(to, try!(update_err(from.stat(), from, to)).perm) chmod(to, try!(update_err(from.stat(), from, to)).perm)
@ -1014,7 +1014,7 @@ mod test {
let mut read_buf = [0, .. 1028]; let mut read_buf = [0, .. 1028];
let read_str = match check!(read_stream.read(read_buf)) { let read_str = match check!(read_stream.read(read_buf)) {
-1|0 => fail!("shouldn't happen"), -1|0 => fail!("shouldn't happen"),
n => str::from_utf8(read_buf.slice_to(n)).unwrap().to_string() n => str::from_utf8(read_buf[..n]).unwrap().to_string()
}; };
assert_eq!(read_str.as_slice(), message); assert_eq!(read_str.as_slice(), message);
} }
@ -1061,11 +1061,11 @@ mod test {
{ {
let mut read_stream = File::open_mode(filename, Open, Read); let mut read_stream = File::open_mode(filename, Open, Read);
{ {
let read_buf = read_mem.slice_mut(0, 4); let read_buf = read_mem[mut 0..4];
check!(read_stream.read(read_buf)); check!(read_stream.read(read_buf));
} }
{ {
let read_buf = read_mem.slice_mut(4, 8); let read_buf = read_mem[mut 4..8];
check!(read_stream.read(read_buf)); check!(read_stream.read(read_buf));
} }
} }

View file

@ -19,7 +19,7 @@ use result::{Err, Ok};
use io; use io;
use io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult}; use io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult};
use slice; use slice;
use slice::{Slice, ImmutableSlice, MutableSlice}; use slice::AsSlice;
use vec::Vec; use vec::Vec;
static BUF_CAPACITY: uint = 128; static BUF_CAPACITY: uint = 128;
@ -146,8 +146,8 @@ impl Reader for MemReader {
let write_len = min(buf.len(), self.buf.len() - self.pos); let write_len = min(buf.len(), self.buf.len() - self.pos);
{ {
let input = self.buf.slice(self.pos, self.pos + write_len); let input = self.buf[self.pos.. self.pos + write_len];
let output = buf.slice_mut(0, write_len); let output = buf[mut ..write_len];
assert_eq!(input.len(), output.len()); assert_eq!(input.len(), output.len());
slice::bytes::copy_memory(output, input); slice::bytes::copy_memory(output, input);
} }
@ -174,7 +174,7 @@ impl Buffer for MemReader {
#[inline] #[inline]
fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> { fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> {
if self.pos < self.buf.len() { if self.pos < self.buf.len() {
Ok(self.buf.slice_from(self.pos)) Ok(self.buf[self.pos..])
} else { } else {
Err(io::standard_error(io::EndOfFile)) Err(io::standard_error(io::EndOfFile))
} }
@ -232,7 +232,7 @@ impl<'a> Writer for BufWriter<'a> {
}) })
} }
slice::bytes::copy_memory(self.buf.slice_from_mut(self.pos), buf); slice::bytes::copy_memory(self.buf[mut self.pos..], buf);
self.pos += buf.len(); self.pos += buf.len();
Ok(()) Ok(())
} }
@ -292,8 +292,8 @@ impl<'a> Reader for BufReader<'a> {
let write_len = min(buf.len(), self.buf.len() - self.pos); let write_len = min(buf.len(), self.buf.len() - self.pos);
{ {
let input = self.buf.slice(self.pos, self.pos + write_len); let input = self.buf[self.pos.. self.pos + write_len];
let output = buf.slice_mut(0, write_len); let output = buf[mut ..write_len];
assert_eq!(input.len(), output.len()); assert_eq!(input.len(), output.len());
slice::bytes::copy_memory(output, input); slice::bytes::copy_memory(output, input);
} }
@ -320,7 +320,7 @@ impl<'a> Buffer for BufReader<'a> {
#[inline] #[inline]
fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> { fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> {
if self.pos < self.buf.len() { if self.pos < self.buf.len() {
Ok(self.buf.slice_from(self.pos)) Ok(self.buf[self.pos..])
} else { } else {
Err(io::standard_error(io::EndOfFile)) Err(io::standard_error(io::EndOfFile))
} }
@ -427,7 +427,7 @@ mod test {
assert_eq!(buf.as_slice(), b); assert_eq!(buf.as_slice(), b);
assert_eq!(reader.read(buf), Ok(3)); assert_eq!(reader.read(buf), Ok(3));
let b: &[_] = &[5, 6, 7]; let b: &[_] = &[5, 6, 7];
assert_eq!(buf.slice(0, 3), b); assert_eq!(buf[0..3], b);
assert!(reader.read(buf).is_err()); assert!(reader.read(buf).is_err());
let mut reader = MemReader::new(vec!(0, 1, 2, 3, 4, 5, 6, 7)); let mut reader = MemReader::new(vec!(0, 1, 2, 3, 4, 5, 6, 7));
assert_eq!(reader.read_until(3).unwrap(), vec!(0, 1, 2, 3)); assert_eq!(reader.read_until(3).unwrap(), vec!(0, 1, 2, 3));
@ -454,7 +454,7 @@ mod test {
assert_eq!(buf.as_slice(), b); assert_eq!(buf.as_slice(), b);
assert_eq!(reader.read(buf), Ok(3)); assert_eq!(reader.read(buf), Ok(3));
let b: &[_] = &[5, 6, 7]; let b: &[_] = &[5, 6, 7];
assert_eq!(buf.slice(0, 3), b); assert_eq!(buf[0..3], b);
assert!(reader.read(buf).is_err()); assert!(reader.read(buf).is_err());
let mut reader = BufReader::new(in_buf.as_slice()); let mut reader = BufReader::new(in_buf.as_slice());
assert_eq!(reader.read_until(3).unwrap(), vec!(0, 1, 2, 3)); assert_eq!(reader.read_until(3).unwrap(), vec!(0, 1, 2, 3));
@ -548,7 +548,7 @@ mod test {
assert!(r.read_at_least(buf.len(), buf).is_ok()); assert!(r.read_at_least(buf.len(), buf).is_ok());
let b: &[_] = &[1, 2, 3]; let b: &[_] = &[1, 2, 3];
assert_eq!(buf.as_slice(), b); assert_eq!(buf.as_slice(), b);
assert!(r.read_at_least(0, buf.slice_to_mut(0)).is_ok()); assert!(r.read_at_least(0, buf[mut ..0]).is_ok());
assert_eq!(buf.as_slice(), b); assert_eq!(buf.as_slice(), b);
assert!(r.read_at_least(buf.len(), buf).is_ok()); assert!(r.read_at_least(buf.len(), buf).is_ok());
let b: &[_] = &[4, 5, 6]; let b: &[_] = &[4, 5, 6];

View file

@ -235,7 +235,7 @@ use os;
use boxed::Box; use boxed::Box;
use result::{Ok, Err, Result}; use result::{Ok, Err, Result};
use rt::rtio; use rt::rtio;
use slice::{Slice, MutableSlice, ImmutableSlice}; use slice::{AsSlice, ImmutableSlice};
use str::{Str, StrSlice}; use str::{Str, StrSlice};
use str; use str;
use string::String; use string::String;
@ -575,7 +575,7 @@ pub trait Reader {
while read < min { while read < min {
let mut zeroes = 0; let mut zeroes = 0;
loop { loop {
match self.read(buf.slice_from_mut(read)) { match self.read(buf[mut read..]) {
Ok(0) => { Ok(0) => {
zeroes += 1; zeroes += 1;
if zeroes >= NO_PROGRESS_LIMIT { if zeroes >= NO_PROGRESS_LIMIT {
@ -1111,8 +1111,8 @@ pub trait Writer {
#[inline] #[inline]
fn write_char(&mut self, c: char) -> IoResult<()> { fn write_char(&mut self, c: char) -> IoResult<()> {
let mut buf = [0u8, ..4]; let mut buf = [0u8, ..4];
let n = c.encode_utf8(buf.as_mut_slice()).unwrap_or(0); let n = c.encode_utf8(buf[mut]).unwrap_or(0);
self.write(buf.slice_to(n)) self.write(buf[..n])
} }
/// Write the result of passing n through `int::to_str_bytes`. /// Write the result of passing n through `int::to_str_bytes`.
@ -1496,7 +1496,7 @@ pub trait Buffer: Reader {
}; };
match available.iter().position(|&b| b == byte) { match available.iter().position(|&b| b == byte) {
Some(i) => { Some(i) => {
res.push_all(available.slice_to(i + 1)); res.push_all(available[..i + 1]);
used = i + 1; used = i + 1;
break break
} }
@ -1528,14 +1528,14 @@ pub trait Buffer: Reader {
{ {
let mut start = 1; let mut start = 1;
while start < width { while start < width {
match try!(self.read(buf.slice_mut(start, width))) { match try!(self.read(buf[mut start..width])) {
n if n == width - start => break, n if n == width - start => break,
n if n < width - start => { start += n; } n if n < width - start => { start += n; }
_ => return Err(standard_error(InvalidInput)), _ => return Err(standard_error(InvalidInput)),
} }
} }
} }
match str::from_utf8(buf.slice_to(width)) { match str::from_utf8(buf[..width]) {
Some(s) => Ok(s.char_at(0)), Some(s) => Ok(s.char_at(0)),
None => Err(standard_error(InvalidInput)) None => Err(standard_error(InvalidInput))
} }

View file

@ -21,7 +21,7 @@ use from_str::FromStr;
use iter::Iterator; use iter::Iterator;
use option::{Option, None, Some}; use option::{Option, None, Some};
use str::StrSlice; use str::StrSlice;
use slice::{MutableCloneableSlice, ImmutableSlice, MutableSlice}; use slice::{MutableCloneableSlice, MutableSlice};
pub type Port = u16; pub type Port = u16;
@ -241,7 +241,7 @@ impl<'a> Parser<'a> {
assert!(head.len() + tail.len() <= 8); assert!(head.len() + tail.len() <= 8);
let mut gs = [0u16, ..8]; let mut gs = [0u16, ..8];
gs.clone_from_slice(head); gs.clone_from_slice(head);
gs.slice_mut(8 - tail.len(), 8).clone_from_slice(tail); gs[mut 8 - tail.len() .. 8].clone_from_slice(tail);
Ipv6Addr(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7]) Ipv6Addr(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7])
} }
@ -303,7 +303,7 @@ impl<'a> Parser<'a> {
let mut tail = [0u16, ..8]; let mut tail = [0u16, ..8];
let (tail_size, _) = read_groups(self, &mut tail, 8 - head_size); let (tail_size, _) = read_groups(self, &mut tail, 8 - head_size);
Some(ipv6_addr_from_head_tail(head.slice(0, head_size), tail.slice(0, tail_size))) Some(ipv6_addr_from_head_tail(head[..head_size], tail[..tail_size]))
} }
fn read_ipv6_addr(&mut self) -> Option<IpAddr> { fn read_ipv6_addr(&mut self) -> Option<IpAddr> {

View file

@ -35,26 +35,29 @@ use rt::rtio;
/// ///
/// ```rust,no_run /// ```rust,no_run
/// # #![allow(unused_must_use)] /// # #![allow(unused_must_use)]
/// #![feature(slicing_syntax)]
///
/// use std::io::net::udp::UdpSocket; /// use std::io::net::udp::UdpSocket;
/// use std::io::net::ip::{Ipv4Addr, SocketAddr}; /// use std::io::net::ip::{Ipv4Addr, SocketAddr};
/// fn main() {
/// let addr = SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 34254 };
/// let mut socket = match UdpSocket::bind(addr) {
/// Ok(s) => s,
/// Err(e) => fail!("couldn't bind socket: {}", e),
/// };
/// ///
/// let addr = SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 34254 }; /// let mut buf = [0, ..10];
/// let mut socket = match UdpSocket::bind(addr) { /// match socket.recv_from(buf) {
/// Ok(s) => s, /// Ok((amt, src)) => {
/// Err(e) => fail!("couldn't bind socket: {}", e), /// // Send a reply to the socket we received data from
/// }; /// let buf = buf[mut ..amt];
/// /// buf.reverse();
/// let mut buf = [0, ..10]; /// socket.send_to(buf, src);
/// match socket.recv_from(buf) { /// }
/// Ok((amt, src)) => { /// Err(e) => println!("couldn't receive a datagram: {}", e)
/// // Send a reply to the socket we received data from
/// let buf = buf.slice_to_mut(amt);
/// buf.reverse();
/// socket.send_to(buf, src);
/// } /// }
/// Err(e) => println!("couldn't receive a datagram: {}", e) /// drop(socket); // close the socket
/// } /// }
/// drop(socket); // close the socket
/// ``` /// ```
pub struct UdpSocket { pub struct UdpSocket {
obj: Box<RtioUdpSocket + Send>, obj: Box<RtioUdpSocket + Send>,

View file

@ -47,7 +47,7 @@ impl<R: Reader> Reader for LimitReader<R> {
} }
let len = cmp::min(self.limit, buf.len()); let len = cmp::min(self.limit, buf.len());
let res = self.inner.read(buf.slice_to_mut(len)); let res = self.inner.read(buf[mut ..len]);
match res { match res {
Ok(len) => self.limit -= len, Ok(len) => self.limit -= len,
_ => {} _ => {}
@ -59,7 +59,7 @@ impl<R: Reader> Reader for LimitReader<R> {
impl<R: Buffer> Buffer for LimitReader<R> { impl<R: Buffer> Buffer for LimitReader<R> {
fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> { fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> {
let amt = try!(self.inner.fill_buf()); let amt = try!(self.inner.fill_buf());
let buf = amt.slice_to(cmp::min(amt.len(), self.limit)); let buf = amt[..cmp::min(amt.len(), self.limit)];
if buf.len() == 0 { if buf.len() == 0 {
Err(io::standard_error(io::EndOfFile)) Err(io::standard_error(io::EndOfFile))
} else { } else {
@ -216,7 +216,7 @@ impl<R: Reader, W: Writer> TeeReader<R, W> {
impl<R: Reader, W: Writer> Reader for TeeReader<R, W> { impl<R: Reader, W: Writer> Reader for TeeReader<R, W> {
fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> { fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
self.reader.read(buf).and_then(|len| { self.reader.read(buf).and_then(|len| {
self.writer.write(buf.slice_to(len)).map(|()| len) self.writer.write(buf[mut ..len]).map(|()| len)
}) })
} }
} }
@ -230,7 +230,7 @@ pub fn copy<R: Reader, W: Writer>(r: &mut R, w: &mut W) -> io::IoResult<()> {
Err(ref e) if e.kind == io::EndOfFile => return Ok(()), Err(ref e) if e.kind == io::EndOfFile => return Ok(()),
Err(e) => return Err(e), Err(e) => return Err(e),
}; };
try!(w.write(buf.slice_to(len))); try!(w.write(buf[..len]));
} }
} }

View file

@ -105,9 +105,10 @@
html_root_url = "http://doc.rust-lang.org/master/", html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")] html_playground_url = "http://play.rust-lang.org/")]
#![allow(unknown_features)]
#![feature(macro_rules, globs, linkage)] #![feature(macro_rules, globs, linkage)]
#![feature(default_type_params, phase, lang_items, unsafe_destructor)] #![feature(default_type_params, phase, lang_items, unsafe_destructor)]
#![feature(import_shadowing)] #![feature(import_shadowing, slicing_syntax)]
// Don't link to std. We are std. // Don't link to std. We are std.
#![no_std] #![no_std]

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -78,7 +78,7 @@ pub fn to_str_bytes<U>(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U {
(write!(&mut wr, "{}", ::fmt::radix(n, radix as u8))).unwrap(); (write!(&mut wr, "{}", ::fmt::radix(n, radix as u8))).unwrap();
wr.tell().unwrap() as uint wr.tell().unwrap() as uint
}; };
f(buf.slice(0, amt)) f(buf[..amt])
} }
#[deprecated = "use fmt::radix"] #[deprecated = "use fmt::radix"]

View file

@ -730,7 +730,7 @@ pub fn from_str_bytes_common<T:NumCast+Zero+One+PartialEq+PartialOrd+Div<T,T>+
// parse remaining bytes as decimal integer, // parse remaining bytes as decimal integer,
// skipping the exponent char // skipping the exponent char
let exp: Option<int> = from_str_bytes_common( let exp: Option<int> = from_str_bytes_common(
buf.slice(i+1, len), 10, true, false, false, ExpNone, false, buf[i+1..len], 10, true, false, false, ExpNone, false,
ignore_underscores); ignore_underscores);
match exp { match exp {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -79,7 +79,7 @@ pub fn to_str_bytes<U>(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U {
(write!(&mut wr, "{}", ::fmt::radix(n, radix as u8))).unwrap(); (write!(&mut wr, "{}", ::fmt::radix(n, radix as u8))).unwrap();
wr.tell().unwrap() as uint wr.tell().unwrap() as uint
}; };
f(buf.slice(0, amt)) f(buf[..amt])
} }
#[deprecated = "use fmt::radix"] #[deprecated = "use fmt::radix"]

View file

@ -45,7 +45,7 @@ use path::{Path, GenericPath, BytesContainer};
use ptr::RawPtr; use ptr::RawPtr;
use ptr; use ptr;
use result::{Err, Ok, Result}; use result::{Err, Ok, Result};
use slice::{Slice, ImmutableSlice, MutableSlice, ImmutablePartialEqSlice}; use slice::{AsSlice, ImmutableSlice, MutableSlice, ImmutablePartialEqSlice};
use slice::CloneableVector; use slice::CloneableVector;
use str::{Str, StrSlice, StrAllocating}; use str::{Str, StrSlice, StrAllocating};
use string::String; use string::String;
@ -144,7 +144,7 @@ pub mod windows {
use option::{None, Option}; use option::{None, Option};
use option; use option;
use os::TMPBUF_SZ; use os::TMPBUF_SZ;
use slice::{MutableSlice, ImmutableSlice}; use slice::MutableSlice;
use string::String; use string::String;
use str::StrSlice; use str::StrSlice;
use vec::Vec; use vec::Vec;

View file

@ -76,7 +76,7 @@ use option::{Option, None, Some};
use str; use str;
use str::{MaybeOwned, Str, StrSlice}; use str::{MaybeOwned, Str, StrSlice};
use string::String; use string::String;
use slice::{Slice, CloneableVector}; use slice::{AsSlice, CloneableVector};
use slice::{ImmutablePartialEqSlice, ImmutableSlice}; use slice::{ImmutablePartialEqSlice, ImmutableSlice};
use vec::Vec; use vec::Vec;
@ -357,7 +357,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe {
match name.rposition_elem(&dot) { match name.rposition_elem(&dot) {
None | Some(0) => name, None | Some(0) => name,
Some(1) if name == b".." => name, Some(1) if name == b".." => name,
Some(pos) => name.slice_to(pos) Some(pos) => name[..pos]
} }
}) })
} }
@ -404,7 +404,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe {
match name.rposition_elem(&dot) { match name.rposition_elem(&dot) {
None | Some(0) => None, None | Some(0) => None,
Some(1) if name == b".." => None, Some(1) if name == b".." => None,
Some(pos) => Some(name.slice_from(pos+1)) Some(pos) => Some(name[pos+1..])
} }
} }
} }
@ -480,7 +480,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe {
let extlen = extension.container_as_bytes().len(); let extlen = extension.container_as_bytes().len();
match (name.rposition_elem(&dot), extlen) { match (name.rposition_elem(&dot), extlen) {
(None, 0) | (Some(0), 0) => None, (None, 0) | (Some(0), 0) => None,
(Some(idx), 0) => Some(name.slice_to(idx).to_vec()), (Some(idx), 0) => Some(name[..idx].to_vec()),
(idx, extlen) => { (idx, extlen) => {
let idx = match idx { let idx = match idx {
None | Some(0) => name.len(), None | Some(0) => name.len(),
@ -489,7 +489,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe {
let mut v; let mut v;
v = Vec::with_capacity(idx + extlen + 1); v = Vec::with_capacity(idx + extlen + 1);
v.push_all(name.slice_to(idx)); v.push_all(name[..idx]);
v.push(dot); v.push(dot);
v.push_all(extension.container_as_bytes()); v.push_all(extension.container_as_bytes());
Some(v) Some(v)

View file

@ -21,7 +21,7 @@ use iter::{DoubleEndedIterator, AdditiveIterator, Extendable, Iterator, Map};
use option::{Option, None, Some}; use option::{Option, None, Some};
use str::Str; use str::Str;
use str; use str;
use slice::{CloneableVector, Splits, Slice, VectorVector, use slice::{CloneableVector, Splits, AsSlice, VectorVector,
ImmutablePartialEqSlice, ImmutableSlice}; ImmutablePartialEqSlice, ImmutableSlice};
use vec::Vec; use vec::Vec;
@ -165,7 +165,7 @@ impl GenericPathUnsafe for Path {
None => { None => {
self.repr = Path::normalize(filename); self.repr = Path::normalize(filename);
} }
Some(idx) if self.repr.slice_from(idx+1) == b".." => { Some(idx) if self.repr[idx+1..] == b".." => {
let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len()); let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len());
v.push_all(self.repr.as_slice()); v.push_all(self.repr.as_slice());
v.push(SEP_BYTE); v.push(SEP_BYTE);
@ -175,7 +175,7 @@ impl GenericPathUnsafe for Path {
} }
Some(idx) => { Some(idx) => {
let mut v = Vec::with_capacity(idx + 1 + filename.len()); let mut v = Vec::with_capacity(idx + 1 + filename.len());
v.push_all(self.repr.slice_to(idx+1)); v.push_all(self.repr[..idx+1]);
v.push_all(filename); v.push_all(filename);
// FIXME: this is slow // FIXME: this is slow
self.repr = Path::normalize(v.as_slice()); self.repr = Path::normalize(v.as_slice());
@ -216,9 +216,9 @@ impl GenericPath for Path {
match self.sepidx { match self.sepidx {
None if b".." == self.repr.as_slice() => self.repr.as_slice(), None if b".." == self.repr.as_slice() => self.repr.as_slice(),
None => dot_static, None => dot_static,
Some(0) => self.repr.slice_to(1), Some(0) => self.repr[..1],
Some(idx) if self.repr.slice_from(idx+1) == b".." => self.repr.as_slice(), Some(idx) if self.repr[idx+1..] == b".." => self.repr.as_slice(),
Some(idx) => self.repr.slice_to(idx) Some(idx) => self.repr[..idx]
} }
} }
@ -227,9 +227,9 @@ impl GenericPath for Path {
None if b"." == self.repr.as_slice() || None if b"." == self.repr.as_slice() ||
b".." == self.repr.as_slice() => None, b".." == self.repr.as_slice() => None,
None => Some(self.repr.as_slice()), None => Some(self.repr.as_slice()),
Some(idx) if self.repr.slice_from(idx+1) == b".." => None, Some(idx) if self.repr[idx+1..] == b".." => None,
Some(0) if self.repr.slice_from(1).is_empty() => None, Some(0) if self.repr[1..].is_empty() => None,
Some(idx) => Some(self.repr.slice_from(idx+1)) Some(idx) => Some(self.repr[idx+1..])
} }
} }
@ -367,11 +367,11 @@ impl Path {
/// Returns a normalized byte vector representation of a path, by removing all empty /// Returns a normalized byte vector representation of a path, by removing all empty
/// components, and unnecessary . and .. components. /// components, and unnecessary . and .. components.
fn normalize<V: Slice<u8>+CloneableVector<u8>>(v: V) -> Vec<u8> { fn normalize<V: AsSlice<u8>+CloneableVector<u8>>(v: V) -> Vec<u8> {
// borrowck is being very picky // borrowck is being very picky
let val = { let val = {
let is_abs = !v.as_slice().is_empty() && v.as_slice()[0] == SEP_BYTE; let is_abs = !v.as_slice().is_empty() && v.as_slice()[0] == SEP_BYTE;
let v_ = if is_abs { v.as_slice().slice_from(1) } else { v.as_slice() }; let v_ = if is_abs { v.as_slice()[1..] } else { v.as_slice() };
let comps = normalize_helper(v_, is_abs); let comps = normalize_helper(v_, is_abs);
match comps { match comps {
None => None, None => None,
@ -410,7 +410,7 @@ impl Path {
/// A path of "/" yields no components. A path of "." yields one component. /// A path of "/" yields no components. A path of "." yields one component.
pub fn components<'a>(&'a self) -> Components<'a> { pub fn components<'a>(&'a self) -> Components<'a> {
let v = if self.repr[0] == SEP_BYTE { let v = if self.repr[0] == SEP_BYTE {
self.repr.slice_from(1) self.repr[1..]
} else { self.repr.as_slice() }; } else { self.repr.as_slice() };
let mut ret = v.split(is_sep_byte); let mut ret = v.split(is_sep_byte);
if v.is_empty() { if v.is_empty() {

View file

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

View file

@ -46,6 +46,7 @@
#[doc(no_inline)] pub use ops::{Drop, Deref, DerefMut}; #[doc(no_inline)] pub use ops::{Drop, Deref, DerefMut};
#[doc(no_inline)] pub use ops::{Shl, Shr}; #[doc(no_inline)] pub use ops::{Shl, Shr};
#[doc(no_inline)] pub use ops::{Index, IndexMut}; #[doc(no_inline)] pub use ops::{Index, IndexMut};
#[doc(no_inline)] pub use ops::{Slice, SliceMut};
#[doc(no_inline)] pub use ops::{Fn, FnMut, FnOnce}; #[doc(no_inline)] pub use ops::{Fn, FnMut, FnOnce};
#[doc(no_inline)] pub use option::{Option, Some, None}; #[doc(no_inline)] pub use option::{Option, Some, None};
#[doc(no_inline)] pub use result::{Result, Ok, Err}; #[doc(no_inline)] pub use result::{Result, Ok, Err};
@ -87,7 +88,7 @@
#[doc(no_inline)] pub use slice::{MutableCloneableSlice, MutableOrdSlice}; #[doc(no_inline)] pub use slice::{MutableCloneableSlice, MutableOrdSlice};
#[doc(no_inline)] pub use slice::{ImmutableSlice, MutableSlice}; #[doc(no_inline)] pub use slice::{ImmutableSlice, MutableSlice};
#[doc(no_inline)] pub use slice::{ImmutablePartialEqSlice, ImmutableOrdSlice}; #[doc(no_inline)] pub use slice::{ImmutablePartialEqSlice, ImmutableOrdSlice};
#[doc(no_inline)] pub use slice::{Slice, VectorVector}; #[doc(no_inline)] pub use slice::{AsSlice, VectorVector};
#[doc(no_inline)] pub use slice::MutableSliceAllocating; #[doc(no_inline)] pub use slice::MutableSliceAllocating;
#[doc(no_inline)] pub use string::String; #[doc(no_inline)] pub use string::String;
#[doc(no_inline)] pub use vec::Vec; #[doc(no_inline)] pub use vec::Vec;

View file

@ -999,7 +999,7 @@ mod imp {
let bytes = cstr.as_bytes(); let bytes = cstr.as_bytes();
match cstr.as_str() { match cstr.as_str() {
Some(s) => try!(super::demangle(w, s)), Some(s) => try!(super::demangle(w, s)),
None => try!(w.write(bytes.slice_to(bytes.len() - 1))), None => try!(w.write(bytes[..bytes.len()-1])),
} }
} }
try!(w.write(['\n' as u8])); try!(w.write(['\n' as u8]));

View file

@ -496,7 +496,7 @@ impl<'ast> Map<'ast> {
NodesMatchingSuffix { NodesMatchingSuffix {
map: self, map: self,
item_name: parts.last().unwrap(), item_name: parts.last().unwrap(),
in_which: parts.slice_to(parts.len() - 1), in_which: parts[..parts.len() - 1],
idx: 0, idx: 0,
} }
} }

View file

@ -414,7 +414,7 @@ fn highlight_lines(err: &mut EmitterWriter,
let mut elided = false; let mut elided = false;
let mut display_lines = lines.lines.as_slice(); let mut display_lines = lines.lines.as_slice();
if display_lines.len() > MAX_LINES { if display_lines.len() > MAX_LINES {
display_lines = display_lines.slice(0u, MAX_LINES); display_lines = display_lines[0u..MAX_LINES];
elided = true; elided = true;
} }
// Print the offending lines // Print the offending lines

View file

@ -70,6 +70,7 @@ static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[
("tuple_indexing", Active), ("tuple_indexing", Active),
("associated_types", Active), ("associated_types", Active),
("visible_private_types", Active), ("visible_private_types", Active),
("slicing_syntax", Active),
("if_let", Active), ("if_let", Active),
@ -350,6 +351,11 @@ impl<'a, 'v> Visitor<'v> for Context<'a> {
self.gate_feature("if_let", e.span, self.gate_feature("if_let", e.span,
"`if let` syntax is experimental"); "`if let` syntax is experimental");
} }
ast::ExprSlice(..) => {
self.gate_feature("slicing_syntax",
e.span,
"slicing syntax is experimental");
}
_ => {} _ => {}
} }
visit::walk_expr(self, e); visit::walk_expr(self, e);

View file

@ -23,7 +23,8 @@
html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/")] html_root_url = "http://doc.rust-lang.org/master/")]
#![feature(macro_rules, globs, default_type_params, phase)] #![allow(unknown_features)]
#![feature(macro_rules, globs, default_type_params, phase, slicing_syntax)]
#![feature(quote, struct_variant, unsafe_destructor, import_shadowing)] #![feature(quote, struct_variant, unsafe_destructor, import_shadowing)]
#![allow(deprecated)] #![allow(deprecated)]

Some files were not shown because too many files have changed in this diff Show more