This commit is contained in:
Nick Cameron 2015-01-04 17:43:24 +13:00
parent 791f545685
commit 0c7f7a5fb8
89 changed files with 543 additions and 468 deletions

View File

@ -539,18 +539,17 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
script_str.push_str("set print pretty off\n");
// Add the pretty printer directory to GDB's source-file search path
script_str.push_str(format!("directory {}\n", rust_pp_module_abs_path)[]);
script_str.push_str(&format!("directory {}\n", rust_pp_module_abs_path)[]);
// Load the target executable
script_str.push_str(format!("file {}\n",
exe_file.as_str().unwrap().replace("\\", "\\\\"))
.as_slice());
script_str.push_str(&format!("file {}\n",
exe_file.as_str().unwrap().replace("\\", "\\\\"))[]);
// Add line breakpoints
for line in breakpoint_lines.iter() {
script_str.push_str(format!("break '{}':{}\n",
testfile.filename_display(),
*line)[]);
script_str.push_str(&format!("break '{}':{}\n",
testfile.filename_display(),
*line)[]);
}
script_str.push_str(cmds.as_slice());
@ -676,7 +675,7 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
.unwrap()
.to_string();
script_str.push_str(format!("command script import {}\n", rust_pp_module_abs_path.index(&FullRange))[]);
script_str.push_str(&format!("command script import {}\n", &rust_pp_module_abs_path[])[]);
script_str.push_str("type summary add --no-value ");
script_str.push_str("--python-function lldb_rust_formatters.print_val ");
script_str.push_str("-x \".*\" --category Rust\n");

View File

