Skip to content

Commit aa2814f

Browse files
committed
Implement Slice for String and str
Closes #17502
1 parent d64b410 commit aa2814f

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

src/libcollections/string.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use core::default::Default;
1818
use core::fmt;
1919
use core::mem;
2020
use core::ptr;
21+
use core::ops;
2122
// FIXME: ICE's abound if you import the `Slice` type while importing `Slice` trait
2223
use core::raw::Slice as RawSlice;
2324

@@ -926,6 +927,28 @@ impl<S: Str> Add<S, String> for String {
926927
}
927928
}
928929

930+
impl ops::Slice<uint, str> for String {
931+
#[inline]
932+
fn as_slice_<'a>(&'a self) -> &'a str {
933+
self.as_slice()
934+
}
935+
936+
#[inline]
937+
fn slice_from_<'a>(&'a self, from: &uint) -> &'a str {
938+
self[][*from..]
939+
}
940+
941+
#[inline]
942+
fn slice_to_<'a>(&'a self, to: &uint) -> &'a str {
943+
self[][..*to]
944+
}
945+
946+
#[inline]
947+
fn slice_<'a>(&'a self, from: &uint, to: &uint) -> &'a str {
948+
self[][*from..*to]
949+
}
950+
}
951+
929952
/// Unsafe operations
930953
#[unstable = "waiting on raw module conventions"]
931954
pub mod raw {
@@ -1290,6 +1313,15 @@ mod tests {
12901313
#[test] #[should_fail] fn insert_bad1() { "".to_string().insert(1, 't'); }
12911314
#[test] #[should_fail] fn insert_bad2() { "ệ".to_string().insert(1, 't'); }
12921315

1316+
#[test]
1317+
fn test_slicing() {
1318+
let s = "foobar".to_string();
1319+
assert_eq!("foobar", s[]);
1320+
assert_eq!("foo", s[..3]);
1321+
assert_eq!("bar", s[3..]);
1322+
assert_eq!("oob", s[1..4]);
1323+
}
1324+
12931325
#[bench]
12941326
fn bench_with_capacity(b: &mut Bencher) {
12951327
b.iter(|| {

src/libcore/str.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1123,6 +1123,7 @@ pub mod traits {
11231123
use collections::Collection;
11241124
use iter::Iterator;
11251125
use option::{Option, Some};
1126+
use ops;
11261127
use str::{Str, StrSlice, eq_slice};
11271128

11281129
impl<'a> Ord for &'a str {
@@ -1162,6 +1163,28 @@ pub mod traits {
11621163
#[inline]
11631164
fn equiv(&self, other: &S) -> bool { eq_slice(*self, other.as_slice()) }
11641165
}
1166+
1167+
impl ops::Slice<uint, str> for str {
1168+
#[inline]
1169+
fn as_slice_<'a>(&'a self) -> &'a str {
1170+
self
1171+
}
1172+
1173+
#[inline]
1174+
fn slice_from_<'a>(&'a self, from: &uint) -> &'a str {
1175+
self.slice_from(*from)
1176+
}
1177+
1178+
#[inline]
1179+
fn slice_to_<'a>(&'a self, to: &uint) -> &'a str {
1180+
self.slice_to(*to)
1181+
}
1182+
1183+
#[inline]
1184+
fn slice_<'a>(&'a self, from: &uint, to: &uint) -> &'a str {
1185+
self.slice(*from, *to)
1186+
}
1187+
}
11651188
}
11661189

11671190
/// Any string that can be represented as a slice

0 commit comments

Comments
 (0)