1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! String manipulation
13 //! For more details, see std::str
19 use cmp::{Eq, TotalEq};
20 use container::Container;
22 use iter::{Filter, Map, Iterator};
23 use iter::{DoubleEndedIterator, ExactSize};
26 use option::{None, Option, Some};
28 use slice::ImmutableVector;
33 Section: Creating a string
36 /// Converts a vector to a string slice without performing any allocations.
38 /// Once the slice has been validated as utf-8, it is transmuted in-place and
39 /// returned as a '&str' instead of a '&[u8]'
41 /// Returns None if the slice is not utf-8.
42 pub fn from_utf8<'a>(v: &'a [u8]) -> Option<&'a str> {
44 Some(unsafe { raw::from_utf8(v) })
48 /// Something that can be used to compare against a character
50 /// Determine if the splitter should split at the given character
51 fn matches(&mut self, char) -> bool;
52 /// Indicate if this is only concerned about ASCII characters,
53 /// which can allow for a faster implementation.
54 fn only_ascii(&self) -> bool;
57 impl CharEq for char {
59 fn matches(&mut self, c: char) -> bool { *self == c }
62 fn only_ascii(&self) -> bool { (*self as uint) < 128 }
65 impl<'a> CharEq for |char|: 'a -> bool {
67 fn matches(&mut self, c: char) -> bool { (*self)(c) }
70 fn only_ascii(&self) -> bool { false }
73 impl CharEq for extern "Rust" fn(char) -> bool {
75 fn matches(&mut self, c: char) -> bool { (*self)(c) }
78 fn only_ascii(&self) -> bool { false }
81 impl<'a> CharEq for &'a [char] {
83 fn matches(&mut self, c: char) -> bool {
84 self.iter().any(|&mut m| m.matches(c))
88 fn only_ascii(&self) -> bool {
89 self.iter().all(|m| m.only_ascii())
97 /// External iterator for a string's characters.
98 /// Use with the `std::iter` module.
100 pub struct Chars<'a> {
101 /// The slice remaining to be iterated
105 impl<'a> Iterator<char> for Chars<'a> {
107 fn next(&mut self) -> Option<char> {
108 // Decode the next codepoint, then update
109 // the slice to be just the remaining part
110 if self.string.len() != 0 {
111 let CharRange {ch, next} = self.string.char_range_at(0);
113 self.string = raw::slice_unchecked(self.string, next, self.string.len());
122 fn size_hint(&self) -> (uint, Option<uint>) {
123 (self.string.len().saturating_add(3)/4, Some(self.string.len()))
127 impl<'a> DoubleEndedIterator<char> for Chars<'a> {
129 fn next_back(&mut self) -> Option<char> {
130 if self.string.len() != 0 {
131 let CharRange {ch, next} = self.string.char_range_at_reverse(self.string.len());
133 self.string = raw::slice_unchecked(self.string, 0, next);
142 /// External iterator for a string's characters and their byte offsets.
143 /// Use with the `std::iter` module.
145 pub struct CharOffsets<'a> {
146 /// The original string to be iterated
151 impl<'a> Iterator<(uint, char)> for CharOffsets<'a> {
153 fn next(&mut self) -> Option<(uint, char)> {
154 // Compute the byte offset by using the pointer offset between
155 // the original string slice and the iterator's remaining part
156 let offset = self.iter.string.as_ptr() as uint - self.string.as_ptr() as uint;
157 self.iter.next().map(|ch| (offset, ch))
161 fn size_hint(&self) -> (uint, Option<uint>) {
162 self.iter.size_hint()
166 impl<'a> DoubleEndedIterator<(uint, char)> for CharOffsets<'a> {
168 fn next_back(&mut self) -> Option<(uint, char)> {
169 self.iter.next_back().map(|ch| {
170 let offset = self.iter.string.len() +
171 self.iter.string.as_ptr() as uint - self.string.as_ptr() as uint;
177 /// External iterator for a string's bytes.
178 /// Use with the `std::iter` module.
180 Map<'a, &'a u8, u8, slice::Items<'a, u8>>;
182 /// An iterator over the substrings of a string, separated by `sep`.
184 pub struct CharSplits<'a, Sep> {
185 /// The slice remaining to be iterated
188 /// Whether an empty string at the end is allowed
189 allow_trailing_empty: bool,
194 /// An iterator over the substrings of a string, separated by `sep`,
195 /// splitting at most `count` times.
197 pub struct CharSplitsN<'a, Sep> {
198 iter: CharSplits<'a, Sep>,
199 /// The number of splits remaining
204 /// An iterator over the words of a string, separated by a sequence of whitespace
206 Filter<'a, &'a str, CharSplits<'a, extern "Rust" fn(char) -> bool>>;
208 /// An iterator over the lines of a string, separated by either `\n` or (`\r\n`).
209 pub type AnyLines<'a> =
210 Map<'a, &'a str, &'a str, CharSplits<'a, char>>;
212 impl<'a, Sep> CharSplits<'a, Sep> {
214 fn get_end(&mut self) -> Option<&'a str> {
215 if !self.finished && (self.allow_trailing_empty || self.string.len() > 0) {
216 self.finished = true;
224 impl<'a, Sep: CharEq> Iterator<&'a str> for CharSplits<'a, Sep> {
226 fn next(&mut self) -> Option<&'a str> {
227 if self.finished { return None }
229 let mut next_split = None;
231 for (idx, byte) in self.string.bytes().enumerate() {
232 if self.sep.matches(byte as char) && byte < 128u8 {
233 next_split = Some((idx, idx + 1));
238 for (idx, ch) in self.string.char_indices() {
239 if self.sep.matches(ch) {
240 next_split = Some((idx, self.string.char_range_at(idx).next));
246 Some((a, b)) => unsafe {
247 let elt = raw::slice_unchecked(self.string, 0, a);
248 self.string = raw::slice_unchecked(self.string, b, self.string.len());
251 None => self.get_end(),
256 impl<'a, Sep: CharEq> DoubleEndedIterator<&'a str>
257 for CharSplits<'a, Sep> {
259 fn next_back(&mut self) -> Option<&'a str> {
260 if self.finished { return None }
262 if !self.allow_trailing_empty {
263 self.allow_trailing_empty = true;
264 match self.next_back() {
265 Some(elt) if !elt.is_empty() => return Some(elt),
266 _ => if self.finished { return None }
269 let len = self.string.len();
270 let mut next_split = None;
273 for (idx, byte) in self.string.bytes().enumerate().rev() {
274 if self.sep.matches(byte as char) && byte < 128u8 {
275 next_split = Some((idx, idx + 1));
280 for (idx, ch) in self.string.char_indices().rev() {
281 if self.sep.matches(ch) {
282 next_split = Some((idx, self.string.char_range_at(idx).next));
288 Some((a, b)) => unsafe {
289 let elt = raw::slice_unchecked(self.string, b, len);
290 self.string = raw::slice_unchecked(self.string, 0, a);
293 None => { self.finished = true; Some(self.string) }
298 impl<'a, Sep: CharEq> Iterator<&'a str> for CharSplitsN<'a, Sep> {
300 fn next(&mut self) -> Option<&'a str> {
303 if self.invert { self.iter.next_back() } else { self.iter.next() }
310 /// The internal state of an iterator that searches for matches of a substring
311 /// within a larger string using naive search
313 struct NaiveSearcher {
318 fn new() -> NaiveSearcher {
319 NaiveSearcher { position: 0 }
322 fn next(&mut self, haystack: &[u8], needle: &[u8]) -> Option<(uint, uint)> {
323 while self.position + needle.len() <= haystack.len() {
324 if haystack.slice(self.position, self.position + needle.len()) == needle {
325 let matchPos = self.position;
326 self.position += needle.len(); // add 1 for all matches
327 return Some((matchPos, matchPos + needle.len()));
336 /// The internal state of an iterator that searches for matches of a substring
337 /// within a larger string using two-way search
339 struct TwoWaySearcher {
350 impl TwoWaySearcher {
351 fn new(needle: &[u8]) -> TwoWaySearcher {
352 let (critPos1, period1) = TwoWaySearcher::maximal_suffix(needle, false);
353 let (critPos2, period2) = TwoWaySearcher::maximal_suffix(needle, true);
357 if critPos1 > critPos2 {
365 let byteset = needle.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a);
367 if needle.slice_to(critPos) == needle.slice_from(needle.len() - critPos) {
379 period: cmp::max(critPos, needle.len() - critPos) + 1,
383 memory: uint::MAX // Dummy value to signify that the period is long
389 fn next(&mut self, haystack: &[u8], needle: &[u8], longPeriod: bool) -> Option<(uint, uint)> {
391 // Check that we have room to search in
392 if self.position + needle.len() > haystack.len() {
396 // Quickly skip by large portions unrelated to our substring
397 if (self.byteset >> (haystack[self.position + needle.len() - 1] & 0x3f)) & 1 == 0 {
398 self.position += needle.len();
402 // See if the right part of the needle matches
403 let start = if longPeriod { self.critPos } else { cmp::max(self.critPos, self.memory) };
404 for i in range(start, needle.len()) {
405 if needle[i] != haystack[self.position + i] {
406 self.position += i - self.critPos + 1;
414 // See if the left part of the needle matches
415 let start = if longPeriod { 0 } else { self.memory };
416 for i in range(start, self.critPos).rev() {
417 if needle[i] != haystack[self.position + i] {
418 self.position += self.period;
420 self.memory = needle.len() - self.period;
426 // We have found a match!
427 let matchPos = self.position;
428 self.position += needle.len(); // add self.period for all matches
430 self.memory = 0; // set to needle.len() - self.period for all matches
432 return Some((matchPos, matchPos + needle.len()));
437 fn maximal_suffix(arr: &[u8], reversed: bool) -> (uint, uint) {
438 let mut left = -1; // Corresponds to i in the paper
439 let mut right = 0; // Corresponds to j in the paper
440 let mut offset = 1; // Corresponds to k in the paper
441 let mut period = 1; // Corresponds to p in the paper
443 while right + offset < arr.len() {
447 a = arr[left + offset];
448 b = arr[right + offset];
450 a = arr[right + offset];
451 b = arr[left + offset];
454 // Suffix is smaller, period is entire prefix so far.
457 period = right - left;
459 // Advance through repetition of the current period.
460 if offset == period {
467 // Suffix is larger, start over from current location.
478 /// The internal state of an iterator that searches for matches of a substring
479 /// within a larger string using a dynamically chosed search algorithm
482 Naive(NaiveSearcher),
483 TwoWay(TwoWaySearcher),
484 TwoWayLong(TwoWaySearcher)
488 fn new(haystack: &[u8], needle: &[u8]) -> Searcher {
490 if needle.len() > haystack.len() - 20 {
491 Naive(NaiveSearcher::new())
493 let searcher = TwoWaySearcher::new(needle);
494 if searcher.memory == uint::MAX { // If the period is long
503 /// An iterator over the start and end indices of the matches of a
504 /// substring within a larger string
506 pub struct MatchIndices<'a> {
513 /// An iterator over the substrings of a string separated by a given
516 pub struct StrSplits<'a> {
517 it: MatchIndices<'a>,
522 impl<'a> Iterator<(uint, uint)> for MatchIndices<'a> {
524 fn next(&mut self) -> Option<(uint, uint)> {
525 match self.searcher {
526 Naive(ref mut searcher)
527 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes()),
528 TwoWay(ref mut searcher)
529 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), false),
530 TwoWayLong(ref mut searcher)
531 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), true)
536 impl<'a> Iterator<&'a str> for StrSplits<'a> {
538 fn next(&mut self) -> Option<&'a str> {
539 if self.finished { return None; }
541 match self.it.next() {
542 Some((from, to)) => {
543 let ret = Some(self.it.haystack.slice(self.last_end, from));
548 self.finished = true;
549 Some(self.it.haystack.slice(self.last_end, self.it.haystack.len()))
556 Section: Comparing strings
559 // share the implementation of the lang-item vs. non-lang-item
562 fn eq_slice_(a: &str, b: &str) -> bool {
564 extern { fn memcmp(s1: *i8, s2: *i8, n: uint) -> i32; }
565 a.len() == b.len() && unsafe {
566 memcmp(a.as_ptr() as *i8,
572 /// Bytewise slice equality
576 pub fn eq_slice(a: &str, b: &str) -> bool {
580 /// Bytewise slice equality
583 pub fn eq_slice(a: &str, b: &str) -> bool {
591 /// Walk through `iter` checking that it's a valid UTF-8 sequence,
592 /// returning `true` in that case, or, if it is invalid, `false` with
593 /// `iter` reset such that it is pointing at the first byte in the
594 /// invalid sequence.
596 fn run_utf8_validation_iterator(iter: &mut slice::Items<u8>) -> bool {
598 // save the current thing we're pointing at.
601 // restore the iterator we had at the start of this codepoint.
602 macro_rules! err ( () => { {*iter = old; return false} });
603 macro_rules! next ( () => {
606 // we needed data, but there was none: error!
611 let first = match iter.next() {
613 // we're at the end of the iterator and a codepoint
614 // boundary at the same time, so this string is valid.
618 // ASCII characters are always valid, so only large
619 // bytes need more examination.
621 let w = utf8_char_width(first);
622 let second = next!();
623 // 2-byte encoding is for codepoints \u0080 to \u07ff
624 // first C2 80 last DF BF
625 // 3-byte encoding is for codepoints \u0800 to \uffff
626 // first E0 A0 80 last EF BF BF
627 // excluding surrogates codepoints \ud800 to \udfff
628 // ED A0 80 to ED BF BF
629 // 4-byte encoding is for codepoints \u10000 to \u10ffff
630 // first F0 90 80 80 last F4 8F BF BF
632 // Use the UTF-8 syntax from the RFC
634 // https://tools.ietf.org/html/rfc3629
636 // UTF8-2 = %xC2-DF UTF8-tail
637 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
638 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
639 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
640 // %xF4 %x80-8F 2( UTF8-tail )
642 2 => if second & 192 != TAG_CONT_U8 {err!()},
644 match (first, second, next!() & 192) {
645 (0xE0 , 0xA0 .. 0xBF, TAG_CONT_U8) |
646 (0xE1 .. 0xEC, 0x80 .. 0xBF, TAG_CONT_U8) |
647 (0xED , 0x80 .. 0x9F, TAG_CONT_U8) |
648 (0xEE .. 0xEF, 0x80 .. 0xBF, TAG_CONT_U8) => {}
653 match (first, second, next!() & 192, next!() & 192) {
654 (0xF0 , 0x90 .. 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
655 (0xF1 .. 0xF3, 0x80 .. 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
656 (0xF4 , 0x80 .. 0x8F, TAG_CONT_U8, TAG_CONT_U8) => {}
666 /// Determines if a vector of bytes contains valid UTF-8.
667 pub fn is_utf8(v: &[u8]) -> bool {
668 run_utf8_validation_iterator(&mut v.iter())
671 /// Determines if a vector of `u16` contains valid UTF-16
672 pub fn is_utf16(v: &[u16]) -> bool {
673 let mut it = v.iter();
674 macro_rules! next ( ($ret:expr) => {
675 match it.next() { Some(u) => *u, None => return $ret }
681 match char::from_u32(u as u32) {
684 let u2 = next!(false);
685 if u < 0xD7FF || u > 0xDBFF ||
686 u2 < 0xDC00 || u2 > 0xDFFF { return false; }
692 /// An iterator that decodes UTF-16 encoded codepoints from a vector
695 pub struct Utf16Items<'a> {
696 iter: slice::Items<'a, u16>
698 /// The possibilities for values decoded from a `u16` stream.
699 #[deriving(Eq, TotalEq, Clone, Show)]
701 /// A valid codepoint.
703 /// An invalid surrogate without its pair.
708 /// Convert `self` to a `char`, taking `LoneSurrogate`s to the
709 /// replacement character (U+FFFD).
711 pub fn to_char_lossy(&self) -> char {
714 LoneSurrogate(_) => '\uFFFD'
719 impl<'a> Iterator<Utf16Item> for Utf16Items<'a> {
720 fn next(&mut self) -> Option<Utf16Item> {
721 let u = match self.iter.next() {
726 if u < 0xD800 || 0xDFFF < u {
728 Some(ScalarValue(unsafe {mem::transmute(u as u32)}))
729 } else if u >= 0xDC00 {
730 // a trailing surrogate
731 Some(LoneSurrogate(u))
733 // preserve state for rewinding.
736 let u2 = match self.iter.next() {
739 None => return Some(LoneSurrogate(u))
741 if u2 < 0xDC00 || u2 > 0xDFFF {
742 // not a trailing surrogate so we're not a valid
743 // surrogate pair, so rewind to redecode u2 next time.
745 return Some(LoneSurrogate(u))
748 // all ok, so lets decode it.
749 let c = ((u - 0xD800) as u32 << 10 | (u2 - 0xDC00) as u32) + 0x1_0000;
750 Some(ScalarValue(unsafe {mem::transmute(c)}))
755 fn size_hint(&self) -> (uint, Option<uint>) {
756 let (low, high) = self.iter.size_hint();
757 // we could be entirely valid surrogates (2 elements per
758 // char), or entirely non-surrogates (1 element per char)
763 /// Create an iterator over the UTF-16 encoded codepoints in `v`,
764 /// returning invalid surrogates as `LoneSurrogate`s.
770 /// use std::str::{ScalarValue, LoneSurrogate};
772 /// // 𝄞mus<invalid>ic<invalid>
773 /// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
774 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
777 /// assert_eq!(str::utf16_items(v).collect::<Vec<_>>(),
778 /// vec![ScalarValue('𝄞'),
779 /// ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
780 /// LoneSurrogate(0xDD1E),
781 /// ScalarValue('i'), ScalarValue('c'),
782 /// LoneSurrogate(0xD834)]);
784 pub fn utf16_items<'a>(v: &'a [u16]) -> Utf16Items<'a> {
785 Utf16Items { iter : v.iter() }
788 /// Return a slice of `v` ending at (and not including) the first NUL
797 /// let mut v = ['a' as u16, 'b' as u16, 'c' as u16, 'd' as u16];
798 /// // no NULs so no change
799 /// assert_eq!(str::truncate_utf16_at_nul(v), v.as_slice());
803 /// assert_eq!(str::truncate_utf16_at_nul(v),
804 /// &['a' as u16, 'b' as u16]);
806 pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] {
807 match v.iter().position(|c| *c == 0) {
808 // don't include the 0
809 Some(i) => v.slice_to(i),
814 // https://tools.ietf.org/html/rfc3629
815 static UTF8_CHAR_WIDTH: [u8, ..256] = [
816 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
817 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
818 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
819 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
820 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
821 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
822 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
823 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
824 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
825 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
826 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
827 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
828 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
829 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
830 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
831 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
834 /// Given a first byte, determine how many bytes are in this UTF-8 character
836 pub fn utf8_char_width(b: u8) -> uint {
837 return UTF8_CHAR_WIDTH[b as uint] as uint;
840 /// Struct that contains a `char` and the index of the first byte of
841 /// the next `char` in a string. This can be used as a data structure
842 /// for iterating over the UTF-8 bytes of a string.
843 pub struct CharRange {
846 /// Index of the first byte of the next `char`
850 // Return the initial codepoint accumulator for the first byte.
851 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
852 // for width 3, and 3 bits for width 4
853 macro_rules! utf8_first_byte(
854 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
857 // return the value of $ch updated with continuation byte $byte
858 macro_rules! utf8_acc_cont_byte(
859 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63u8) as u32)
862 static TAG_CONT_U8: u8 = 128u8;
864 /// Unsafe operations
867 use container::Container;
871 use slice::{ImmutableVector};
872 use str::{is_utf8, StrSlice};
874 /// Converts a slice of bytes to a string slice without checking
875 /// that the string contains valid UTF-8.
876 pub unsafe fn from_utf8<'a>(v: &'a [u8]) -> &'a str {
880 /// Form a slice from a C string. Unsafe because the caller must ensure the
881 /// C string has the static lifetime, or else the return value may be
882 /// invalidated later.
883 pub unsafe fn c_str_to_static_slice(s: *i8) -> &'static str {
889 curr = s.offset(len as int);
891 let v = Slice { data: s, len: len };
892 assert!(is_utf8(::mem::transmute(v)));
896 /// Takes a bytewise (not UTF-8) slice from a string.
898 /// Returns the substring from [`begin`..`end`).
902 /// If begin is greater than end.
903 /// If end is greater than the length of the string.
905 pub unsafe fn slice_bytes<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
906 assert!(begin <= end);
907 assert!(end <= s.len());
908 slice_unchecked(s, begin, end)
911 /// Takes a bytewise (not UTF-8) slice from a string.
913 /// Returns the substring from [`begin`..`end`).
915 /// Caller must check slice boundaries!
917 pub unsafe fn slice_unchecked<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
918 mem::transmute(Slice {
919 data: s.as_ptr().offset(begin as int),
926 Section: Trait implementations
930 #[allow(missing_doc)]
932 use container::Container;
933 use cmp::{TotalOrd, Ordering, Less, Equal, Greater, Eq, Ord, Equiv, TotalEq};
935 use option::{Some, None};
936 use str::{Str, StrSlice, eq_slice};
938 impl<'a> TotalOrd for &'a str {
940 fn cmp(&self, other: & &'a str) -> Ordering {
941 for (s_b, o_b) in self.bytes().zip(other.bytes()) {
942 match s_b.cmp(&o_b) {
943 Greater => return Greater,
949 self.len().cmp(&other.len())
953 impl<'a> Eq for &'a str {
955 fn eq(&self, other: & &'a str) -> bool {
956 eq_slice((*self), (*other))
959 fn ne(&self, other: & &'a str) -> bool { !(*self).eq(other) }
962 impl<'a> TotalEq for &'a str {}
964 impl<'a> Ord for &'a str {
966 fn lt(&self, other: & &'a str) -> bool { self.cmp(other) == Less }
969 impl<'a, S: Str> Equiv<S> for &'a str {
971 fn equiv(&self, other: &S) -> bool { eq_slice(*self, other.as_slice()) }
978 /// Any string that can be represented as a slice
980 /// Work with `self` as a slice.
981 fn as_slice<'a>(&'a self) -> &'a str;
984 impl<'a> Str for &'a str {
986 fn as_slice<'a>(&'a self) -> &'a str { *self }
989 impl<'a> Container for &'a str {
991 fn len(&self) -> uint {
996 /// Methods for string slices
997 pub trait StrSlice<'a> {
998 /// Returns true if one string contains another
1002 /// - needle - The string to look for
1003 fn contains<'a>(&self, needle: &'a str) -> bool;
1005 /// Returns true if a string contains a char.
1009 /// - needle - The char to look for
1010 fn contains_char(&self, needle: char) -> bool;
1012 /// An iterator over the characters of `self`. Note, this iterates
1013 /// over unicode code-points, not unicode graphemes.
1018 /// let v: Vec<char> = "abc åäö".chars().collect();
1019 /// assert_eq!(v, vec!['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
1021 fn chars(&self) -> Chars<'a>;
1023 /// An iterator over the bytes of `self`
1024 fn bytes(&self) -> Bytes<'a>;
1026 /// An iterator over the characters of `self` and their byte offsets.
1027 fn char_indices(&self) -> CharOffsets<'a>;
1029 /// An iterator over substrings of `self`, separated by characters
1030 /// matched by `sep`.
1035 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1036 /// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
1038 /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_digit()).collect();
1039 /// assert_eq!(v, vec!["abc", "def", "ghi"]);
1041 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1042 /// assert_eq!(v, vec!["lion", "", "tiger", "leopard"]);
1044 /// let v: Vec<&str> = "".split('X').collect();
1045 /// assert_eq!(v, vec![""]);
1047 fn split<Sep: CharEq>(&self, sep: Sep) -> CharSplits<'a, Sep>;
1049 /// An iterator over substrings of `self`, separated by characters
1050 /// matched by `sep`, restricted to splitting at most `count`
1056 /// let v: Vec<&str> = "Mary had a little lambda".splitn(' ', 2).collect();
1057 /// assert_eq!(v, vec!["Mary", "had", "a little lambda"]);
1059 /// let v: Vec<&str> = "abc1def2ghi".splitn(|c: char| c.is_digit(), 1).collect();
1060 /// assert_eq!(v, vec!["abc", "def2ghi"]);
1062 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn('X', 2).collect();
1063 /// assert_eq!(v, vec!["lion", "", "tigerXleopard"]);
1065 /// let v: Vec<&str> = "abcXdef".splitn('X', 0).collect();
1066 /// assert_eq!(v, vec!["abcXdef"]);
1068 /// let v: Vec<&str> = "".splitn('X', 1).collect();
1069 /// assert_eq!(v, vec![""]);
1071 fn splitn<Sep: CharEq>(&self, sep: Sep, count: uint) -> CharSplitsN<'a, Sep>;
1073 /// An iterator over substrings of `self`, separated by characters
1074 /// matched by `sep`.
1076 /// Equivalent to `split`, except that the trailing substring
1077 /// is skipped if empty (terminator semantics).
1082 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1083 /// assert_eq!(v, vec!["A", "B"]);
1085 /// let v: Vec<&str> = "A..B..".split_terminator('.').collect();
1086 /// assert_eq!(v, vec!["A", "", "B", ""]);
1088 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').rev().collect();
1089 /// assert_eq!(v, vec!["lamb", "little", "a", "had", "Mary"]);
1091 /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_digit()).rev().collect();
1092 /// assert_eq!(v, vec!["ghi", "def", "abc"]);
1094 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').rev().collect();
1095 /// assert_eq!(v, vec!["leopard", "tiger", "", "lion"]);
1097 fn split_terminator<Sep: CharEq>(&self, sep: Sep) -> CharSplits<'a, Sep>;
1099 /// An iterator over substrings of `self`, separated by characters
1100 /// matched by `sep`, starting from the end of the string.
1101 /// Restricted to splitting at most `count` times.
1106 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(' ', 2).collect();
1107 /// assert_eq!(v, vec!["lamb", "little", "Mary had a"]);
1109 /// let v: Vec<&str> = "abc1def2ghi".rsplitn(|c: char| c.is_digit(), 1).collect();
1110 /// assert_eq!(v, vec!["ghi", "abc1def"]);
1112 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn('X', 2).collect();
1113 /// assert_eq!(v, vec!["leopard", "tiger", "lionX"]);
1115 fn rsplitn<Sep: CharEq>(&self, sep: Sep, count: uint) -> CharSplitsN<'a, Sep>;
1117 /// An iterator over the start and end indices of the disjoint
1118 /// matches of `sep` within `self`.
1120 /// That is, each returned value `(start, end)` satisfies
1121 /// `self.slice(start, end) == sep`. For matches of `sep` within
1122 /// `self` that overlap, only the indicies corresponding to the
1123 /// first match are returned.
1128 /// let v: Vec<(uint, uint)> = "abcXXXabcYYYabc".match_indices("abc").collect();
1129 /// assert_eq!(v, vec![(0,3), (6,9), (12,15)]);
1131 /// let v: Vec<(uint, uint)> = "1abcabc2".match_indices("abc").collect();
1132 /// assert_eq!(v, vec![(1,4), (4,7)]);
1134 /// let v: Vec<(uint, uint)> = "ababa".match_indices("aba").collect();
1135 /// assert_eq!(v, vec![(0, 3)]); // only the first `aba`
1137 fn match_indices(&self, sep: &'a str) -> MatchIndices<'a>;
1139 /// An iterator over the substrings of `self` separated by `sep`.
1144 /// let v: Vec<&str> = "abcXXXabcYYYabc".split_str("abc").collect();
1145 /// assert_eq!(v, vec!["", "XXX", "YYY", ""]);
1147 /// let v: Vec<&str> = "1abcabc2".split_str("abc").collect();
1148 /// assert_eq!(v, vec!["1", "", "2"]);
1150 fn split_str(&self, &'a str) -> StrSplits<'a>;
1152 /// An iterator over the lines of a string (subsequences separated
1153 /// by `\n`). This does not include the empty string after a
1159 /// let four_lines = "foo\nbar\n\nbaz\n";
1160 /// let v: Vec<&str> = four_lines.lines().collect();
1161 /// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
1163 fn lines(&self) -> CharSplits<'a, char>;
1165 /// An iterator over the lines of a string, separated by either
1166 /// `\n` or `\r\n`. As with `.lines()`, this does not include an
1167 /// empty trailing line.
1172 /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
1173 /// let v: Vec<&str> = four_lines.lines_any().collect();
1174 /// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
1176 fn lines_any(&self) -> AnyLines<'a>;
1178 /// An iterator over the words of a string (subsequences separated
1179 /// by any sequence of whitespace). Sequences of whitespace are
1180 /// collapsed, so empty "words" are not included.
1185 /// let some_words = " Mary had\ta little \n\t lamb";
1186 /// let v: Vec<&str> = some_words.words().collect();
1187 /// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
1189 fn words(&self) -> Words<'a>;
1191 /// Returns true if the string contains only whitespace.
1193 /// Whitespace characters are determined by `char::is_whitespace`.
1198 /// assert!(" \t\n".is_whitespace());
1199 /// assert!("".is_whitespace());
1201 /// assert!( !"abc".is_whitespace());
1203 fn is_whitespace(&self) -> bool;
1205 /// Returns true if the string contains only alphanumeric code
1208 /// Alphanumeric characters are determined by `char::is_alphanumeric`.
1213 /// assert!("Löwe老虎Léopard123".is_alphanumeric());
1214 /// assert!("".is_alphanumeric());
1216 /// assert!( !" &*~".is_alphanumeric());
1218 fn is_alphanumeric(&self) -> bool;
1220 /// Returns the number of Unicode code points (`char`) that a
1223 /// This does not perform any normalization, and is `O(n)`, since
1224 /// UTF-8 is a variable width encoding of code points.
1226 /// *Warning*: The number of code points in a string does not directly
1227 /// correspond to the number of visible characters or width of the
1228 /// visible text due to composing characters, and double- and
1229 /// zero-width ones.
1231 /// See also `.len()` for the byte length.
1236 /// // composed forms of `ö` and `é`
1237 /// let c = "Löwe 老虎 Léopard"; // German, Simplified Chinese, French
1238 /// // decomposed forms of `ö` and `é`
1239 /// let d = "Lo\u0308we 老虎 Le\u0301opard";
1241 /// assert_eq!(c.char_len(), 15);
1242 /// assert_eq!(d.char_len(), 17);
1244 /// assert_eq!(c.len(), 21);
1245 /// assert_eq!(d.len(), 23);
1247 /// // the two strings *look* the same
1248 /// println!("{}", c);
1249 /// println!("{}", d);
1251 fn char_len(&self) -> uint;
1253 /// Returns a slice of the given string from the byte range
1254 /// [`begin`..`end`).
1256 /// This operation is `O(1)`.
1258 /// Fails when `begin` and `end` do not point to valid characters
1259 /// or point beyond the last character of the string.
1261 /// See also `slice_to` and `slice_from` for slicing prefixes and
1262 /// suffixes of strings, and `slice_chars` for slicing based on
1263 /// code point counts.
1268 /// let s = "Löwe 老虎 Léopard";
1269 /// assert_eq!(s.slice(0, 1), "L");
1271 /// assert_eq!(s.slice(1, 9), "öwe 老");
1273 /// // these will fail:
1274 /// // byte 2 lies within `ö`:
1275 /// // s.slice(2, 3);
1277 /// // byte 8 lies within `老`
1278 /// // s.slice(1, 8);
1280 /// // byte 100 is outside the string
1281 /// // s.slice(3, 100);
1283 fn slice(&self, begin: uint, end: uint) -> &'a str;
1285 /// Returns a slice of the string from `begin` to its end.
1287 /// Equivalent to `self.slice(begin, self.len())`.
1289 /// Fails when `begin` does not point to a valid character, or is
1292 /// See also `slice`, `slice_to` and `slice_chars`.
1293 fn slice_from(&self, begin: uint) -> &'a str;
1295 /// Returns a slice of the string from the beginning to byte
1298 /// Equivalent to `self.slice(0, end)`.
1300 /// Fails when `end` does not point to a valid character, or is
1303 /// See also `slice`, `slice_from` and `slice_chars`.
1304 fn slice_to(&self, end: uint) -> &'a str;
1306 /// Returns a slice of the string from the character range
1307 /// [`begin`..`end`).
1309 /// That is, start at the `begin`-th code point of the string and
1310 /// continue to the `end`-th code point. This does not detect or
1311 /// handle edge cases such as leaving a combining character as the
1312 /// first code point of the string.
1314 /// Due to the design of UTF-8, this operation is `O(end)`.
1315 /// See `slice`, `slice_to` and `slice_from` for `O(1)`
1316 /// variants that use byte indices rather than code point
1319 /// Fails if `begin` > `end` or the either `begin` or `end` are
1320 /// beyond the last character of the string.
1325 /// let s = "Löwe 老虎 Léopard";
1326 /// assert_eq!(s.slice_chars(0, 4), "Löwe");
1327 /// assert_eq!(s.slice_chars(5, 7), "老虎");
1329 fn slice_chars(&self, begin: uint, end: uint) -> &'a str;
1331 /// Returns true if `needle` is a prefix of the string.
1332 fn starts_with(&self, needle: &str) -> bool;
1334 /// Returns true if `needle` is a suffix of the string.
1335 fn ends_with(&self, needle: &str) -> bool;
1337 /// Returns a string with leading and trailing whitespace removed.
1338 fn trim(&self) -> &'a str;
1340 /// Returns a string with leading whitespace removed.
1341 fn trim_left(&self) -> &'a str;
1343 /// Returns a string with trailing whitespace removed.
1344 fn trim_right(&self) -> &'a str;
1346 /// Returns a string with characters that match `to_trim` removed.
1350 /// * to_trim - a character matcher
1355 /// assert_eq!("11foo1bar11".trim_chars('1'), "foo1bar")
1356 /// assert_eq!("12foo1bar12".trim_chars(&['1', '2']), "foo1bar")
1357 /// assert_eq!("123foo1bar123".trim_chars(|c: char| c.is_digit()), "foo1bar")
1359 fn trim_chars<C: CharEq>(&self, to_trim: C) -> &'a str;
1361 /// Returns a string with leading `chars_to_trim` removed.
1365 /// * to_trim - a character matcher
1370 /// assert_eq!("11foo1bar11".trim_left_chars('1'), "foo1bar11")
1371 /// assert_eq!("12foo1bar12".trim_left_chars(&['1', '2']), "foo1bar12")
1372 /// assert_eq!("123foo1bar123".trim_left_chars(|c: char| c.is_digit()), "foo1bar123")
1374 fn trim_left_chars<C: CharEq>(&self, to_trim: C) -> &'a str;
1376 /// Returns a string with trailing `chars_to_trim` removed.
1380 /// * to_trim - a character matcher
1385 /// assert_eq!("11foo1bar11".trim_right_chars('1'), "11foo1bar")
1386 /// assert_eq!("12foo1bar12".trim_right_chars(&['1', '2']), "12foo1bar")
1387 /// assert_eq!("123foo1bar123".trim_right_chars(|c: char| c.is_digit()), "123foo1bar")
1389 fn trim_right_chars<C: CharEq>(&self, to_trim: C) -> &'a str;
1391 /// Check that `index`-th byte lies at the start and/or end of a
1392 /// UTF-8 code point sequence.
1394 /// The start and end of the string (when `index == self.len()`)
1395 /// are considered to be boundaries.
1397 /// Fails if `index` is greater than `self.len()`.
1402 /// let s = "Löwe 老虎 Léopard";
1403 /// assert!(s.is_char_boundary(0));
1405 /// assert!(s.is_char_boundary(6));
1406 /// assert!(s.is_char_boundary(s.len()));
1408 /// // second byte of `ö`
1409 /// assert!(!s.is_char_boundary(2));
1411 /// // third byte of `老`
1412 /// assert!(!s.is_char_boundary(8));
1414 fn is_char_boundary(&self, index: uint) -> bool;
1416 /// Pluck a character out of a string and return the index of the next
1419 /// This function can be used to iterate over the unicode characters of a
1424 /// This example manually iterate through the characters of a
1425 /// string; this should normally by done by `.chars()` or
1426 /// `.char_indices`.
1429 /// use std::str::CharRange;
1431 /// let s = "中华Việt Nam";
1433 /// while i < s.len() {
1434 /// let CharRange {ch, next} = s.char_range_at(i);
1435 /// println!("{}: {}", i, ch);
1457 /// * s - The string
1458 /// * i - The byte offset of the char to extract
1462 /// A record {ch: char, next: uint} containing the char value and the byte
1463 /// index of the next unicode character.
1467 /// If `i` is greater than or equal to the length of the string.
1468 /// If `i` is not the index of the beginning of a valid UTF-8 character.
1469 fn char_range_at(&self, start: uint) -> CharRange;
1471 /// Given a byte position and a str, return the previous char and its position.
1473 /// This function can be used to iterate over a unicode string in reverse.
1475 /// Returns 0 for next index if called on start index 0.
1476 fn char_range_at_reverse(&self, start: uint) -> CharRange;
1478 /// Plucks the character starting at the `i`th byte of a string
1479 fn char_at(&self, i: uint) -> char;
1481 /// Plucks the character ending at the `i`th byte of a string
1482 fn char_at_reverse(&self, i: uint) -> char;
1484 /// Work with the byte buffer of a string as a byte slice.
1485 fn as_bytes(&self) -> &'a [u8];
1487 /// Returns the byte index of the first character of `self` that
1488 /// matches `search`.
1492 /// `Some` containing the byte index of the last matching character
1493 /// or `None` if there is no match
1498 /// let s = "Löwe 老虎 Léopard";
1500 /// assert_eq!(s.find('L'), Some(0));
1501 /// assert_eq!(s.find('é'), Some(14));
1503 /// // the first space
1504 /// assert_eq!(s.find(|c: char| c.is_whitespace()), Some(5));
1506 /// // neither are found
1507 /// assert_eq!(s.find(&['1', '2']), None);
1509 fn find<C: CharEq>(&self, search: C) -> Option<uint>;
1511 /// Returns the byte index of the last character of `self` that
1512 /// matches `search`.
1516 /// `Some` containing the byte index of the last matching character
1517 /// or `None` if there is no match.
1522 /// let s = "Löwe 老虎 Léopard";
1524 /// assert_eq!(s.rfind('L'), Some(13));
1525 /// assert_eq!(s.rfind('é'), Some(14));
1527 /// // the second space
1528 /// assert_eq!(s.rfind(|c: char| c.is_whitespace()), Some(12));
1530 /// // searches for an occurrence of either `1` or `2`, but neither are found
1531 /// assert_eq!(s.rfind(&['1', '2']), None);
1533 fn rfind<C: CharEq>(&self, search: C) -> Option<uint>;
1535 /// Returns the byte index of the first matching substring
1539 /// * `needle` - The string to search for
1543 /// `Some` containing the byte index of the first matching substring
1544 /// or `None` if there is no match.
1549 /// let s = "Löwe 老虎 Léopard";
1551 /// assert_eq!(s.find_str("老虎 L"), Some(6));
1552 /// assert_eq!(s.find_str("muffin man"), None);
1554 fn find_str(&self, &str) -> Option<uint>;
1556 /// Retrieves the first character from a string slice and returns
1557 /// it. This does not allocate a new string; instead, it returns a
1558 /// slice that point one character beyond the character that was
1559 /// shifted. If the string does not contain any characters,
1560 /// a tuple of None and an empty string is returned instead.
1565 /// let s = "Löwe 老虎 Léopard";
1566 /// let (c, s1) = s.slice_shift_char();
1567 /// assert_eq!(c, Some('L'));
1568 /// assert_eq!(s1, "öwe 老虎 Léopard");
1570 /// let (c, s2) = s1.slice_shift_char();
1571 /// assert_eq!(c, Some('ö'));
1572 /// assert_eq!(s2, "we 老虎 Léopard");
1574 fn slice_shift_char(&self) -> (Option<char>, &'a str);
1576 /// Returns the byte offset of an inner slice relative to an enclosing outer slice.
1578 /// Fails if `inner` is not a direct slice contained within self.
1583 /// let string = "a\nb\nc";
1584 /// let lines: Vec<&str> = string.lines().collect();
1585 /// let lines = lines.as_slice();
1587 /// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
1588 /// assert!(string.subslice_offset(lines[1]) == 2); // &"b"
1589 /// assert!(string.subslice_offset(lines[2]) == 4); // &"c"
1591 fn subslice_offset(&self, inner: &str) -> uint;
1593 /// Return an unsafe pointer to the strings buffer.
1595 /// The caller must ensure that the string outlives this pointer,
1596 /// and that it is not reallocated (e.g. by pushing to the
1598 fn as_ptr(&self) -> *u8;
1601 impl<'a> StrSlice<'a> for &'a str {
1603 fn contains<'a>(&self, needle: &'a str) -> bool {
1604 self.find_str(needle).is_some()
1608 fn contains_char(&self, needle: char) -> bool {
1609 self.find(needle).is_some()
1613 fn chars(&self) -> Chars<'a> {
1614 Chars{string: *self}
1618 fn bytes(&self) -> Bytes<'a> {
1619 self.as_bytes().iter().map(|&b| b)
1623 fn char_indices(&self) -> CharOffsets<'a> {
1624 CharOffsets{string: *self, iter: self.chars()}
1628 fn split<Sep: CharEq>(&self, sep: Sep) -> CharSplits<'a, Sep> {
1631 only_ascii: sep.only_ascii(),
1633 allow_trailing_empty: true,
1639 fn splitn<Sep: CharEq>(&self, sep: Sep, count: uint)
1640 -> CharSplitsN<'a, Sep> {
1642 iter: self.split(sep),
1649 fn split_terminator<Sep: CharEq>(&self, sep: Sep)
1650 -> CharSplits<'a, Sep> {
1652 allow_trailing_empty: false,
1658 fn rsplitn<Sep: CharEq>(&self, sep: Sep, count: uint)
1659 -> CharSplitsN<'a, Sep> {
1661 iter: self.split(sep),
1668 fn match_indices(&self, sep: &'a str) -> MatchIndices<'a> {
1669 assert!(!sep.is_empty())
1673 searcher: Searcher::new(self.as_bytes(), sep.as_bytes())
1678 fn split_str(&self, sep: &'a str) -> StrSplits<'a> {
1680 it: self.match_indices(sep),
1687 fn lines(&self) -> CharSplits<'a, char> {
1688 self.split_terminator('\n')
1691 fn lines_any(&self) -> AnyLines<'a> {
1692 self.lines().map(|line| {
1694 if l > 0 && line[l - 1] == '\r' as u8 { line.slice(0, l - 1) }
1700 fn words(&self) -> Words<'a> {
1701 self.split(char::is_whitespace).filter(|s| !s.is_empty())
1705 fn is_whitespace(&self) -> bool { self.chars().all(char::is_whitespace) }
1708 fn is_alphanumeric(&self) -> bool { self.chars().all(char::is_alphanumeric) }
1711 fn char_len(&self) -> uint { self.chars().len() }
1714 fn slice(&self, begin: uint, end: uint) -> &'a str {
1715 assert!(self.is_char_boundary(begin) && self.is_char_boundary(end));
1716 unsafe { raw::slice_bytes(*self, begin, end) }
1720 fn slice_from(&self, begin: uint) -> &'a str {
1721 self.slice(begin, self.len())
1725 fn slice_to(&self, end: uint) -> &'a str {
1726 assert!(self.is_char_boundary(end));
1727 unsafe { raw::slice_bytes(*self, 0, end) }
1730 fn slice_chars(&self, begin: uint, end: uint) -> &'a str {
1731 assert!(begin <= end);
1733 let mut begin_byte = None;
1734 let mut end_byte = None;
1736 // This could be even more efficient by not decoding,
1737 // only finding the char boundaries
1738 for (idx, _) in self.char_indices() {
1739 if count == begin { begin_byte = Some(idx); }
1740 if count == end { end_byte = Some(idx); break; }
1743 if begin_byte.is_none() && count == begin { begin_byte = Some(self.len()) }
1744 if end_byte.is_none() && count == end { end_byte = Some(self.len()) }
1746 match (begin_byte, end_byte) {
1747 (None, _) => fail!("slice_chars: `begin` is beyond end of string"),
1748 (_, None) => fail!("slice_chars: `end` is beyond end of string"),
1749 (Some(a), Some(b)) => unsafe { raw::slice_bytes(*self, a, b) }
1754 fn starts_with<'a>(&self, needle: &'a str) -> bool {
1755 let n = needle.len();
1756 self.len() >= n && needle.as_bytes() == self.as_bytes().slice_to(n)
1760 fn ends_with(&self, needle: &str) -> bool {
1761 let (m, n) = (self.len(), needle.len());
1762 m >= n && needle.as_bytes() == self.as_bytes().slice_from(m - n)
1766 fn trim(&self) -> &'a str {
1767 self.trim_left().trim_right()
1771 fn trim_left(&self) -> &'a str {
1772 self.trim_left_chars(char::is_whitespace)
1776 fn trim_right(&self) -> &'a str {
1777 self.trim_right_chars(char::is_whitespace)
1781 fn trim_chars<C: CharEq>(&self, mut to_trim: C) -> &'a str {
1782 let cur = match self.find(|c: char| !to_trim.matches(c)) {
1784 Some(i) => unsafe { raw::slice_bytes(*self, i, self.len()) }
1786 match cur.rfind(|c: char| !to_trim.matches(c)) {
1789 let right = cur.char_range_at(i).next;
1790 unsafe { raw::slice_bytes(cur, 0, right) }
1796 fn trim_left_chars<C: CharEq>(&self, mut to_trim: C) -> &'a str {
1797 match self.find(|c: char| !to_trim.matches(c)) {
1799 Some(first) => unsafe { raw::slice_bytes(*self, first, self.len()) }
1804 fn trim_right_chars<C: CharEq>(&self, mut to_trim: C) -> &'a str {
1805 match self.rfind(|c: char| !to_trim.matches(c)) {
1808 let next = self.char_range_at(last).next;
1809 unsafe { raw::slice_bytes(*self, 0u, next) }
1815 fn is_char_boundary(&self, index: uint) -> bool {
1816 if index == self.len() { return true; }
1817 if index > self.len() { return false; }
1818 let b = self[index];
1819 return b < 128u8 || b >= 192u8;
1823 fn char_range_at(&self, i: uint) -> CharRange {
1824 if self[i] < 128u8 {
1825 return CharRange {ch: self[i] as char, next: i + 1 };
1828 // Multibyte case is a fn to allow char_range_at to inline cleanly
1829 fn multibyte_char_range_at(s: &str, i: uint) -> CharRange {
1830 let mut val = s[i] as u32;
1831 let w = UTF8_CHAR_WIDTH[val as uint] as uint;
1834 val = utf8_first_byte!(val, w);
1835 val = utf8_acc_cont_byte!(val, s[i + 1]);
1836 if w > 2 { val = utf8_acc_cont_byte!(val, s[i + 2]); }
1837 if w > 3 { val = utf8_acc_cont_byte!(val, s[i + 3]); }
1839 return CharRange {ch: unsafe { mem::transmute(val) }, next: i + w};
1842 return multibyte_char_range_at(*self, i);
1846 fn char_range_at_reverse(&self, start: uint) -> CharRange {
1847 let mut prev = start;
1849 prev = prev.saturating_sub(1);
1850 if self[prev] < 128 { return CharRange{ch: self[prev] as char, next: prev} }
1852 // Multibyte case is a fn to allow char_range_at_reverse to inline cleanly
1853 fn multibyte_char_range_at_reverse(s: &str, mut i: uint) -> CharRange {
1854 // while there is a previous byte == 10......
1855 while i > 0 && s[i] & 192u8 == TAG_CONT_U8 {
1859 let mut val = s[i] as u32;
1860 let w = UTF8_CHAR_WIDTH[val as uint] as uint;
1863 val = utf8_first_byte!(val, w);
1864 val = utf8_acc_cont_byte!(val, s[i + 1]);
1865 if w > 2 { val = utf8_acc_cont_byte!(val, s[i + 2]); }
1866 if w > 3 { val = utf8_acc_cont_byte!(val, s[i + 3]); }
1868 return CharRange {ch: unsafe { mem::transmute(val) }, next: i};
1871 return multibyte_char_range_at_reverse(*self, prev);
1875 fn char_at(&self, i: uint) -> char {
1876 self.char_range_at(i).ch
1880 fn char_at_reverse(&self, i: uint) -> char {
1881 self.char_range_at_reverse(i).ch
1885 fn as_bytes(&self) -> &'a [u8] {
1886 unsafe { mem::transmute(*self) }
1889 fn find<C: CharEq>(&self, mut search: C) -> Option<uint> {
1890 if search.only_ascii() {
1891 self.bytes().position(|b| search.matches(b as char))
1893 for (index, c) in self.char_indices() {
1894 if search.matches(c) { return Some(index); }
1900 fn rfind<C: CharEq>(&self, mut search: C) -> Option<uint> {
1901 if search.only_ascii() {
1902 self.bytes().rposition(|b| search.matches(b as char))
1904 for (index, c) in self.char_indices().rev() {
1905 if search.matches(c) { return Some(index); }
1911 fn find_str(&self, needle: &str) -> Option<uint> {
1912 if needle.is_empty() {
1915 self.match_indices(needle)
1917 .map(|(start, _end)| start)
1922 fn slice_shift_char(&self) -> (Option<char>, &'a str) {
1923 if self.is_empty() {
1924 return (None, *self);
1926 let CharRange {ch, next} = self.char_range_at(0u);
1927 let next_s = unsafe { raw::slice_bytes(*self, next, self.len()) };
1928 return (Some(ch), next_s);
1932 fn subslice_offset(&self, inner: &str) -> uint {
1933 let a_start = self.as_ptr() as uint;
1934 let a_end = a_start + self.len();
1935 let b_start = inner.as_ptr() as uint;
1936 let b_end = b_start + inner.len();
1938 assert!(a_start <= b_start);
1939 assert!(b_end <= a_end);
1944 fn as_ptr(&self) -> *u8 {
1949 impl<'a> Default for &'a str {
1950 fn default() -> &'a str { "" }