@ -525,7 +525,7 @@ impl<T> RingBuf<T> {
/// *num = *num - 2;
/// }
/// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
/// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b);
/// assert_eq!(&buf.iter_mut().collect::<Vec<&mut int>>()[], b);
/// ```
#[stable]
pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {

View File

@ -1393,15 +1393,20 @@ fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order
#[cfg(test)]
mod tests {
use prelude::{Some, None, range, Vec, ToString, Clone, Greater, Less, Equal};
use prelude::{SliceExt, Iterator, IteratorExt};
use prelude::AsSlice;
use prelude::{RandomAccessIterator, Ord, SliceConcatExt};
use core::cmp::Ordering::{Greater, Less, Equal};
use core::prelude::{Some, None, range, Clone};
use core::prelude::{Iterator, IteratorExt};
use core::prelude::{AsSlice};
use core::prelude::{Ord, FullRange};
use core::default::Default;
use core::mem;
use core::ops::Index;
use std::iter::RandomAccessIterator;
use std::rand::{Rng, thread_rng};
use std::rc::Rc;
use super::ElementSwaps;
use string::ToString;
use vec::Vec;
use super::{ElementSwaps, SliceConcatExt, SliceExt};
fn square(n: uint) -> uint { n * n }

View File

@ -60,7 +60,7 @@ use core::char::CharExt;
use core::clone::Clone;
use core::iter::AdditiveIterator;
use core::iter::{range, Iterator, IteratorExt};
use core::ops::{self, llRange, Index};
use core::ops::{FullRange, Index};
use core::option::Option::{self, Some, None};
use core::slice::AsSlice;
use core::str as core_str;
@ -408,7 +408,7 @@ Section: Trait implementations
/// Any string that can be represented as a slice.
#[stable]
pub trait StrExt: Index<FullRange, str> {
pub trait StrExt: Index<FullRange, Output = str> {
/// Escapes each char in `s` with `char::escape_default`.
#[unstable = "return type may change to be an iterator"]
fn escape_default(&self) -> String {
@ -1339,12 +1339,6 @@ pub trait StrExt: Index<FullRange, str> {
fn trim_left(&self) -> &str {
UnicodeStr::trim_left(self.index(&FullRange))
}
/// Returns a string with trailing whitespace removed.
#[stable]
fn trim_right(&self) -> &str {
UnicodeStr::trim_right(self.index(&FullRange))
}
}
#[stable]
@ -2133,7 +2127,7 @@ mod tests {
let mut bytes = [0u8; 4];
for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) {
let len = c.encode_utf8(&mut bytes).unwrap_or(0);
let s = ::core::str::from_utf8(bytes.index(&(0..len))).unwrap();
let s = ::core::str::from_utf8(&bytes[..len]).unwrap();
if Some(c) != s.chars().next() {
panic!("character {:x}={} does not decode correctly", c as u32, c);
}
@ -2145,7 +2139,7 @@ mod tests {
let mut bytes = [0u8; 4];
for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) {
let len = c.encode_utf8(&mut bytes).unwrap_or(0);
let s = ::core::str::from_utf8(bytes.index(&(0..len))).unwrap();
let s = ::core::str::from_utf8(&bytes[..len]).unwrap();
if Some(c) != s.chars().rev().next() {
panic!("character {:x}={} does not decode correctly", c as u32, c);
}

View File

@ -22,7 +22,7 @@ use core::fmt;
use core::hash;
use core::iter::FromIterator;
use core::mem;
use core::ops::{self, Deref, Add};
use core::ops::{self, Deref, Add, Index};
use core::ptr;
use core::raw::Slice as RawSlice;
use unicode::str as unicode_str;
@ -818,28 +818,29 @@ impl<'a> Add<&'a str> for String {
}
}
impl ops::Index<ops::Range<uint>, str> for String {
impl ops::Index<ops::Range<uint>> for String {
type Output = str;
#[inline]
fn index(&self, index: &ops::Range<uint>) -> &str {
&self.index(&FullRange)[*index]
}
}
impl ops::Index<ops::RangeTo<uint>, str> for String {
impl ops::Index<ops::RangeTo<uint>> for String {
type Output = str;
#[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &str {
&self.index(&FullRange)[*index]
}
}
impl ops::Index<ops::RangeFrom<uint>, str> for String {
impl ops::Index<ops::RangeFrom<uint>> for String {
type Output = str;
#[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &str {
&self.index(&FullRange)[*index]
}
}
impl ops::Index<ops::FullRange, str> for String {
impl ops::Index<ops::FullRange> for String {
type Output = str;
#[inline]
fn index(&self, _index: &ops::FullRange) -> &str {
unsafe { mem::transmute(self.vec.as_slice()) }
@ -949,6 +950,7 @@ mod tests {
use str::Utf8Error;
use core::iter::repeat;
use super::{as_string, CowString};
use core::ops::FullRange;
#[test]
fn test_as_string() {
@ -1230,10 +1232,10 @@ mod tests {
#[test]
fn test_slicing() {
let s = "foobar".to_string();
assert_eq!("foobar", s.index(&FullRange));
assert_eq!("foo", s.index(&(0..3)));
assert_eq!("bar", s.index(&(3..)));
assert_eq!("oob", s.index(&(1..4)));
assert_eq!("foobar", &s[]);
assert_eq!("foo", &s[..3]);
assert_eq!("bar", &s[3..]);
assert_eq!("oob", &s[1..4]);
}
#[test]

View File

@ -1209,62 +1209,66 @@ impl<T> IndexMut<uint> for Vec<T> {
}
}
impl<T> ops::Index<ops::Range<uint>, [T]> for Vec<T> {
impl<T> ops::Index<ops::Range<uint>> for Vec<T> {
type Output = [T];
#[inline]
fn index(&self, index: &ops::Range<uint>) -> &[T] {
self.as_slice().index(index)
}
}
impl<T> ops::Index<ops::RangeTo<uint>, [T]> for Vec<T> {
impl<T> ops::Index<ops::RangeTo<uint>> for Vec<T> {
type Output = [T];
#[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
self.as_slice().index(index)
}
}
impl<T> ops::Index<ops::RangeFrom<uint>, [T]> for Vec<T> {
impl<T> ops::Index<ops::RangeFrom<uint>> for Vec<T> {
type Output = [T];
#[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
self.as_slice().index(index)
}
}
impl<T> ops::Index<ops::FullRange, [T]> for Vec<T> {
impl<T> ops::Index<ops::FullRange> for Vec<T> {
type Output = [T];
#[inline]
fn index(&self, _index: &ops::FullRange) -> &[T] {
self.as_slice()
}
}
impl<T> ops::IndexMut<ops::Range<uint>, [T]> for Vec<T> {
impl<T> ops::IndexMut<ops::Range<uint>> for Vec<T> {
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
self.as_mut_slice().index_mut(index)
}
}
impl<T> ops::IndexMut<ops::RangeTo<uint>, [T]> for Vec<T> {
impl<T> ops::IndexMut<ops::RangeTo<uint>> for Vec<T> {
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
self.as_mut_slice().index_mut(index)
}
}
impl<T> ops::IndexMut<ops::RangeFrom<uint>, [T]> for Vec<T> {
impl<T> ops::IndexMut<ops::RangeFrom<uint>> for Vec<T> {
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
self.as_mut_slice().index_mut(index)
}
}
impl<T> ops::IndexMut<ops::FullRange, [T]> for Vec<T> {
impl<T> ops::IndexMut<ops::FullRange> for Vec<T> {
type Output = [T];
#[inline]
fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] {
self.as_mut_slice()
}
}
#[stable]
impl<T> ops::Deref for Vec<T> {
type Target = [T];
@ -1795,6 +1799,7 @@ mod tests {
use prelude::*;
use core::mem::size_of;
use core::iter::repeat;
use core::ops::FullRange;
use test::Bencher;
use super::as_vec;
@ -1932,7 +1937,7 @@ mod tests {
let (left, right) = values.split_at_mut(2);
{
let left: &[_] = left;
assert!(left[0..left.len()] == [1, 2][]);
assert!(&left[..left.len()] == &[1, 2][]);
}
for p in left.iter_mut() {
*p += 1;
@ -1940,7 +1945,7 @@ mod tests {
{
let right: &[_] = right;
assert!(right[0..right.len()] == [3, 4, 5][]);
assert!(&right[..right.len()] == &[3, 4, 5][]);
}
for p in right.iter_mut() {
*p += 2;
@ -2111,35 +2116,35 @@ mod tests {
#[should_fail]
fn test_slice_out_of_bounds_1() {
let x: Vec<int> = vec![1, 2, 3, 4, 5];
x[-1..];
&x[(-1)..];
}
#[test]
#[should_fail]
fn test_slice_out_of_bounds_2() {
let x: Vec<int> = vec![1, 2, 3, 4, 5];
x.index(&(0..6));
&x[..6];
}
#[test]
#[should_fail]
fn test_slice_out_of_bounds_3() {
let x: Vec<int> = vec![1, 2, 3, 4, 5];
x[-1..4];
&x[(-1)..4];
}
#[test]
#[should_fail]
fn test_slice_out_of_bounds_4() {
let x: Vec<int> = vec![1, 2, 3, 4, 5];
x.index(&(1..6));
&x[1..6];
}
#[test]
#[should_fail]
fn test_slice_out_of_bounds_5() {
let x: Vec<int> = vec![1, 2, 3, 4, 5];
x.index(&(3..2));
&x[3..2];
}
#[test]
@ -2385,7 +2390,7 @@ mod tests {
b.bytes = src_len as u64;
b.iter(|| {
let dst = src.clone().as_slice().to_vec();
let dst = src.clone()[].to_vec();
assert_eq!(dst.len(), src_len);
assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
});

View File

@ -57,9 +57,13 @@ macro_rules! array_impls {
Rhs: Deref<Target=[B]>,
{
#[inline(always)]
fn eq(&self, other: &Rhs) -> bool { PartialEq::eq(self.index(&FullRange), &**other) }
fn eq(&self, other: &Rhs) -> bool {
PartialEq::eq(self.index(&FullRange), &**other)
}
#[inline(always)]
fn ne(&self, other: &Rhs) -> bool { PartialEq::ne(self.index(&FullRange), &**other) }
fn ne(&self, other: &Rhs) -> bool {
PartialEq::ne(self.index(&FullRange), &**other)
}
}
#[stable]
@ -68,9 +72,13 @@ macro_rules! array_impls {
Lhs: Deref<Target=[A]>
{
#[inline(always)]
fn eq(&self, other: &[B; $N]) -> bool { PartialEq::eq(&**self, other.index(&FullRange)) }
fn eq(&self, other: &[B; $N]) -> bool {
PartialEq::eq(&**self, other.index(&FullRange))
}
#[inline(always)]
fn ne(&self, other: &[B; $N]) -> bool { PartialEq::ne(&**self, other.index(&FullRange)) }
fn ne(&self, other: &[B; $N]) -> bool {
PartialEq::ne(&**self, other.index(&FullRange))
}
}
#[stable]

View File

@ -521,7 +521,7 @@ impl<'a> Formatter<'a> {
let mut fill = [0u8; 4];
let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
let fill = unsafe { str::from_utf8_unchecked(fill[..len]) };
let fill = unsafe { str::from_utf8_unchecked(fill.index(&(..len))) };
for _ in range(0, pre_pad) {
try!(self.buf.write_str(fill));

View File

@ -551,78 +551,8 @@ impl<T> ops::IndexMut<uint> for [T] {
}
}
impl<T> ops::Index<ops::Range<uint>, [T]> for [T] {
#[inline]
fn index(&self, &index: &ops::Range<uint>) -> &[T] {
assert!(index.start <= index.end);
assert!(index.end <= self.len());
unsafe {
transmute(RawSlice {
data: self.as_ptr().offset(index.start as int),
len: index.end - index.start
})
}
}
}
impl<T> ops::Index<ops::RangeTo<uint>, [T]> for [T] {
#[inline]
fn index(&self, &index: &ops::RangeTo<uint>) -> &[T] {
self.index(&ops::Range{ start: 0, end: index.end })
}
}
impl<T> ops::Index<ops::RangeFrom<uint>, [T]> for [T] {
#[inline]
fn index(&self, &index: &ops::RangeFrom<uint>) -> &[T] {
self.index(&ops::Range{ start: index.start, end: self.len() })
}
}
impl<T> ops::Index<ops::FullRange, [T]> for [T] {
#[inline]
fn index(&self, &index: &ops::FullRange) -> &[T] {
self
}
}
impl<T> ops::IndexMut<ops::Range<uint>, [T]> for [T] {
#[inline]
fn index_mut(&mut self, &index: &ops::Range<uint>) -> &mut [T] {
assert!(index.start <= index.end);
assert!(index.end <= self.len());
unsafe {
transmute(RawSlice {
data: self.as_ptr().offset(index.start as int),
len: index.end - index.start
})
}
}
}
impl<T> ops::IndexMut<ops::RangeTo<uint>, [T]> for [T] {
#[inline]
fn index_mut(&mut self, &index: &ops::RangeTo<uint>) -> &mut [T] {
self.index_mut(&ops::Range{ start: 0, end: index.end })
}
}
impl<T> ops::IndexMut<ops::RangeFrom<uint>, [T]> for [T] {
#[inline]
fn index_mut(&mut self, &index: &ops::RangeFrom<uint>) -> &mut [T] {
let len = self.len();
self.index_mut(&ops::Range{ start: index.start, end: len })
}
}
impl<T> ops::IndexMut<ops::FullRange, [T]> for [T] {
#[inline]
fn index_mut(&mut self, &index: &ops::FullRange) -> &mut [T] {
self
}
}
impl<T> ops::Index<ops::Range<uint>, [T]> for [T] {
impl<T> ops::Index<ops::Range<uint>> for [T] {
type Output = [T];
#[inline]
fn index(&self, index: &ops::Range<uint>) -> &[T] {
assert!(index.start <= index.end);
@ -635,6 +565,64 @@ impl<T> ops::Index<ops::Range<uint>, [T]> for [T] {
}
}
}
impl<T> ops::Index<ops::RangeTo<uint>> for [T] {
type Output = [T];
#[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
self.index(&ops::Range{ start: 0, end: index.end })
}
}
impl<T> ops::Index<ops::RangeFrom<uint>> for [T] {
type Output = [T];
#[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
self.index(&ops::Range{ start: index.start, end: self.len() })
}
}
impl<T> ops::Index<ops::FullRange> for [T] {
type Output = [T];
#[inline]
fn index(&self, _index: &ops::FullRange) -> &[T] {
self
}
}
impl<T> ops::IndexMut<ops::Range<uint>> for [T] {
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
assert!(index.start <= index.end);
assert!(index.end <= self.len());
unsafe {
transmute(RawSlice {
data: self.as_ptr().offset(index.start as int),
len: index.end - index.start
})
}
}
}
impl<T> ops::IndexMut<ops::RangeTo<uint>> for [T] {
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
self.index_mut(&ops::Range{ start: 0, end: index.end })
}
}
impl<T> ops::IndexMut<ops::RangeFrom<uint>> for [T] {
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
let len = self.len();
self.index_mut(&ops::Range{ start: index.start, end: len })
}
}
impl<T> ops::IndexMut<ops::FullRange> for [T] {
type Output = [T];
#[inline]
fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] {
self
}
}
////////////////////////////////////////////////////////////////////////////////
@ -767,7 +755,8 @@ pub struct Iter<'a, T: 'a> {
}
#[experimental]
impl<'a, T> ops::Index<ops::Range<uint>, [T]> for Iter<'a, T> {
impl<'a, T> ops::Index<ops::Range<uint>> for Iter<'a, T> {
type Output = [T];
#[inline]
fn index(&self, index: &ops::Range<uint>) -> &[T] {
self.as_slice().index(index)
@ -775,7 +764,8 @@ impl<'a, T> ops::Index<ops::Range<uint>, [T]> for Iter<'a, T> {
}
#[experimental]
impl<'a, T> ops::Index<ops::RangeTo<uint>, [T]> for Iter<'a, T> {
impl<'a, T> ops::Index<ops::RangeTo<uint>> for Iter<'a, T> {
type Output = [T];
#[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
self.as_slice().index(index)
@ -783,7 +773,8 @@ impl<'a, T> ops::Index<ops::RangeTo<uint>, [T]> for Iter<'a, T> {
}
#[experimental]
impl<'a, T> ops::Index<ops::RangeFrom<uint>, [T]> for Iter<'a, T> {
impl<'a, T> ops::Index<ops::RangeFrom<uint>> for Iter<'a, T> {
type Output = [T];
#[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
self.as_slice().index(index)
@ -791,14 +782,14 @@ impl<'a, T> ops::Index<ops::RangeFrom<uint>, [T]> for Iter<'a, T> {
}
#[experimental]
impl<'a, T> ops::Index<ops::FullRange, [T]> for Iter<'a, T> {
impl<'a, T> ops::Index<ops::FullRange> for Iter<'a, T> {
type Output = [T];
#[inline]
fn index(&self, _index: &ops::FullRange) -> &[T] {
self.as_slice()
}
}
impl<'a, T> Iter<'a, T> {
/// View the underlying data as a subslice of the original data.
///
@ -855,32 +846,34 @@ pub struct IterMut<'a, T: 'a> {
marker: marker::ContravariantLifetime<'a>,
}
#[experimental]
impl<'a, T> ops::Index<ops::Range<uint>, [T]> for IterMut<'a, T> {
impl<'a, T> ops::Index<ops::Range<uint>> for IterMut<'a, T> {
type Output = [T];
#[inline]
fn index(&self, index: &ops::Range<uint>) -> &[T] {
self.index(&ops::FullRange).index(index)
}
}
#[experimental]
impl<'a, T> ops::Index<ops::RangeTo<uint>, [T]> for IterMut<'a, T> {
impl<'a, T> ops::Index<ops::RangeTo<uint>> for IterMut<'a, T> {
type Output = [T];
#[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
self.index(&ops::FullRange).index(index)
}
}
#[experimental]
impl<'a, T> ops::Index<ops::RangeFrom<uint>, [T]> for IterMut<'a, T> {
impl<'a, T> ops::Index<ops::RangeFrom<uint>> for IterMut<'a, T> {
type Output = [T];
#[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
self.index(&ops::FullRange).index(index)
}
}
#[experimental]
impl<'a, T> ops::Index<ops::FullRange, [T]> for IterMut<'a, T> {
impl<'a, T> ops::Index<ops::FullRange> for IterMut<'a, T> {
type Output = [T];
#[inline]
fn index(&self, _index: &ops::FullRange) -> &[T] {
make_slice!(T -> &[T]: self.ptr, self.end)
@ -888,31 +881,32 @@ impl<'a, T> ops::Index<ops::FullRange, [T]> for IterMut<'a, T> {
}
#[experimental]
impl<'a, T> ops::IndexMut<ops::Range<uint>, [T]> for IterMut<'a, T> {
impl<'a, T> ops::IndexMut<ops::Range<uint>> for IterMut<'a, T> {
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
self.index_mut(&ops::FullRange).index_mut(index)
}
}
#[experimental]
impl<'a, T> ops::IndexMut<ops::RangeTo<uint>, [T]> for IterMut<'a, T> {
impl<'a, T> ops::IndexMut<ops::RangeTo<uint>> for IterMut<'a, T> {
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
self.index_mut(&ops::FullRange).index_mut(index)
}
}
#[experimental]
impl<'a, T> ops::IndexMut<ops::RangeFrom<uint>, [T]> for IterMut<'a, T> {
impl<'a, T> ops::IndexMut<ops::RangeFrom<uint>> for IterMut<'a, T> {
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
self.index_mut(&ops::FullRange).index_mut(index)
}
}
#[experimental]
impl<'a, T> ops::IndexMut<ops::FullRange, [T]> for IterMut<'a, T> {
impl<'a, T> ops::IndexMut<ops::FullRange> for IterMut<'a, T> {
type Output = [T];
#[inline]
fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] {
make_slice!(T -> &mut [T]: self.ptr, self.end)

View File

@ -1119,28 +1119,29 @@ mod traits {
}
}
impl ops::Index<ops::Range<uint>, str> for str {
impl ops::Index<ops::Range<uint>> for str {
type Output = str;
#[inline]
fn index(&self, index: &ops::Range<uint>) -> &str {
self.slice(index.start, index.end)
}
}
impl ops::Index<ops::RangeTo<uint>, str> for str {
impl ops::Index<ops::RangeTo<uint>> for str {
type Output = str;
#[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &str {
self.slice_to(index.end)
}
}
impl ops::Index<ops::RangeFrom<uint>, str> for str {
impl ops::Index<ops::RangeFrom<uint>> for str {
type Output = str;
#[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &str {
self.slice_from(index.start)
}
}
impl ops::Index<ops::FullRange, str> for str {
impl ops::Index<ops::FullRange> for str {
type Output = str;
#[inline]
fn index(&self, _index: &ops::FullRange) -> &str {
self

View File

@ -14,7 +14,6 @@ use core::iter::MinMaxResult::*;
use core::num::SignedInt;
use core::uint;
use core::cmp;
use core::ops::Slice;
use test::Bencher;
@ -230,7 +229,7 @@ fn test_inspect() {
.collect::<Vec<uint>>();
assert_eq!(n, xs.len());
assert_eq!(xs.index(&FullRange), ys.index(&FullRange));
assert_eq!(&xs[], &ys[]);
}
#[test]
@ -281,47 +280,47 @@ fn test_iterator_nth() {
fn test_iterator_last() {
let v: &[_] = &[0i, 1, 2, 3, 4];
assert_eq!(v.iter().last().unwrap(), &4);
assert_eq!(v.index(&(0..1)).iter().last().unwrap(), &0);
assert_eq!(v[..1].iter().last().unwrap(), &0);
}
#[test]
fn test_iterator_len() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.index(&(0..4)).iter().count(), 4);
assert_eq!(v.index(&(0..10)).iter().count(), 10);
assert_eq!(v.index(&(0..0)).iter().count(), 0);
assert_eq!(v[..4].iter().count(), 4);
assert_eq!(v[..10].iter().count(), 10);
assert_eq!(v[0..0].iter().count(), 0);
}
#[test]
fn test_iterator_sum() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.index(&(0..4)).iter().map(|&x| x).sum(), 6);
assert_eq!(v[..4].iter().map(|&x| x).sum(), 6);
assert_eq!(v.iter().map(|&x| x).sum(), 55);
assert_eq!(v.index(&(0..0)).iter().map(|&x| x).sum(), 0);
assert_eq!(v[0..0].iter().map(|&x| x).sum(), 0);
}
#[test]
fn test_iterator_product() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.index(&(0..4)).iter().map(|&x| x).product(), 0);
assert_eq!(v.index(&(1..5)).iter().map(|&x| x).product(), 24);
assert_eq!(v.index(&(0..0)).iter().map(|&x| x).product(), 1);
assert_eq!(v[0..4].iter().map(|&x| x).product(), 0);
assert_eq!(v[1..5].iter().map(|&x| x).product(), 24);
assert_eq!(v[0..0].iter().map(|&x| x).product(), 1);
}
#[test]
fn test_iterator_max() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.index(&(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.index(&(0..0)).iter().map(|&x| x).max(), None);
assert_eq!(v[0..0].iter().map(|&x| x).max(), None);
}
#[test]
fn test_iterator_min() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.index(&(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.index(&(0..0)).iter().map(|&x| x).min(), None);
assert_eq!(v[0..0].iter().map(|&x| x).min(), None);
}
#[test]
@ -374,7 +373,7 @@ fn test_all() {
assert!(v.iter().all(|&x| x < 10));
assert!(!v.iter().all(|&x| x % 2 == 0));
assert!(!v.iter().all(|&x| x > 100));
assert!(v.slice_or_fail(&0, &0).iter().all(|_| panic!()));
assert!(v[0..0].iter().all(|_| panic!()));
}
#[test]
@ -383,7 +382,7 @@ fn test_any() {
assert!(v.iter().any(|&x| x < 10));
assert!(v.iter().any(|&x| x % 2 == 0));
assert!(!v.iter().any(|&x| x > 100));
assert!(!v.slice_or_fail(&0, &0).iter().any(|_| panic!()));
assert!(!v[0..0].iter().any(|_| panic!()));
}
#[test]
@ -586,7 +585,7 @@ fn check_randacc_iter<A, T>(a: T, len: uint) where
fn test_double_ended_flat_map() {
let u = [0u,1];
let v = [5u,6,7,8];
let mut it = u.iter().flat_map(|x| v[*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().unwrap(), &5);
assert_eq!(it.next_back().unwrap(), &7);

View File

@ -43,35 +43,35 @@ fn iterator_to_slice() {
{
let mut iter = data.iter();
assert_eq!(iter.index(&FullRange), other_data.index(&FullRange));
assert_eq!(&iter[], &other_data[]);
iter.next();
assert_eq!(iter.index(&FullRange), other_data.index(&(1..)));
assert_eq!(&iter[], &other_data[1..]);
iter.next_back();
assert_eq!(iter.index(&FullRange), other_data.index(&(1..2)));
assert_eq!(&iter[], &other_data[1..2]);
let s = iter.as_slice();
iter.next();
assert_eq!(s, other_data.index(&(1..2)));
assert_eq!(s, &other_data[1..2]);
}
{
let mut iter = data.iter_mut();
assert_eq!(iter.index(&FullRange), other_data.index(&FullRange));
// mutability:
assert!(iter[mut] == other_data);
assert!(&mut iter[] == other_data);
iter.next();
assert_eq!(iter.index(&FullRange), other_data.index(&(1..)));
assert!(iter[mut] == other_data[mut 1..]);
assert!(&mut iter[] == &mut other_data[1..]);
iter.next_back();
assert_eq!(iter.index(&FullRange), other_data.index(&(1..2)));
assert!(iter[mut] == other_data[mut 1..2]);
assert!(&mut iter[] == &mut other_data[1..2]);
let s = iter.into_slice();
assert!(s == other_data[mut 1..2]);
assert!(s == &mut other_data[1..2]);
}
}}
}

View File

@ -1413,7 +1413,7 @@ mod tests {
assert!(matches_single.opts_present(&["e".to_string(), "encrypt".to_string()]));
assert!(!matches_single.opts_present(&["encrypt".to_string()]));
assert!(!matches_single.opts_present(&["thing".to_string()]));
assert!(!matches_single.opts_present(&.index(&FullRange)));
assert!(!matches_single.opts_present(&[]));
assert_eq!(matches_single.opts_str(&["e".to_string()]).unwrap(), "foo");
assert_eq!(matches_single.opts_str(&["e".to_string(), "encrypt".to_string()]).unwrap(),
@ -1434,7 +1434,7 @@ mod tests {
assert!(matches_both.opts_present(&["e".to_string(), "encrypt".to_string()]));
assert!(!matches_both.opts_present(&["f".to_string()]));
assert!(!matches_both.opts_present(&["thing".to_string()]));
assert!(!matches_both.opts_present(&.index(&FullRange)));
assert!(!matches_both.opts_present(&[]));
assert_eq!(matches_both.opts_str(&["e".to_string()]).unwrap(), "foo");
assert_eq!(matches_both.opts_str(&["encrypt".to_string()]).unwrap(), "foo");

View File

@ -24,7 +24,7 @@ use core::num::{Float, Int};
use {Rng, Rand};
pub use self::range::Range as RandRange;
pub use self::range::Range;
pub use self::gamma::{Gamma, ChiSquared, FisherF, StudentT};
pub use self::normal::{Normal, LogNormal};
pub use self::exponential::Exp;
@ -104,7 +104,7 @@ pub struct Weighted<T> {
/// ```
pub struct WeightedChoice<'a, T:'a> {
items: &'a mut [Weighted<T>],
weight_range: RandRange<uint>
weight_range: Range<uint>
}
impl<'a, T: Clone> WeightedChoice<'a, T> {
@ -138,7 +138,7 @@ impl<'a, T: Clone> WeightedChoice<'a, T> {
items: items,
// we're likely to be generating numbers in this range
// relatively often, so might as well cache it
weight_range: RandRange::new(0, running_total)
weight_range: Range::new(0, running_total)
}
}
}

View File

@ -166,7 +166,7 @@ mod tests {
use std::num::Int;
use std::prelude::v1::*;
use distributions::{Sample, IndependentSample};
use super::Range;
use super::Range as Range;
#[should_fail]
#[test]

View File

@ -58,7 +58,7 @@ use core::prelude::*;
pub use isaac::{IsaacRng, Isaac64Rng};
pub use chacha::ChaChaRng;
use distributions::{RandRange, IndependentSample};
use distributions::{Range, IndependentSample};
use distributions::range::SampleRange;
#[cfg(test)]
@ -247,7 +247,7 @@ pub trait Rng : Sized {
/// ```
fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
assert!(low < high, "Rng.gen_range called with low >= high");
RandRange::new(low, high).ind_sample(self)
Range::new(low, high).ind_sample(self)
}
/// Return a bool with a 1 in n chance of true
@ -290,8 +290,8 @@ pub trait Rng : Sized {
/// let choices = [1i, 2, 4, 8, 16, 32];
/// let mut rng = thread_rng();
/// println!("{}", rng.choose(&choices));
/// # // replace with slicing syntax when it's stable!
/// assert_eq!(rng.choose(choices.index(&(0..0))), None);
/// # // uncomment when slicing syntax is stable
/// //assert_eq!(rng.choose(choices.index(&(0..0))), None);
/// ```
fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
if values.is_empty() {

View File

@ -121,7 +121,7 @@ mat!{match_basic_110, r"a[b-d]", r"aac", Some((1, 3))}
mat!{match_basic_111, r"a[-b]", r"a-", Some((0, 2))}
mat!{match_basic_112, r"a[b-]", r"a-", Some((0, 2))}
mat!{match_basic_113, r"a]", r"a]", Some((0, 2))}
mat!{match_basic_114, r"a.index(&FullRange)]b", r"a]b", Some((0, 3))}
mat!{match_basic_114, r"a[]]b", r"a]b", Some((0, 3))}
mat!{match_basic_115, r"a[^bc]d", r"aed", Some((0, 3))}
mat!{match_basic_116, r"a[^-b]c", r"adc", Some((0, 3))}
mat!{match_basic_117, r"a[^]b]c", r"adc", Some((0, 3))}

View File

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

View File

@ -499,7 +499,7 @@ impl<'a, 'tcx> Context<'a, 'tcx> {
None => {
self.span_lint(builtin::UNKNOWN_LINTS, span,
format!("unknown `{}` attribute: `{}`",
level.as_str(), lint_name).index(&FullRange));
level.as_str(), lint_name).as_slice());
continue;
}
}
@ -791,7 +791,7 @@ pub fn check_crate(tcx: &ty::ctxt,
for &(lint, span, ref msg) in v.iter() {
tcx.sess.span_bug(span,
format!("unprocessed lint {} at {}: {}",
lint.as_str(), tcx.map.node_to_string(*id), *msg).index(&FullRange))
lint.as_str(), tcx.map.node_to_string(*id), *msg).as_slice())
}
}

View File

@ -209,7 +209,7 @@ impl<'a> CrateReader<'a> {
let name = match *path_opt {
Some((ref path_str, _)) => {
let name = path_str.get().to_string();
validate_crate_name(Some(self.sess), name[],
validate_crate_name(Some(self.sess), name.index(&FullRange),
Some(i.span));
name
}
@ -276,7 +276,7 @@ impl<'a> CrateReader<'a> {
} else {
self.sess.span_err(m.span,
format!("unknown kind: `{}`",
k)[]);
k).index(&FullRange));
cstore::NativeUnknown
}
}
@ -330,7 +330,7 @@ impl<'a> CrateReader<'a> {
match self.sess.opts.externs.get(name) {
Some(locs) => {
let found = locs.iter().any(|l| {
let l = fs::realpath(&Path::new(l[])).ok();
let l = fs::realpath(&Path::new(l.index(&FullRange))).ok();
l == source.dylib || l == source.rlib
});
if found {
@ -409,7 +409,7 @@ impl<'a> CrateReader<'a> {
crate_name: name,
hash: hash.map(|a| &*a),
filesearch: self.sess.target_filesearch(kind),
triple: self.sess.opts.target_triple[],
triple: self.sess.opts.target_triple.index(&FullRange),
root: root,
rejected_via_hash: vec!(),
rejected_via_triple: vec!(),

View File

@ -1826,10 +1826,10 @@ fn encode_macro_defs(rbml_w: &mut Encoder,
rbml_w.start_tag(tag_macro_def);
encode_name(rbml_w, def.ident.name);
encode_attributes(rbml_w, def.attrs[]);
encode_attributes(rbml_w, def.attrs.index(&FullRange));
rbml_w.start_tag(tag_macro_def_body);
rbml_w.wr_str(pprust::tts_to_string(def.body[])[]);
rbml_w.wr_str(pprust::tts_to_string(def.body.index(&FullRange)).index(&FullRange));
rbml_w.end_tag();
rbml_w.end_tag();

View File

@ -624,7 +624,8 @@ impl<'a> Context<'a> {
return true
} else {
let (ref prefix, ref suffix) = dylibname;
if file.starts_with(prefix.index(&FullRange)) && file.ends_with(suffix.index(&FullRange)) {
if file.starts_with(prefix.index(&FullRange)) &&
file.ends_with(suffix.index(&FullRange)) {
return true
}
}

View File

@ -85,7 +85,9 @@ impl<'a, 'ast> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a, 'ast> {
let s = self.ast_map.node_to_string(node_id);
// left-aligns the lines
let s = replace_newline_with_backslash_l(s);
label.push_str(format!("exiting scope_{} {}", i, s.index(&FullRange)).index(&FullRange));
label.push_str(format!("exiting scope_{} {}",
i,
s.index(&FullRange)).index(&FullRange));
}
dot::LabelText::EscStr(label.into_cow())
}

View File

@ -165,6 +165,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &ast::Expr) {
ast::ExprParen(..) |
ast::ExprField(..) |
ast::ExprTupField(..) |
ast::ExprIndex(..) |
ast::ExprTup(..) |
ast::ExprRepeat(..) |
ast::ExprStruct(..) => {}

View File

@ -1158,7 +1158,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> {
let msg = format!("Pattern has unexpected type: {} and type {}",
def,
cmt_pat.ty.repr(tcx));
tcx.sess.span_bug(pat.span, msg[])
tcx.sess.span_bug(pat.span, msg.as_slice())
}
}

View File

@ -495,7 +495,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> {
ret_ty), 1, true)
}
None => {
self.cat_index(expr, self.cat_expr(&**base))
self.cat_index(expr, try!(self.cat_expr(&**base)))
}
}
}
@ -1497,7 +1497,7 @@ impl<'tcx> Repr<'tcx> for InteriorKind {
token::get_name(fld).get().to_string()
}
InteriorField(PositionalField(i)) => format!("#{}", i),
InteriorElement(_) => ".index(&FullRange)".to_string(),
InteriorElement(_) => "[]".to_string(),
}
}
}

View File

@ -378,7 +378,7 @@ pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
span,
format!("overflow evaluating whether `{}` is `{}`",
ty.user_string(infcx.tcx),
bound.user_string(infcx.tcx))[]);
bound.user_string(infcx.tcx)).as_slice());
suggest_new_overflow_limit(infcx.tcx, span);
false
}

View File

@ -178,7 +178,7 @@ fn object_safety_violations_for_method<'tcx>(tcx: &ty::ctxt<'tcx>,
// The `Self` type is erased, so it should not appear in list of
// arguments or return type apart from the receiver.
let ref sig = method.fty.sig;
for &input_ty in sig.0.inputs[1..].iter() {
for &input_ty in sig.0.inputs.index(&(1..)).iter() {
if contains_illegal_self_type_reference(tcx, trait_def_id, input_ty) {
return Some(MethodViolationCode::ReferencesSelf);
}

View File

@ -490,7 +490,7 @@ fn assemble_candidates_from_object_type<'cx,'tcx>(
selcx.tcx().sess.span_bug(
obligation.cause.span,
format!("assemble_candidates_from_object_type called with non-object: {}",
object_ty.repr(selcx.tcx()))[]);
object_ty.repr(selcx.tcx())).as_slice());
}
};
let projection_bounds = data.projection_bounds_with_self_ty(selcx.tcx(), object_ty);

View File

@ -3654,7 +3654,8 @@ pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool {
ty_unboxed_closure(..) => {
// this check is run on type definitions, so we don't expect to see
// inference by-products or unboxed closure types
cx.sess.bug(format!("requires check invoked on inapplicable type: {}", ty)[])
cx.sess.bug(format!("requires check invoked on inapplicable type: {}",
ty).as_slice())
}
ty_tup(ref ts) => {
@ -3747,7 +3748,8 @@ pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>)
ty_unboxed_closure(..) => {
// this check is run on type definitions, so we don't expect to see
// unboxed closure types
cx.sess.bug(format!("requires check invoked on inapplicable type: {}", ty)[])
cx.sess.bug(format!("requires check invoked on inapplicable type: {}",
ty).as_slice())
}
_ => Representable,
}

View File

@ -639,7 +639,7 @@ pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config {
let target = match Target::search(opts.target_triple.index(&FullRange)) {
Ok(t) => t,
Err(e) => {
sp.handler().fatal((format!("Error loading target specification: {}", e)).index(&FullRange));
sp.handler().fatal((format!("Error loading target specification: {}", e)).as_slice());
}
};
@ -1027,7 +1027,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
s => {
early_error(format!("unknown library kind `{}`, expected \
one of dylib, framework, or static",
s)[]);
s).as_slice());
}
};
return (name.to_string(), kind)

View File

@ -247,7 +247,9 @@ impl Target {
} );
($key_name:ident, bool) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(name.index(&FullRange)).map(|o| o.as_boolean().map(|s| base.options.$key_name = s));
obj.find(name.index(&FullRange))
.map(|o| o.as_boolean()
.map(|s| base.options.$key_name = s));
} );
($key_name:ident, list) => ( {
let name = (stringify!($key_name)).replace("_", "-");

View File

@ -138,7 +138,7 @@
//! - `FREEZE` means that the `LV` cannot be borrowed immutably;
//!
//! Finally, it is never possible to move from an lvalue that appears in a
//! restriction. This implies that the "empty restriction" `(LV, .index(&FullRange))`,
//! restriction. This implies that the "empty restriction" `(LV, [])`,
//! which contains an empty set of actions, still has a purpose---it
//! prevents moves from `LV`. I chose not to make `MOVE` a fourth kind of
//! action because that would imply that sometimes moves are permitted
@ -476,7 +476,7 @@
//! ```text
//! &mut LV => RESTRICTIONS(LV, LT, MUTATE|CLAIM|FREEZE)
//! &LV => RESTRICTIONS(LV, LT, MUTATE|CLAIM)
//! &const LV => RESTRICTIONS(LV, LT, .index(&FullRange))
//! &const LV => RESTRICTIONS(LV, LT, [])
//! ```
//!
//! The reasoning here is that a mutable borrow must be the only writer,
@ -542,7 +542,7 @@
//! restricting `MUTATE` and `CLAIM` actions:
//!
//! ```text
//! RESTRICTIONS(*LV, LT, ACTIONS) = .index(&FullRange) // R-Deref-Imm-Borrowed
//! RESTRICTIONS(*LV, LT, ACTIONS) = [] // R-Deref-Imm-Borrowed
//! TYPE(LV) = &LT' Ty
//! LT <= LT' // (1)
//! ACTIONS subset of [MUTATE, CLAIM]
@ -660,7 +660,7 @@
//! necessary to add any restrictions at all to the final result.
//!
//! ```text
//! RESTRICTIONS(*LV, LT, .index(&FullRange)) = .index(&FullRange) // R-Deref-Freeze-Borrowed
//! RESTRICTIONS(*LV, LT, []) = [] // R-Deref-Freeze-Borrowed
//! TYPE(LV) = &const Ty
//! ```
//!

View File

@ -804,7 +804,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
mc::AliasableClosure(id) => {
self.tcx.sess.span_err(span,
format!("{} in a captured outer \
variable in an `Fn` closure", prefix).index(&FullRange));
variable in an `Fn` closure", prefix).as_slice());
span_help!(self.tcx.sess, self.tcx.map.span(id),
"consider changing this closure to take self by mutable reference");
}

View File

@ -3763,13 +3763,13 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
self.resolve_error(path.span,
format!("`{}` is not an enum variant, struct or const",
token::get_ident(
path.segments.last().unwrap().identifier)).index(&FullRange));
path.segments.last().unwrap().identifier)).as_slice());
}
None => {
self.resolve_error(path.span,
format!("unresolved enum variant, struct or const `{}`",
token::get_ident(
path.segments.last().unwrap().identifier)).index(&FullRange));
path.segments.last().unwrap().identifier)).as_slice());
}
}

View File

@ -608,7 +608,7 @@ fn link_rlib<'a>(sess: &'a Session,
// extension to it. This is to work around a bug in LLDB that
// would cause it to crash if the name of a file in an archive
// was exactly 16 bytes.
let bc_filename = obj_filename.with_extension(format!("{}.bc", i).index(&FullRange));
let bc_filename = obj_filename.with_extension(format!("{}.bc", i).as_slice());
let bc_deflated_filename = obj_filename.with_extension(
format!("{}.bytecode.deflate", i).index(&FullRange));
@ -1083,8 +1083,8 @@ fn add_local_native_libraries(cmd: &mut Command, sess: &Session) {
// -force_load is the OSX equivalent of --whole-archive, but it
// involves passing the full path to the library to link.
let lib = archive::find_library(l.index(&FullRange),
sess.target.target.options.staticlib_prefix.index(&FullRange),
sess.target.target.options.staticlib_suffix.index(&FullRange),
sess.target.target.options.staticlib_prefix.as_slice(),
sess.target.target.options.staticlib_suffix.as_slice(),
search_path.index(&FullRange),
&sess.diagnostic().handler);
let mut v = b"-Wl,-force_load,".to_vec();

View File

@ -64,7 +64,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef,
debug!("reading {}", file);
for i in iter::count(0u, 1) {
let bc_encoded = time(sess.time_passes(),
format!("check for {}.{}.bytecode.deflate", name, i).index(&FullRange),
format!("check for {}.{}.bytecode.deflate", name, i).as_slice(),
(),
|_| {
archive.read(format!("{}.{}.bytecode.deflate",

View File

@ -381,8 +381,8 @@ unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_vo
cgcx.handler.note(format!("optimization {} for {} at {}: {}",
opt.kind.describe(),
pass_name,
if loc.is_empty() { "[unknown]" } else { loc.index(&FullRange) },
llvm::twine_to_string(opt.message)).index(&FullRange));
if loc.is_empty() { "[unknown]" } else { loc.as_slice() },
llvm::twine_to_string(opt.message)).as_slice());
}
}

View File

@ -292,7 +292,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
Some(def_id) => {
result.push_str(" as ");
result.push_str(
ty::item_path_str(&self.analysis.ty_cx, def_id).index(&FullRange));
ty::item_path_str(&self.analysis.ty_cx, def_id).as_slice());
},
None => {}
}
@ -636,7 +636,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
item.id);
for field in struct_def.fields.iter() {
self.process_struct_field_def(field, qualname.index(&FullRange), variant.node.id);
self.process_struct_field_def(field, qualname.as_slice(), variant.node.id);
self.visit_ty(&*field.node.ty);
}
}
@ -774,7 +774,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
let def_map = self.analysis.ty_cx.def_map.borrow();
if !def_map.contains_key(&id) {
self.sess.span_bug(span,
format!("def_map has no key for {} in visit_expr", id).index(&FullRange));
format!("def_map has no key for {} in visit_expr", id).as_slice());
}
let def = &(*def_map)[id];
let sub_span = self.span.span_for_last_ident(span);
@ -1065,7 +1065,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> {
value.index(&FullRange));
self.visit_ty(&**ty);
self.process_generic_params(ty_params, item.span, qualname.index(&FullRange), item.id);
self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
},
ast::ItemMac(_) => (),
_ => visit::walk_item(self, item),
@ -1418,7 +1418,8 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> {
let def_map = self.analysis.ty_cx.def_map.borrow();
if !def_map.contains_key(&id) {
self.sess.span_bug(p.span,
format!("def_map has no key for {} in visit_arm", id).index(&FullRange));
format!("def_map has no key for {} in visit_arm",
id).index(&FullRange));
}
let def = &(*def_map)[id];
match *def {

View File

@ -237,7 +237,7 @@ impl<'a> FmtStrs<'a> {
if !needs_span {
self.span.sess.span_bug(span,
format!("Called record_with_span for '{}' \
which does not require a span", label).index(&FullRange));
which does not require a span", label).as_slice());
}
let values_str = match self.make_values_str(label, fields, values, span) {

View File

@ -1037,8 +1037,8 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
field_vals.len())
);
let mut vals = field_vals;
vals.push_all(vals_left.index(&FullRange));
compile_submatch(bcx, pats.index(&FullRange), vals.index(&FullRange), chk, has_genuine_default);
vals.push_all(vals_left.as_slice());
compile_submatch(bcx, pats.as_slice(), vals.as_slice(), chk, has_genuine_default);
return;
}
_ => ()

View File

@ -2239,7 +2239,7 @@ pub fn update_linkage(ccx: &CrateContext,
if let Some(id) = id {
let item = ccx.tcx().map.get(id);
if let ast_map::NodeItem(i) = item {
if let Some(name) = attr::first_attr_value_str_by_name(i.attrs.index(&FullRange), "linkage") {
if let Some(name) = attr::first_attr_value_str_by_name(i.attrs.as_slice(), "linkage") {
if let Some(linkage) = llvm_linkage_by_name(name.get()) {
llvm::SetLinkage(llval, linkage);
} else {
@ -2597,7 +2597,11 @@ pub fn register_fn_llvmty(ccx: &CrateContext,
llfty: Type) -> ValueRef {
debug!("register_fn_llvmty id={} sym={}", node_id, sym);
let llfn = decl_fn(ccx, sym.index(&FullRange), cc, llfty, ty::FnConverging(ty::mk_nil(ccx.tcx())));
let llfn = decl_fn(ccx,
sym.index(&FullRange),
cc,
llfty,
ty::FnConverging(ty::mk_nil(ccx.tcx())));
finish_register_fn(ccx, sp, sym, node_id, llfn);
llfn
}

View File

@ -414,7 +414,7 @@ impl<'tcx> TypeMap<'tcx> {
unique_type_id.push_str(format!("[{}]", len).index(&FullRange));
}
None => {
unique_type_id.push_str(".index(&FullRange)");
unique_type_id.push_str("[]");
}
};

View File

@ -1369,13 +1369,13 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
let tcx = bcx.tcx();
with_field_tys(tcx, ty, Some(expr_id), |discr, field_tys| {
let mut need_base: Vec<_> = repeat(true).take(field_tys.len()).collect();
let mut need_base: Vec<bool> = repeat(true).take(field_tys.len()).collect();
let numbered_fields = fields.iter().map(|field| {
let opt_pos =
field_tys.iter().position(|field_ty|
field_ty.name == field.ident.node.name);
match opt_pos {
let result = match opt_pos {
Some(i) => {
need_base[i] = false;
(i, &*field.expr)
@ -1384,14 +1384,15 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
tcx.sess.span_bug(field.span,
"Couldn't find field in struct type")
}
}
};
result
}).collect::<Vec<_>>();
let optbase = match base {
Some(base_expr) => {
let mut leftovers = Vec::new();
for (i, b) in need_base.iter().enumerate() {
if *b {
leftovers.push((i, field_tys[i].mt.ty))
leftovers.push((i, field_tys[i].mt.ty));
}
}
Some(StructBaseInfo {expr: base_expr,
@ -1408,7 +1409,7 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
trans_adt(bcx,
ty,
discr,
numbered_fields.index(&FullRange),
numbered_fields.as_slice(),
optbase,
dest,
Some(NodeInfo { id: expr_id, span: expr_span }))

View File

@ -748,7 +748,7 @@ pub fn trans_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
debug!("calling llrustfn = {}, t = {}",
ccx.tn().val_to_string(llrustfn), t.repr(ccx.tcx()));
let attributes = base::get_fn_llvm_attributes(ccx, t);
let llrust_ret_val = builder.call(llrustfn, llrust_args.index(&FullRange), Some(attributes));
let llrust_ret_val = builder.call(llrustfn, llrust_args.as_slice(), Some(attributes));
// Get the return value where the foreign fn expects it.
let llforeign_ret_ty = match tys.fn_ty.ret_ty.cast {
@ -869,7 +869,7 @@ fn foreign_types_for_fn_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
ty.repr(ccx.tcx()),
ccx.tn().types_to_str(llsig.llarg_tys.index(&FullRange)),
ccx.tn().type_to_string(llsig.llret_ty),
ccx.tn().types_to_str(fn_ty.arg_tys.iter().map(|t| t.ty).collect::<Vec<_>>().index(&FullRange)),
ccx.tn().types_to_str(fn_ty.arg_tys.iter().map(|t| t.ty).collect::<Vec<_>>().as_slice()),
ccx.tn().type_to_string(fn_ty.ret_ty.ty),
llsig.ret_def);

View File

@ -556,7 +556,8 @@ pub fn instantiate_trait_ref<'tcx>(
_ => {
this.tcx().sess.span_fatal(
ast_trait_ref.path.span,
format!("`{}` is not a trait", ast_trait_ref.path.user_string(this.tcx())).index(&FullRange));
format!("`{}` is not a trait",
ast_trait_ref.path.user_string(this.tcx())).index(&FullRange));
}
}
}
@ -1069,8 +1070,12 @@ pub fn ast_ty_to_ty<'tcx>(
ast::TyObjectSum(ref ty, ref bounds) => {
match ast_ty_to_trait_ref(this, rscope, &**ty, bounds.index(&FullRange)) {
Ok((trait_ref, projection_bounds)) => {
trait_ref_to_object_type(this, rscope, ast_ty.span,
trait_ref, projection_bounds, bounds.index(&FullRange))
trait_ref_to_object_type(this,
rscope,
ast_ty.span,
trait_ref,
projection_bounds,
bounds.index(&FullRange))
}
Err(ErrorReported) => {
this.tcx().types.err

View File

@ -195,7 +195,7 @@ fn confirm_builtin_call<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
let arg_exprs: Vec<_> = arg_exprs.iter().collect(); // for some weird reason we take &[&P<...>].
check_argument_types(fcx,
call_expr.span,
fn_sig.inputs[],
fn_sig.inputs.as_slice(),
arg_exprs.as_slice(),
AutorefArgs::No,
fn_sig.variadic,

View File

@ -563,7 +563,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> {
&**base_expr,
Some(&ty::AdjustDerefRef(base_adjustment.clone())));
let index_expr_ty = self.fcx.expr_ty(&**index_expr);
let result = check::try_index_step(
self.fcx,
MethodCall::expr(expr.id),
@ -640,7 +640,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> {
self.span,
format!("cannot upcast `{}` to `{}`",
source_trait_ref.repr(self.tcx()),
target_trait_def_id.repr(self.tcx()))[]);
target_trait_def_id.repr(self.tcx())).as_slice());
}
}
}

View File

@ -3976,7 +3976,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>,
callee::check_call(fcx, expr, &**callee, args.as_slice());
}
ast::ExprMethodCall(ident, ref tps, ref args) => {
check_method_call(fcx, expr, ident, args.index(&FullRange), tps.index(&FullRange), lvalue_pref);
check_method_call(fcx, expr, ident, args.as_slice(), tps.as_slice(), lvalue_pref);
let arg_tys = args.iter().map(|a| fcx.expr_ty(&**a));
let args_err = arg_tys.fold(false,
|rest_err, a| {

View File

@ -1318,7 +1318,7 @@ fn get_or_create_type_parameter_def<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>,
let param_ty = ty::ParamTy::new(space, index, param.ident.name);
let bounds = compute_bounds(ccx,
param_ty.to_ty(ccx.tcx),
param.bounds.index(&FullRange,
param.bounds.index(&FullRange),
SizedByDefault::Yes,
param.span);
let default = match param.default {

View File

@ -97,7 +97,7 @@ impl fmt::Show for clean::Generics {
if i > 0 {
try!(f.write_str(", "))
}
try!(f.write_str(tp.name[]));
try!(f.write_str(tp.name.as_slice()));
if tp.bounds.len() > 0 {
try!(write!(f, ": {}", TyParamBounds(tp.bounds.as_slice())));
@ -337,7 +337,7 @@ fn path<F, G>(w: &mut fmt::Formatter,
// This is a documented path, link to it!
Some((ref fqp, shortty)) if abs_root.is_some() => {
let mut url = String::from_str(abs_root.unwrap().as_slice());
let to_link = fqp[..fqp.len() - 1];
let to_link = &fqp[..(fqp.len() - 1)];
for component in to_link.iter() {
url.push_str(component.as_slice());
url.push_str("/");
@ -433,7 +433,7 @@ impl fmt::Show for clean::Type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::TyParamBinder(id) => {
f.write_str(cache().typarams[ast_util::local_def(id)][])
f.write_str(cache().typarams[ast_util::local_def(id)].as_slice())
}
clean::Generic(ref name) => {
f.write_str(name.as_slice())

View File

@ -404,7 +404,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult<String>
search_index.push(IndexItem {
ty: shortty(item),
name: item.name.clone().unwrap(),
path: fqp[..fqp.len() - 1].connect("::"),
path: fqp[..(fqp.len() - 1)].connect("::"),
desc: shorter(item.doc_value()).to_string(),
parent: Some(did),
});
@ -559,7 +559,7 @@ fn write_shared(cx: &Context,
};
let mut mydst = dst.clone();
for part in remote_path[..remote_path.len() - 1].iter() {
for part in remote_path[..(remote_path.len() - 1)].iter() {
mydst.push(part.as_slice());
try!(mkdir(&mydst));
}
@ -842,7 +842,7 @@ impl DocFolder for Cache {
clean::StructFieldItem(..) |
clean::VariantItem(..) => {
((Some(*self.parent_stack.last().unwrap()),
Some(self.stack[..self.stack.len() - 1])),
Some(&self.stack[..(self.stack.len() - 1)])),
false)
}
clean::MethodItem(..) => {
@ -853,13 +853,13 @@ impl DocFolder for Cache {
let did = *last;
let path = match self.paths.get(&did) {
Some(&(_, ItemType::Trait)) =>
Some(self.stack[..self.stack.len() - 1]),
Some(&self.stack[..(self.stack.len() - 1)]),
// The current stack not necessarily has correlation for
// where the type was defined. On the other hand,
// `paths` always has the right information if present.
Some(&(ref fqp, ItemType::Struct)) |
Some(&(ref fqp, ItemType::Enum)) =>
Some(fqp[..fqp.len() - 1]),
Some(&fqp[..(fqp.len() - 1)]),
Some(..) => Some(self.stack.as_slice()),
None => None
};
@ -1185,7 +1185,7 @@ impl Context {
.collect::<String>();
match cache().paths.get(&it.def_id) {
Some(&(ref names, _)) => {
for name in names[..names.len() - 1].iter() {
for name in (&names[..(names.len() - 1)]).iter() {
url.push_str(name.as_slice());
url.push_str("/");
}
@ -2267,7 +2267,7 @@ fn item_macro(w: &mut fmt::Formatter, it: &clean::Item,
t: &clean::Macro) -> fmt::Result {
try!(w.write_str(highlight::highlight(t.source.as_slice(),
Some("macro"),
None)[]));
None).as_slice()));
document(w, it)
}

View File

@ -1124,7 +1124,7 @@ impl Json {
}
}
impl<'a> ops::Index<&'a str> for Json {
impl<'a> Index<&'a str> for Json {
type Output = Json;
fn index(&self, idx: & &str) -> &Json {
@ -1132,7 +1132,7 @@ impl<'a> ops::Index<&'a str> for Json {
}
}
impl ops::Index<uint> for Json {
impl Index<uint> for Json {
type Output = Json;
fn index<'a>(&'a self, idx: &uint) -> &'a Json {
@ -1186,7 +1186,8 @@ pub struct Stack {
}
/// StackElements compose a Stack.
/// For example, StackElement::Key("foo"), StackElement::Key("bar"), StackElement::Index(3) and StackElement::Key("x") are the
/// For example, StackElement::Key("foo"), StackElement::Key("bar"),
/// StackElement::Index(3) and StackElement::Key("x") are the
/// StackElements compositing the stack that represents foo.bar[3].x
#[derive(PartialEq, Clone, Show)]
pub enum StackElement<'l> {
@ -2505,12 +2506,12 @@ mod tests {
use super::ParserError::*;
use super::DecoderError::*;
use super::JsonEvent::*;
use super::StackElement::*;
use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
StackElement, Stack, Decoder};
use std::{i64, u64, f32, f64};
use std::{i64, u64, f32, f64, io};
use std::collections::BTreeMap;
use std::num::Float;
use std::ops::Index;
use std::string;
#[derive(RustcDecodable, Eq, PartialEq, Show)]
@ -3487,9 +3488,12 @@ mod tests {
(U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]),
(ArrayEnd, vec![StackElement::Key("array")]),
(ArrayStart, vec![StackElement::Key("idents")]),
(NullValue, vec![StackElement::Key("idents"), StackElement::Index(0)]),
(BooleanValue(true), vec![StackElement::Key("idents"), StackElement::Index(1)]),
(BooleanValue(false), vec![StackElement::Key("idents"), StackElement::Index(2)]),
(NullValue, vec![StackElement::Key("idents"),
StackElement::Index(0)]),
(BooleanValue(true), vec![StackElement::Key("idents"),
StackElement::Index(1)]),
(BooleanValue(false), vec![StackElement::Key("idents"),
StackElement::Index(2)]),
(ArrayEnd, vec![StackElement::Key("idents")]),
(ObjectEnd, vec![]),
]
@ -3567,13 +3571,24 @@ mod tests {
(ObjectStart, vec![]),
(F64Value(1.0), vec![StackElement::Key("a")]),
(ArrayStart, vec![StackElement::Key("b")]),
(BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]),
(StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"), StackElement::Index(1)]),
(ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2)]),
(ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")]),
(NullValue, vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c"), StackElement::Key("d")]),
(ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")]),
(ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2)]),
(BooleanValue(true), vec![StackElement::Key("b"),
StackElement::Index(0)]),
(StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"),
StackElement::Index(1)]),
(ObjectStart, vec![StackElement::Key("b"),
StackElement::Index(2)]),
(ObjectStart, vec![StackElement::Key("b"),
StackElement::Index(2),
StackElement::Key("c")]),
(NullValue, vec![StackElement::Key("b"),
StackElement::Index(2),
StackElement::Key("c"),
StackElement::Key("d")]),
(ObjectEnd, vec![StackElement::Key("b"),
StackElement::Index(2),
StackElement::Key("c")]),
(ObjectEnd, vec![StackElement::Key("b"),
StackElement::Index(2)]),
(ArrayEnd, vec![StackElement::Key("b")]),
(ObjectEnd, vec![]),
]
@ -3716,13 +3731,19 @@ mod tests {
stack.push_key("bar".to_string());
assert!(stack.len() == 3);
assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo"), StackElement::Key("bar")]));
assert!(stack.is_equal_to(&[StackElement::Index(1),
StackElement::Key("foo"),
StackElement::Key("bar")]));
assert!(stack.starts_with(&[StackElement::Index(1)]));
assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo"), StackElement::Key("bar")]));
assert!(stack.starts_with(&[StackElement::Index(1),
StackElement::Key("foo"),
StackElement::Key("bar")]));
assert!(stack.ends_with(&[StackElement::Key("bar")]));
assert!(stack.ends_with(&[StackElement::Key("foo"), StackElement::Key("bar")]));
assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo"), StackElement::Key("bar")]));
assert!(stack.ends_with(&[StackElement::Index(1),
StackElement::Key("foo"),
StackElement::Key("bar")]));
assert!(!stack.last_is_index());
assert!(stack.get(0) == StackElement::Index(1));
assert!(stack.get(1) == StackElement::Key("foo"));

View File

@ -211,6 +211,7 @@ use std::string;
use std::ops;
use unicode::str as unicode_str;
use unicode::str::Utf16Item;
use std::ops::Index as IndexOp;
use Encodable;
@ -386,7 +387,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result {
};
if start < i {
try!(wr.write_str(v[start..i]));
try!(wr.write_str(v.index(&(start..i))));
}
try!(wr.write_str(escaped));
@ -395,7 +396,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result {
}
if start != v.len() {
try!(wr.write_str(v[start..]));
try!(wr.write_str(v.index(&(start..))));
}
wr.write_str("\"")
@ -404,7 +405,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result {
fn escape_char(writer: &mut fmt::Writer, v: char) -> fmt::Result {
let mut buf = [0; 4];
let n = v.encode_utf8(&mut buf).unwrap();
let buf = unsafe { str::from_utf8_unchecked(buf[0..n]) };
let buf = unsafe { str::from_utf8_unchecked(buf.index(&(0..n))) };
escape_str(writer, buf)
}
@ -417,7 +418,7 @@ fn spaces(wr: &mut fmt::Writer, mut n: uint) -> fmt::Result {
}
if n > 0 {
wr.write_str(BUF[..n])
wr.write_str(BUF.index(&(..n)))
} else {
Ok(())
}
@ -624,7 +625,7 @@ impl<'a> ::Encoder<fmt::Error> for Encoder<'a> {
let mut check_encoder = Encoder::new(&mut buf);
try!(f(transmute(&mut check_encoder)));
}
let out = str::from_utf8(buf[]).unwrap();
let out = str::from_utf8(buf.index(&FullRange)).unwrap();
let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
if needs_wrapping { try!(write!(self.writer, "\"")); }
try!(f(self));
@ -893,7 +894,7 @@ impl<'a> ::Encoder<fmt::Error> for PrettyEncoder<'a> {
let mut check_encoder = PrettyEncoder::new(&mut buf);
try!(f(transmute(&mut check_encoder)));
}
let out = str::from_utf8(buf[]).unwrap();
let out = str::from_utf8(buf.index(&FullRange)).unwrap();
let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
if needs_wrapping { try!(write!(self.writer, "\"")); }
try!(f(self));
@ -1026,7 +1027,7 @@ impl Json {
/// Returns None otherwise.
pub fn as_string<'a>(&'a self) -> Option<&'a str> {
match *self {
Json::String(ref s) => Some(s[]),
Json::String(ref s) => Some(s.index(&FullRange)),
_ => None
}
}
@ -1220,7 +1221,8 @@ impl Stack {
InternalIndex(i) => Index(i),
InternalKey(start, size) => {
Key(str::from_utf8(
self.str_buffer[start as uint .. start as uint + size as uint]).unwrap())
self.str_buffer.index(
&((start as uint) .. (start as uint + size as uint)))).unwrap())
}
}
}
@ -1262,7 +1264,7 @@ impl Stack {
Some(&InternalIndex(i)) => Some(Index(i)),
Some(&InternalKey(start, size)) => {
Some(Key(str::from_utf8(
self.str_buffer[start as uint .. (start+size) as uint]
self.str_buffer.index(&(start as uint) .. ((start+size) as uint))
).unwrap()))
}
}
@ -2139,7 +2141,7 @@ impl ::Decoder<DecoderError> for Decoder {
return Err(ExpectedError("String or Object".to_string(), format!("{}", json)))
}
};
let idx = match names.iter().position(|n| *n == name[]) {
let idx = match names.iter().position(|n| *n == name.index(&FullRange)) {
Some(idx) => idx,
None => return Err(UnknownVariantError(name))
};
@ -3352,7 +3354,7 @@ mod tests {
hm.insert(1, true);
let mut mem_buf = Vec::new();
write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
let json_str = from_utf8(mem_buf[]).unwrap();
let json_str = from_utf8(&mem_buf.index(&FullRange)).unwrap();
match from_str(json_str) {
Err(_) => panic!("Unable to parse json_str: {}", json_str),
_ => {} // it parsed and we are good to go
@ -3368,7 +3370,7 @@ mod tests {
hm.insert(1, true);
let mut mem_buf = Vec::new();
write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
let json_str = from_utf8(mem_buf[]).unwrap();
let json_str = from_utf8(&mem_buf.index(&FullRange)).unwrap();
match from_str(json_str) {
Err(_) => panic!("Unable to parse json_str: {}", json_str),
_ => {} // it parsed and we are good to go
@ -3408,7 +3410,7 @@ mod tests {
write!(&mut writer, "{}",
super::as_pretty_json(&json).indent(i)).unwrap();
let printed = from_utf8(writer[]).unwrap();
let printed = from_utf8(&writer.index(&FullRange)).unwrap();
// Check for indents at each line
let lines: Vec<&str> = printed.lines().collect();

View File

@ -14,6 +14,7 @@
Core encoding and decoding interfaces.
*/
use std::ops::FullRange;
use std::path;
use std::rc::Rc;
use std::cell::{Cell, RefCell};
@ -308,7 +309,7 @@ impl<E, S:Encoder<E>> Encodable<S, E> for str {
impl<E, S:Encoder<E>> Encodable<S, E> for String {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_str(self[])
s.emit_str(self.index(&FullRange))
}
}

View File

@ -472,41 +472,37 @@ mod test {
writer.write(&[0, 1]).unwrap();
let b: &[_] = &[];
assert_eq!(writer.get_ref()[], b);
assert_eq!(&writer.get_ref()[], b);
writer.write(&[2]).unwrap();
let b: &[_] = &[0, 1];
assert_eq!(writer.get_ref()[], b);
assert_eq!(&writer.get_ref()[], b);
writer.write(&[3]).unwrap();
assert_eq!(writer.get_ref()[], b);
assert_eq!(&writer.get_ref()[], b);
writer.flush().unwrap();
let a: &[_] = &[0, 1, 2, 3];
assert_eq!(a, writer.get_ref()[]);
assert_eq!(a, &writer.get_ref()[]);
writer.write(&[4]).unwrap();
writer.write(&[5]).unwrap();
assert_eq!(a, writer.get_ref()[]);
assert_eq!(a, &writer.get_ref()[]);
writer.write(&[6]).unwrap();
let a: &[_] = &[0, 1, 2, 3, 4, 5];
assert_eq!(a,
writer.get_ref()[]);
assert_eq!(a, &writer.get_ref()[]);
writer.write(&[7, 8]).unwrap();
let a: &[_] = &[0, 1, 2, 3, 4, 5, 6];
assert_eq!(a,
writer.get_ref()[]);
assert_eq!(a, &writer.get_ref()[]);
writer.write(&[9, 10, 11]).unwrap();
let a: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
assert_eq!(a,
writer.get_ref()[]);
assert_eq!(a, &writer.get_ref()[]);
writer.flush().unwrap();
assert_eq!(a,
writer.get_ref()[]);
assert_eq!(a, &writer.get_ref()[]);
}
#[test]
@ -514,7 +510,7 @@ mod test {
let mut w = BufferedWriter::with_capacity(3, Vec::new());
w.write(&[0, 1]).unwrap();
let a: &[_] = &[];
assert_eq!(a, w.get_ref()[]);
assert_eq!(a, &w.get_ref()[]);
let w = w.into_inner();
let a: &[_] = &[0, 1];
assert_eq!(a, w.index(&FullRange));
@ -559,21 +555,21 @@ mod test {
let mut writer = LineBufferedWriter::new(Vec::new());
writer.write(&[0]).unwrap();
let b: &[_] = &[];
assert_eq!(writer.get_ref()[], b);
assert_eq!(&writer.get_ref()[], b);
writer.write(&[1]).unwrap();
assert_eq!(writer.get_ref()[], b);
assert_eq!(&writer.get_ref()[], b);
writer.flush().unwrap();
let b: &[_] = &[0, 1];
assert_eq!(writer.get_ref()[], b);
assert_eq!(&writer.get_ref()[], b);
writer.write(&[0, b'\n', 1, b'\n', 2]).unwrap();
let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n'];
assert_eq!(writer.get_ref()[], b);
assert_eq!(&writer.get_ref()[], b);
writer.flush().unwrap();
let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n', 2];
assert_eq!(writer.get_ref()[], b);
assert_eq!(&writer.get_ref()[], b);
writer.write(&[3, b'\n']).unwrap();
let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n', 2, 3, b'\n'];
assert_eq!(writer.get_ref()[], b);
assert_eq!(&writer.get_ref()[], b);
}
#[test]

View File

@ -13,7 +13,7 @@
//! Readers and Writers for in-memory buffers
use cmp::min;
use prelude::Index;
use prelude::v1::Index;
use option::Option::None;
use result::Result::{Err, Ok};
use io;
@ -391,9 +391,9 @@ impl<'a> Buffer for BufReader<'a> {
#[cfg(test)]
mod test {
extern crate "test" as test_crate;
use prelude::v1::*;
use io::{SeekSet, SeekCur, SeekEnd};
use io::{SeekSet, SeekCur, SeekEnd, Reader, Writer, Seek};
use prelude::v1::{Ok, Err, range, Vec, Buffer, AsSlice, SliceExt};
use prelude::v1::{IteratorExt, Index};
use io;
use iter::repeat;
use self::test_crate::Bencher;

View File

@ -752,12 +752,12 @@ impl Drop for Process {
#[cfg(test)]
mod tests {
use prelude::v1::*;
use io::{Truncate, Write, TimedOut, timer, process, FileNotFound};
use prelude::v1::{Ok, Err, range, drop, Some, None, Vec};
use prelude::v1::{Path, String, Reader, Writer, Clone};
use prelude::v1::{SliceExt, Str, StrExt, AsSlice, ToString, GenericPath};
use io::fs::PathExtensions;
use io::process;
use io::timer::*;
use io::{Truncate, Write, TimedOut, timer, FileNotFound};
use rt::running_on_valgrind;
use str;
use super::{CreatePipe};

View File

@ -68,7 +68,7 @@ use fmt;
use iter::IteratorExt;
use option::Option;
use option::Option::{None, Some};
use prelude::{FullRange, Index};
use prelude::v1::{FullRange, Index};
use str;
use str::StrExt;
use string::{String, CowString};

View File

@ -24,7 +24,7 @@ use iter::{AdditiveIterator, Extend};
use iter::{Iterator, IteratorExt, Map, repeat};
use mem;
use option::Option::{self, Some, None};
use prelude::{FullRange, Index};
use prelude::v1::{FullRange, Index};
use slice::{SliceExt, SliceConcatExt};
use str::{SplitTerminator, FromStr, StrExt};
use string::{String, ToString};
@ -337,8 +337,12 @@ impl GenericPath for Path {
Some(match self.sepidx_or_prefix_len() {
None if ".." == self.repr => self.repr.index(&FullRange),
None => ".",
Some((_,idxa,end)) if self.repr.index(&(idxa..end)) == ".." => self.repr.index(&FullRange),
Some((idxb,_,end)) if self.repr.index(&(idxb..end)) == "\\" => self.repr.index(&FullRange),
Some((_,idxa,end)) if self.repr.index(&(idxa..end)) == ".." => {
self.repr.index(&FullRange)
}
Some((idxb,_,end)) if self.repr.index(&(idxb..end)) == "\\" => {
self.repr.index(&FullRange)
}
Some((0,idxa,_)) => self.repr.index(&(0..idxa)),
Some((idxb,idxa,_)) => {
match self.prefix {

View File

@ -14,7 +14,8 @@
// Reexported core operators
#[stable] #[doc(no_inline)] pub use kinds::{Copy, Send, Sized, Sync};
#[stable] #[doc(no_inline)] pub use ops::{Drop, Fn, FnMut, FnOnce};
#[stable] #[doc(no_inline)] pub use ops::{Drop, Fn, FnMut, FnOnce, FullRange};
#[unstable] #[doc(no_inline)] pub use ops::{Index, IndexMut};
// Reexported functions
#[stable] #[doc(no_inline)] pub use mem::drop;

View File

@ -23,6 +23,7 @@
use dynamic_lib::DynamicLibrary;
use ffi;
use core::ops::Index;
use intrinsics;
use io::{IoResult, Writer};
use libc;
@ -361,7 +362,7 @@ pub fn write(w: &mut Writer) -> IoResult<()> {
let bytes = unsafe { ffi::c_str_to_bytes(&ptr) };
match str::from_utf8(bytes) {
Ok(s) => try!(demangle(w, s)),
Err(..) => try!(w.write(bytes[..bytes.len()-1])),
Err(..) => try!(w.write(bytes.index(&(..(bytes.len()-1))))),
}
}
try!(w.write(&['\n' as u8]));

View File

@ -206,7 +206,7 @@ impl<D: Decoder<E>, E> Decodable<D, E> for Ident {
#[cfg(not(stage0))]
impl Decodable for Ident {
fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
Ok(str_to_ident(try!(d.read_str())[]))
Ok(str_to_ident(try!(d.read_str()).index(&FullRange)))
}
}

View File

@ -332,7 +332,7 @@ pub fn cfg_matches(diagnostic: &SpanHandler, cfgs: &[P<MetaItem>], cfg: &ast::Me
!cfg_matches(diagnostic, cfgs, &*mis[0])
}
ast::MetaList(ref pred, _) => {
diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred).index(&FullRange));
diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred).as_slice());
false
},
ast::MetaWord(_) | ast::MetaNameValue(..) => contains(cfgs, cfg),

View File

@ -29,12 +29,13 @@ pub fn expand_deriving_bound<F>(cx: &mut ExtCtxt,
"Send" | "Sync" => {
return cx.span_err(span,
format!("{} is an unsafe trait and it \
should be implemented explicitly", *tname).index(&FullRange))
should be implemented explicitly",
*tname).as_slice())
}
ref tname => {
cx.span_bug(span,
format!("expected built-in trait name but \
found {}", *tname).index(&FullRange))
found {}", *tname).as_slice())
}
}
},

View File

@ -386,7 +386,7 @@ pub fn parse(sess: &ParseSess,
new_ei.idx += 1u;
//we specifically matched zero repeats.
for idx in range(ei.match_cur, ei.match_cur + seq.num_captures) {
(&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(Vec::new(), sp)));
(&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp)));
}
cur_eis.push(new_ei);

View File

@ -278,7 +278,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
_ => {}
}
if attr::contains_name(i.attrs[],
if attr::contains_name(i.attrs.as_slice(),
"unsafe_destructor") {
self.gate_feature("unsafe_destructor",
i.span,
@ -287,7 +287,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
removed in the future");
}
if attr::contains_name(i.attrs[],
if attr::contains_name(i.attrs.index(&FullRange),
"old_orphan_check") {
self.gate_feature(
"old_orphan_check",
@ -309,7 +309,8 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
and not portable across platforms")
}
let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs[], "link_name") {
let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
"link_name") {
Some(val) => val.get().starts_with("llvm."),
_ => false
};

View File

@ -1167,10 +1167,10 @@ mod test {
for &src in srcs.iter() {
let spans = get_spans_of_pat_idents(src);
let Span{lo:lo,hi:hi,..} = spans[0];
assert!("self" == src[lo.to_uint()..hi.to_uint()],
let Span{ lo, hi, .. } = spans[0];
assert!("self" == &src[lo.to_uint()..hi.to_uint()],
"\"{}\" != \"self\". src=\"{}\"",
src[lo.to_uint()..hi.to_uint()], src)
&src[lo.to_uint()..hi.to_uint()], src)
}
}

View File

@ -1726,7 +1726,7 @@ impl<'a> Parser<'a> {
token::Str_(s) => {
(true,
LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).index(&FullRange)),
LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()),
ast::CookedStr))
}
token::StrRaw(s, n) => {
@ -2538,16 +2538,26 @@ impl<'a> Parser<'a> {
token::OpenDelim(token::Bracket) => {
let bracket_pos = self.span.lo;
self.bump();
if self.eat(&token::CloseDelim(token::Bracket)) {
let mut found_dotdot = false;
if self.token == token::DotDot &&
self.look_ahead(1, |t| t == &token::CloseDelim(token::Bracket)) {
// Using expr[..], which is a mistake, should be expr[]
self.bump();
self.bump();
found_dotdot = true;
}
if found_dotdot || self.eat(&token::CloseDelim(token::Bracket)) {
// No expression, expand to a FullRange
let ix = {
hi = self.last_span.hi;
let range = ExprStruct(ident_to_path(mk_sp(lo, hi),
token::special_idents::FullRange),
vec![],
None);
self.mk_expr(bracket_pos, hi, range)
};
// FIXME(#20516) It would be better to use a lang item or
// something for FullRange.
hi = self.last_span.hi;
let range = ExprStruct(ident_to_path(mk_sp(lo, hi),
token::special_idents::FullRange),
vec![],
None);
let ix = self.mk_expr(bracket_pos, hi, range);
let index = self.mk_index(e, ix);
e = self.mk_expr(lo, hi, index)
} else {
@ -2557,6 +2567,12 @@ impl<'a> Parser<'a> {
let index = self.mk_index(e, ix);
e = self.mk_expr(lo, hi, index)
}
if found_dotdot {
self.span_err(e.span, "incorrect slicing expression: `[..]`");
self.span_note(e.span,
"use `&expr[]` to construct a slice of the whole of expr");
}
}
// A range expression, either `expr..expr` or `expr..`.
@ -4881,7 +4897,7 @@ impl<'a> Parser<'a> {
let token_str = self.this_token_to_string();
self.fatal(format!("expected `where`, or `{}` after struct \
name, found `{}`", "{",
token_str)[]);
token_str).index(&FullRange));
}
fields

View File

@ -689,8 +689,7 @@ impl<D:Decoder<E>, E> Decodable<D, E> for InternedString {
#[cfg(not(stage0))]
impl Decodable for InternedString {
fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
Ok(get_name(get_ident_interner().intern(
try!(d.read_str())[])))
Ok(get_name(get_ident_interner().intern(try!(d.read_str()).index(&FullRange))))
}
}
@ -704,7 +703,7 @@ impl<S:Encoder<E>, E> Encodable<S, E> for InternedString {
#[cfg(not(stage0))]
impl Encodable for InternedString {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_str(self.string[])
s.emit_str(self.string.index(&FullRange))
}
}

View File

@ -1537,35 +1537,34 @@ impl<'a> State<'a> {
ast::ExprStruct(ref path, ref fields, ref wth) => {
try!(self.print_path(path, true));
if fields.is_empty() && wth.is_none() {
return;
}
try!(word(&mut self.s, "{"));
try!(self.commasep_cmnt(
Consistent,
fields.index(&FullRange),
|s, field| {
try!(s.ibox(indent_unit));
try!(s.print_ident(field.ident.node));
try!(s.word_space(":"));
try!(s.print_expr(&*field.expr));
s.end()
},
|f| f.span));
match *wth {
Some(ref expr) => {
try!(self.ibox(indent_unit));
if !fields.is_empty() {
try!(word(&mut self.s, ","));
try!(space(&mut self.s));
if !(fields.is_empty() && wth.is_none()) {
try!(word(&mut self.s, "{"));
try!(self.commasep_cmnt(
Consistent,
fields.index(&FullRange),
|s, field| {
try!(s.ibox(indent_unit));
try!(s.print_ident(field.ident.node));
try!(s.word_space(":"));
try!(s.print_expr(&*field.expr));
s.end()
},
|f| f.span));
match *wth {
Some(ref expr) => {
try!(self.ibox(indent_unit));
if !fields.is_empty() {
try!(word(&mut self.s, ","));
try!(space(&mut self.s));
}
try!(word(&mut self.s, ".."));
try!(self.print_expr(&**expr));
try!(self.end());
}
try!(word(&mut self.s, ".."));
try!(self.print_expr(&**expr));
try!(self.end());
_ => try!(word(&mut self.s, ",")),
}
_ => try!(word(&mut self.s, ",")),
try!(word(&mut self.s, "}"));
}
try!(word(&mut self.s, "}"));
}
ast::ExprTup(ref exprs) => {
try!(self.popen());
@ -2781,7 +2780,7 @@ impl<'a> State<'a> {
format!("-{}", istr).index(&FullRange))
}
ast::UnsignedIntLit(ut) => {
word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).index(&FullRange))
word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).as_slice())
}
ast::UnsuffixedIntLit(ast::Plus) => {
word(&mut self.s, format!("{}", i).index(&FullRange))

View File

@ -105,7 +105,7 @@ impl Perm {
let d = idx / self.fact[i] as i32;
self.cnt[i] = d;
idx %= self.fact[i] as i32;
for (place, val) in pp.iter_mut().zip(self.perm.p[..i+1].iter()) {
for (place, val) in pp.iter_mut().zip(self.perm.p[..(i+1)].iter()) {
*place = (*val) as u8
}

View File

@ -99,7 +99,7 @@ fn make_fasta<W: Writer, I: Iterator<Item=u8>>(
}
n -= nb;
line[nb] = '\n' as u8;
try!(wr.write(line[..nb+1]));
try!(wr.write(&line[..(nb+1)]));
}
Ok(())
}

View File

@ -101,11 +101,11 @@ fn windows_with_carry<F>(bb: &[u8], nn: uint, mut it: F) -> Vec<u8> where
let len = bb.len();
while ii < len - (nn - 1u) {
it(bb[ii..ii+nn]);
it(&bb[ii..(ii+nn)]);
ii += 1u;
}
return bb[len - (nn - 1u)..len].to_vec();
return bb[(len - (nn - 1u))..len].to_vec();
}
fn make_sequence_processor(sz: uint,

View File

@ -17,12 +17,12 @@ fn takes_imm_elt<F>(_v: &int, f: F) where F: FnOnce() {
}
fn has_mut_vec_and_does_not_try_to_change_it() {
let mut v = vec!(1, 2, 3);
let mut v: Vec<int> = vec!(1, 2, 3);
takes_imm_elt(&v[0], || {})
}
fn has_mut_vec_but_tries_to_change_it() {
let mut v = vec!(1, 2, 3);
let mut v: Vec<int> = vec!(1, 2, 3);
takes_imm_elt(
&v[0],
|| { //~ ERROR cannot borrow `v` as mutable

View File

@ -13,7 +13,8 @@
fn main() {
fn bar<T>(_: T) {}
[0][0u8]; //~ ERROR: mismatched types
[0][0u8]; //~ ERROR: the trait `core::ops::Index<u8>` is not implemented
//~^ ERROR: the trait `core::ops::Index<u8>` is not implemented
[0][0]; // should infer to be a uint

View File

@ -11,16 +11,24 @@
pub fn main() {
let v: Vec<int> = vec!(0, 1, 2, 3, 4, 5);
let s: String = "abcdef".to_string();
assert_eq!(v.as_slice()[3u], 3);
assert_eq!(v.as_slice()[3u8], 3); //~ ERROR: mismatched types
assert_eq!(v.as_slice()[3i8], 3); //~ ERROR: mismatched types
assert_eq!(v.as_slice()[3u32], 3); //~ ERROR: mismatched types
assert_eq!(v.as_slice()[3i32], 3); //~ ERROR: mismatched types
println!("{}", v.as_slice()[3u8]); //~ ERROR: mismatched types
assert_eq!(s.as_bytes()[3u], 'd' as u8);
assert_eq!(s.as_bytes()[3u8], 'd' as u8); //~ ERROR: mismatched types
assert_eq!(s.as_bytes()[3i8], 'd' as u8); //~ ERROR: mismatched types
assert_eq!(s.as_bytes()[3u32], 'd' as u8); //~ ERROR: mismatched types
assert_eq!(s.as_bytes()[3i32], 'd' as u8); //~ ERROR: mismatched types
println!("{}", s.as_bytes()[3u8]); //~ ERROR: mismatched types
v.as_slice()[3u];
v.as_slice()[3];
v.as_slice()[3u8]; //~ERROR the trait `core::ops::Index<u8>` is not implemented
//~^ ERROR the trait `core::ops::Index<u8>` is not implemented
v.as_slice()[3i8]; //~ERROR the trait `core::ops::Index<i8>` is not implemented
//~^ ERROR the trait `core::ops::Index<i8>` is not implemented
v.as_slice()[3u32]; //~ERROR the trait `core::ops::Index<u32>` is not implemented
//~^ ERROR the trait `core::ops::Index<u32>` is not implemented
v.as_slice()[3i32]; //~ERROR the trait `core::ops::Index<i32>` is not implemented
//~^ ERROR the trait `core::ops::Index<i32>` is not implemented
s.as_bytes()[3u];
s.as_bytes()[3];
s.as_bytes()[3u8]; //~ERROR the trait `core::ops::Index<u8>` is not implemented
//~^ERROR the trait `core::ops::Index<u8>` is not implemented
s.as_bytes()[3i8]; //~ERROR the trait `core::ops::Index<i8>` is not implemented
//~^ERROR the trait `core::ops::Index<i8>` is not implemented
s.as_bytes()[3u32]; //~ERROR the trait `core::ops::Index<u32>` is not implemented
//~^ERROR the trait `core::ops::Index<u32>` is not implemented
s.as_bytes()[3i32]; //~ERROR the trait `core::ops::Index<i32>` is not implemented
//~^ERROR the trait `core::ops::Index<i32>` is not implemented
}

View File

@ -1,25 +0,0 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::ptr;
use std::raw;
trait Slice {}
fn main() {
unsafe {
let nil: *const u8 = ptr::null();
let slice: raw::Slice<u8> =
Slice { //~ ERROR use of trait `Slice` as a struct constructor [E0159]
data: nil,
len: 0,
};
}
}

View File

@ -16,8 +16,8 @@ struct Foo;
fn main() {
let x = Foo;
&x[]; //~ ERROR cannot take a slice of a value with type `Foo`
&x[Foo..]; //~ ERROR cannot take a slice of a value with type `Foo`
&x[0..Foo]; //~ ERROR cannot take a slice of a value with type `Foo`
&x[Foo..Foo]; //~ ERROR cannot take a slice of a value with type `Foo`
&x[]; //~ ERROR cannot index a value of type `Foo`
&x[Foo..]; //~ ERROR cannot index a value of type `Foo`
&x[..Foo]; //~ ERROR cannot index a value of type `Foo`
&x[Foo..Foo]; //~ ERROR cannot index a value of type `Foo`
}

View File

@ -16,5 +16,5 @@ fn main() {
let x: &[int] = &[1, 2, 3, 4, 5];
// Can't mutably slice an immutable slice
let slice: &mut [int] = &mut [0, 1];
&mut x[2..4] = slice; //~ ERROR cannot borrow
let _ = &mut x[2..4]; //~ERROR cannot borrow immutable dereference of `&`-pointer `*x` as mutabl
}

View File

@ -15,5 +15,5 @@
fn main() {
let x: &[int] = &[1, 2, 3, 4, 5];
// Immutable slices are not mutable.
let y: &mut[_] = &x[2..4]; //~ ERROR cannot borrow immutable dereference of `&`-pointer as mutabl
let y: &mut[_] = &x[2..4]; //~ ERROR cannot borrow immutable dereference of `&`-pointer as mutab
}

View File

@ -10,5 +10,6 @@
pub fn main() {
let s: &str = "hello";
let c: u8 = s[4]; //~ ERROR cannot index a value of type `&str`
let c: u8 = s[4]; //~ ERROR the trait `core::ops::Index<_>` is not implemented
//~^ ERROR the trait `core::ops::Index<_>` is not implemented
}

View File

@ -15,7 +15,7 @@ fn main() {
let ss: &&[int] = &s;
let sss: &&&[int] = &ss;
println!("{}", s.index(&(0..3)));
println!("{}", ss.index(&(3..)));
println!("{}", sss.index(&(2..4)));
println!("{}", &s[0..3]);
println!("{}", &ss[3..]);
println!("{}", &sss[2..4]);
}

View File

@ -11,7 +11,7 @@
#![feature(slicing_syntax)]
fn vec_peek<'r, T>(v: &'r [T]) -> &'r [T] {
v.index(&(1..5))
&v[1..5]
}
pub fn main() {}

View File

@ -10,6 +10,6 @@
#![feature(slicing_syntax)]
fn broken(v: &[u8], i: uint, j: uint) -> &[u8] { v.index(&(i..j)) }
fn broken(v: &[u8], i: uint, j: uint) -> &[u8] { &v[i..j] }
pub fn main() {}

View File

@ -18,7 +18,7 @@ pub fn main() {
let abc = [1i, 2, 3];
let tf = [true, false];
let x = [(), ()];
let slice = x.index(&(0..1));
let slice = &x[0..1];
assert_repr_eq(&abc[], "[1, 2, 3]".to_string());
assert_repr_eq(&tf[], "[true, false]".to_string());

View File

@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that is a slicing expr.index(&(..)) fails, the correct cleanups happen.
// Test that if a slicing expr[..] fails, the correct cleanups happen.
#![feature(slicing_syntax)]
@ -24,7 +24,7 @@ impl Drop for Foo {
fn foo() {
let x: &[_] = &[Foo, Foo];
x.index(&(3..4));
&x[3..4];
}
fn main() {

View File

@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that is a slicing expr.index(&(..)) fails, the correct cleanups happen.
// Test that if a slicing expr[..] fails, the correct cleanups happen.
#![feature(slicing_syntax)]
@ -28,7 +28,7 @@ fn bar() -> uint {
fn foo() {
let x: &[_] = &[Foo, Foo];
x[3..bar()];
&x[3..bar()];
}
fn main() {

View File

@ -11,6 +11,7 @@
// Test slicing sugar.
#![feature(slicing_syntax)]
#![feature(associated_types)]
extern crate core;
use core::ops::{Index, Range, RangeTo, RangeFrom, FullRange};
@ -19,49 +20,70 @@ static mut COUNT: uint = 0;
struct Foo;
impl Slice<Foo, Foo> for Foo {
fn as_slice_<'a>(&'a self) -> &'a Foo {
impl Index<Range<Foo>> for Foo {
type Output = Foo;
fn index(&self, index: &Range<Foo>) -> &Foo {
unsafe { COUNT += 1; }
self
}
fn slice_from_or_fail<'a>(&'a self, _from: &Foo) -> &'a Foo {
}
impl Index<RangeTo<Foo>> for Foo {
type Output = Foo;
fn index(&self, index: &RangeTo<Foo>) -> &Foo {
unsafe { COUNT += 1; }
self
}
fn slice_to_or_fail<'a>(&'a self, _to: &Foo) -> &'a Foo {
}
impl Index<RangeFrom<Foo>> for Foo {
type Output = Foo;
fn index(&self, index: &RangeFrom<Foo>) -> &Foo {
unsafe { COUNT += 1; }
self
}
fn slice_or_fail<'a>(&'a self, _from: &Foo, _to: &Foo) -> &'a Foo {
}
impl Index<FullRange> for Foo {
type Output = Foo;
fn index(&self, _index: &FullRange) -> &Foo {
unsafe { COUNT += 1; }
self
}
}
impl SliceMut<Foo, Foo> for Foo {
fn as_mut_slice_<'a>(&'a mut self) -> &'a mut Foo {
unsafe { COUNT += 1; }
self
}
fn slice_from_or_fail_mut<'a>(&'a mut self, _from: &Foo) -> &'a mut Foo {
unsafe { COUNT += 1; }
self
}
fn slice_to_or_fail_mut<'a>(&'a mut self, _to: &Foo) -> &'a mut Foo {
unsafe { COUNT += 1; }
self
}
fn slice_or_fail_mut<'a>(&'a mut self, _from: &Foo, _to: &Foo) -> &'a mut Foo {
impl IndexMut<Range<Foo>> for Foo {
type Output = Foo;
fn index_mut(&mut self, index: &Range<Foo>) -> &mut Foo {
unsafe { COUNT += 1; }
self
}
}
impl IndexMut<RangeTo<Foo>> for Foo {
type Output = Foo;
fn index_mut(&mut self, index: &RangeTo<Foo>) -> &mut Foo {
unsafe { COUNT += 1; }
self
}
}
impl IndexMut<RangeFrom<Foo>> for Foo {
type Output = Foo;
fn index_mut(&mut self, index: &RangeFrom<Foo>) -> &mut Foo {
unsafe { COUNT += 1; }
self
}
}
impl IndexMut<FullRange> for Foo {
type Output = Foo;
fn index_mut(&mut self, _index: &FullRange) -> &mut Foo {
unsafe { COUNT += 1; }
self
}
}
fn main() {
let mut x = Foo;
&x[];
&x[Foo..];
&x[0..Foo];
&x[..Foo];
&x[Foo..Foo];
&mut x[];
&mut x[Foo..];