]> git.lizzy.rs Git - rust.git/blob - src/libcore/str.rs
Removed some unnecessary RefCells from resolve
[rust.git] / src / libcore / str.rs
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.
4 //
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.
10 //
11 // ignore-lexer-test FIXME #15679
12
13 //! String manipulation
14 //!
15 //! For more details, see std::str
16
17 #![doc(primitive = "str")]
18
19 use mem;
20 use char;
21 use char::Char;
22 use clone::Clone;
23 use cmp;
24 use cmp::{PartialEq, Eq};
25 use collections::Collection;
26 use default::Default;
27 use iter::{Map, Iterator};
28 use iter::{DoubleEndedIterator, ExactSize};
29 use iter::range;
30 use num::{CheckedMul, Saturating};
31 use option::{Option, None, Some};
32 use raw::Repr;
33 use slice::{ImmutableSlice, MutableSlice};
34 use slice;
35 use uint;
36
37 /*
38 Section: Creating a string
39 */
40
41 /// Converts a vector to a string slice without performing any allocations.
42 ///
43 /// Once the slice has been validated as utf-8, it is transmuted in-place and
44 /// returned as a '&str' instead of a '&[u8]'
45 ///
46 /// Returns None if the slice is not utf-8.
47 pub fn from_utf8<'a>(v: &'a [u8]) -> Option<&'a str> {
48     if is_utf8(v) {
49         Some(unsafe { raw::from_utf8(v) })
50     } else { None }
51 }
52
53 /// Something that can be used to compare against a character
54 pub trait CharEq {
55     /// Determine if the splitter should split at the given character
56     fn matches(&mut self, char) -> bool;
57     /// Indicate if this is only concerned about ASCII characters,
58     /// which can allow for a faster implementation.
59     fn only_ascii(&self) -> bool;
60 }
61
62 impl CharEq for char {
63     #[inline]
64     fn matches(&mut self, c: char) -> bool { *self == c }
65
66     #[inline]
67     fn only_ascii(&self) -> bool { (*self as uint) < 128 }
68 }
69
70 impl<'a> CharEq for |char|: 'a -> bool {
71     #[inline]
72     fn matches(&mut self, c: char) -> bool { (*self)(c) }
73
74     #[inline]
75     fn only_ascii(&self) -> bool { false }
76 }
77
78 impl CharEq for extern "Rust" fn(char) -> bool {
79     #[inline]
80     fn matches(&mut self, c: char) -> bool { (*self)(c) }
81
82     #[inline]
83     fn only_ascii(&self) -> bool { false }
84 }
85
86 impl<'a> CharEq for &'a [char] {
87     #[inline]
88     fn matches(&mut self, c: char) -> bool {
89         self.iter().any(|&mut m| m.matches(c))
90     }
91
92     #[inline]
93     fn only_ascii(&self) -> bool {
94         self.iter().all(|m| m.only_ascii())
95     }
96 }
97
98 /*
99 Section: Iterators
100 */
101
102 /// Iterator for the char (representing *Unicode Scalar Values*) of a string
103 ///
104 /// Created with the method `.chars()`.
105 #[deriving(Clone)]
106 pub struct Chars<'a> {
107     iter: slice::Items<'a, u8>
108 }
109
110 // Return the initial codepoint accumulator for the first byte.
111 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
112 // for width 3, and 3 bits for width 4
113 macro_rules! utf8_first_byte(
114     ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
115 )
116
117 // return the value of $ch updated with continuation byte $byte
118 macro_rules! utf8_acc_cont_byte(
119     ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & CONT_MASK) as u32)
120 )
121
122 macro_rules! utf8_is_cont_byte(
123     ($byte:expr) => (($byte & !CONT_MASK) == TAG_CONT_U8)
124 )
125
126 #[inline]
127 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
128     match opt {
129         Some(&byte) => byte,
130         None => 0,
131     }
132 }
133
134 impl<'a> Iterator<char> for Chars<'a> {
135     #[inline]
136     fn next(&mut self) -> Option<char> {
137         // Decode UTF-8, using the valid UTF-8 invariant
138         let x = match self.iter.next() {
139             None => return None,
140             Some(&next_byte) if next_byte < 128 => return Some(next_byte as char),
141             Some(&next_byte) => next_byte,
142         };
143
144         // Multibyte case follows
145         // Decode from a byte combination out of: [[[x y] z] w]
146         // NOTE: Performance is sensitive to the exact formulation here
147         let init = utf8_first_byte!(x, 2);
148         let y = unwrap_or_0(self.iter.next());
149         let mut ch = utf8_acc_cont_byte!(init, y);
150         if x >= 0xE0 {
151             // [[x y z] w] case
152             // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
153             let z = unwrap_or_0(self.iter.next());
154             let y_z = utf8_acc_cont_byte!((y & CONT_MASK) as u32, z);
155             ch = init << 12 | y_z;
156             if x >= 0xF0 {
157                 // [x y z w] case
158                 // use only the lower 3 bits of `init`
159                 let w = unwrap_or_0(self.iter.next());
160                 ch = (init & 7) << 18 | utf8_acc_cont_byte!(y_z, w);
161             }
162         }
163
164         // str invariant says `ch` is a valid Unicode Scalar Value
165         unsafe {
166             Some(mem::transmute(ch))
167         }
168     }
169
170     #[inline]
171     fn size_hint(&self) -> (uint, Option<uint>) {
172         let (len, _) = self.iter.size_hint();
173         (len.saturating_add(3) / 4, Some(len))
174     }
175 }
176
177 impl<'a> DoubleEndedIterator<char> for Chars<'a> {
178     #[inline]
179     fn next_back(&mut self) -> Option<char> {
180         let w = match self.iter.next_back() {
181             None => return None,
182             Some(&back_byte) if back_byte < 128 => return Some(back_byte as char),
183             Some(&back_byte) => back_byte,
184         };
185
186         // Multibyte case follows
187         // Decode from a byte combination out of: [x [y [z w]]]
188         let mut ch;
189         let z = unwrap_or_0(self.iter.next_back());
190         ch = utf8_first_byte!(z, 2);
191         if utf8_is_cont_byte!(z) {
192             let y = unwrap_or_0(self.iter.next_back());
193             ch = utf8_first_byte!(y, 3);
194             if utf8_is_cont_byte!(y) {
195                 let x = unwrap_or_0(self.iter.next_back());
196                 ch = utf8_first_byte!(x, 4);
197                 ch = utf8_acc_cont_byte!(ch, y);
198             }
199             ch = utf8_acc_cont_byte!(ch, z);
200         }
201         ch = utf8_acc_cont_byte!(ch, w);
202
203         // str invariant says `ch` is a valid Unicode Scalar Value
204         unsafe {
205             Some(mem::transmute(ch))
206         }
207     }
208 }
209
210 /// External iterator for a string's characters and their byte offsets.
211 /// Use with the `std::iter` module.
212 #[deriving(Clone)]
213 pub struct CharOffsets<'a> {
214     front_offset: uint,
215     iter: Chars<'a>,
216 }
217
218 impl<'a> Iterator<(uint, char)> for CharOffsets<'a> {
219     #[inline]
220     fn next(&mut self) -> Option<(uint, char)> {
221         let (pre_len, _) = self.iter.iter.size_hint();
222         match self.iter.next() {
223             None => None,
224             Some(ch) => {
225                 let index = self.front_offset;
226                 let (len, _) = self.iter.iter.size_hint();
227                 self.front_offset += pre_len - len;
228                 Some((index, ch))
229             }
230         }
231     }
232
233     #[inline]
234     fn size_hint(&self) -> (uint, Option<uint>) {
235         self.iter.size_hint()
236     }
237 }
238
239 impl<'a> DoubleEndedIterator<(uint, char)> for CharOffsets<'a> {
240     #[inline]
241     fn next_back(&mut self) -> Option<(uint, char)> {
242         match self.iter.next_back() {
243             None => None,
244             Some(ch) => {
245                 let (len, _) = self.iter.iter.size_hint();
246                 let index = self.front_offset + len;
247                 Some((index, ch))
248             }
249         }
250     }
251 }
252
253 /// External iterator for a string's bytes.
254 /// Use with the `std::iter` module.
255 pub type Bytes<'a> =
256     Map<'a, &'a u8, u8, slice::Items<'a, u8>>;
257
258 /// An iterator over the substrings of a string, separated by `sep`.
259 #[deriving(Clone)]
260 pub struct CharSplits<'a, Sep> {
261     /// The slice remaining to be iterated
262     string: &'a str,
263     sep: Sep,
264     /// Whether an empty string at the end is allowed
265     allow_trailing_empty: bool,
266     only_ascii: bool,
267     finished: bool,
268 }
269
270 /// An iterator over the substrings of a string, separated by `sep`,
271 /// splitting at most `count` times.
272 #[deriving(Clone)]
273 pub struct CharSplitsN<'a, Sep> {
274     iter: CharSplits<'a, Sep>,
275     /// The number of splits remaining
276     count: uint,
277     invert: bool,
278 }
279
280 /// An iterator over the lines of a string, separated by either `\n` or (`\r\n`).
281 pub type AnyLines<'a> =
282     Map<'a, &'a str, &'a str, CharSplits<'a, char>>;
283
284 impl<'a, Sep> CharSplits<'a, Sep> {
285     #[inline]
286     fn get_end(&mut self) -> Option<&'a str> {
287         if !self.finished && (self.allow_trailing_empty || self.string.len() > 0) {
288             self.finished = true;
289             Some(self.string)
290         } else {
291             None
292         }
293     }
294 }
295
296 impl<'a, Sep: CharEq> Iterator<&'a str> for CharSplits<'a, Sep> {
297     #[inline]
298     fn next(&mut self) -> Option<&'a str> {
299         if self.finished { return None }
300
301         let mut next_split = None;
302         if self.only_ascii {
303             for (idx, byte) in self.string.bytes().enumerate() {
304                 if self.sep.matches(byte as char) && byte < 128u8 {
305                     next_split = Some((idx, idx + 1));
306                     break;
307                 }
308             }
309         } else {
310             for (idx, ch) in self.string.char_indices() {
311                 if self.sep.matches(ch) {
312                     next_split = Some((idx, self.string.char_range_at(idx).next));
313                     break;
314                 }
315             }
316         }
317         match next_split {
318             Some((a, b)) => unsafe {
319                 let elt = raw::slice_unchecked(self.string, 0, a);
320                 self.string = raw::slice_unchecked(self.string, b, self.string.len());
321                 Some(elt)
322             },
323             None => self.get_end(),
324         }
325     }
326 }
327
328 impl<'a, Sep: CharEq> DoubleEndedIterator<&'a str>
329 for CharSplits<'a, Sep> {
330     #[inline]
331     fn next_back(&mut self) -> Option<&'a str> {
332         if self.finished { return None }
333
334         if !self.allow_trailing_empty {
335             self.allow_trailing_empty = true;
336             match self.next_back() {
337                 Some(elt) if !elt.is_empty() => return Some(elt),
338                 _ => if self.finished { return None }
339             }
340         }
341         let len = self.string.len();
342         let mut next_split = None;
343
344         if self.only_ascii {
345             for (idx, byte) in self.string.bytes().enumerate().rev() {
346                 if self.sep.matches(byte as char) && byte < 128u8 {
347                     next_split = Some((idx, idx + 1));
348                     break;
349                 }
350             }
351         } else {
352             for (idx, ch) in self.string.char_indices().rev() {
353                 if self.sep.matches(ch) {
354                     next_split = Some((idx, self.string.char_range_at(idx).next));
355                     break;
356                 }
357             }
358         }
359         match next_split {
360             Some((a, b)) => unsafe {
361                 let elt = raw::slice_unchecked(self.string, b, len);
362                 self.string = raw::slice_unchecked(self.string, 0, a);
363                 Some(elt)
364             },
365             None => { self.finished = true; Some(self.string) }
366         }
367     }
368 }
369
370 impl<'a, Sep: CharEq> Iterator<&'a str> for CharSplitsN<'a, Sep> {
371     #[inline]
372     fn next(&mut self) -> Option<&'a str> {
373         if self.count != 0 {
374             self.count -= 1;
375             if self.invert { self.iter.next_back() } else { self.iter.next() }
376         } else {
377             self.iter.get_end()
378         }
379     }
380 }
381
382 /// The internal state of an iterator that searches for matches of a substring
383 /// within a larger string using naive search
384 #[deriving(Clone)]
385 struct NaiveSearcher {
386     position: uint
387 }
388
389 impl NaiveSearcher {
390     fn new() -> NaiveSearcher {
391         NaiveSearcher { position: 0 }
392     }
393
394     fn next(&mut self, haystack: &[u8], needle: &[u8]) -> Option<(uint, uint)> {
395         while self.position + needle.len() <= haystack.len() {
396             if haystack.slice(self.position, self.position + needle.len()) == needle {
397                 let match_pos = self.position;
398                 self.position += needle.len(); // add 1 for all matches
399                 return Some((match_pos, match_pos + needle.len()));
400             } else {
401                 self.position += 1;
402             }
403         }
404         None
405     }
406 }
407
408 /// The internal state of an iterator that searches for matches of a substring
409 /// within a larger string using two-way search
410 #[deriving(Clone)]
411 struct TwoWaySearcher {
412     // constants
413     crit_pos: uint,
414     period: uint,
415     byteset: u64,
416
417     // variables
418     position: uint,
419     memory: uint
420 }
421
422 /*
423     This is the Two-Way search algorithm, which was introduced in the paper:
424     Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
425
426     Here's some background information.
427
428     A *word* is a string of symbols. The *length* of a word should be a familiar
429     notion, and here we denote it for any word x by |x|.
430     (We also allow for the possibility of the *empty word*, a word of length zero).
431
432     If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
433     *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
434     For example, both 1 and 2 are periods for the string "aa". As another example,
435     the only period of the string "abcd" is 4.
436
437     We denote by period(x) the *smallest* period of x (provided that x is non-empty).
438     This is always well-defined since every non-empty word x has at least one period,
439     |x|. We sometimes call this *the period* of x.
440
441     If u, v and x are words such that x = uv, where uv is the concatenation of u and
442     v, then we say that (u, v) is a *factorization* of x.
443
444     Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
445     that both of the following hold
446
447       - either w is a suffix of u or u is a suffix of w
448       - either w is a prefix of v or v is a prefix of w
449
450     then w is said to be a *repetition* for the factorization (u, v).
451
452     Just to unpack this, there are four possibilities here. Let w = "abc". Then we
453     might have:
454
455       - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
456       - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
457       - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
458       - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
459
460     Note that the word vu is a repetition for any factorization (u,v) of x = uv,
461     so every factorization has at least one repetition.
462
463     If x is a string and (u, v) is a factorization for x, then a *local period* for
464     (u, v) is an integer r such that there is some word w such that |w| = r and w is
465     a repetition for (u, v).
466
467     We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
468     call this *the local period* of (u, v). Provided that x = uv is non-empty, this
469     is well-defined (because each non-empty word has at least one factorization, as
470     noted above).
471
472     It can be proven that the following is an equivalent definition of a local period
473     for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
474     all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
475     defined. (i.e. i > 0 and i + r < |x|).
476
477     Using the above reformulation, it is easy to prove that
478
479         1 <= local_period(u, v) <= period(uv)
480
481     A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
482     *critical factorization*.
483
484     The algorithm hinges on the following theorem, which is stated without proof:
485
486     **Critical Factorization Theorem** Any word x has at least one critical
487     factorization (u, v) such that |u| < period(x).
488
489     The purpose of maximal_suffix is to find such a critical factorization.
490
491 */
492 impl TwoWaySearcher {
493     fn new(needle: &[u8]) -> TwoWaySearcher {
494         let (crit_pos1, period1) = TwoWaySearcher::maximal_suffix(needle, false);
495         let (crit_pos2, period2) = TwoWaySearcher::maximal_suffix(needle, true);
496
497         let crit_pos;
498         let period;
499         if crit_pos1 > crit_pos2 {
500             crit_pos = crit_pos1;
501             period = period1;
502         } else {
503             crit_pos = crit_pos2;
504             period = period2;
505         }
506
507         // This isn't in the original algorithm, as far as I'm aware.
508         let byteset = needle.iter()
509                             .fold(0, |a, &b| (1 << ((b & 0x3f) as uint)) | a);
510
511         // A particularly readable explanation of what's going on here can be found
512         // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
513         // see the code for "Algorithm CP" on p. 323.
514         //
515         // What's going on is we have some critical factorization (u, v) of the
516         // needle, and we want to determine whether u is a suffix of
517         // v.slice_to(period). If it is, we use "Algorithm CP1". Otherwise we use
518         // "Algorithm CP2", which is optimized for when the period of the needle
519         // is large.
520         if needle.slice_to(crit_pos) == needle.slice(period, period + crit_pos) {
521             TwoWaySearcher {
522                 crit_pos: crit_pos,
523                 period: period,
524                 byteset: byteset,
525
526                 position: 0,
527                 memory: 0
528             }
529         } else {
530             TwoWaySearcher {
531                 crit_pos: crit_pos,
532                 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
533                 byteset: byteset,
534
535                 position: 0,
536                 memory: uint::MAX // Dummy value to signify that the period is long
537             }
538         }
539     }
540
541     // One of the main ideas of Two-Way is that we factorize the needle into
542     // two halves, (u, v), and begin trying to find v in the haystack by scanning
543     // left to right. If v matches, we try to match u by scanning right to left.
544     // How far we can jump when we encounter a mismatch is all based on the fact
545     // that (u, v) is a critical factorization for the needle.
546     #[inline]
547     fn next(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> Option<(uint, uint)> {
548         'search: loop {
549             // Check that we have room to search in
550             if self.position + needle.len() > haystack.len() {
551                 return None;
552             }
553
554             // Quickly skip by large portions unrelated to our substring
555             if (self.byteset >>
556                     ((haystack[self.position + needle.len() - 1] & 0x3f)
557                      as uint)) & 1 == 0 {
558                 self.position += needle.len();
559                 if !long_period {
560                     self.memory = 0;
561                 }
562                 continue 'search;
563             }
564
565             // See if the right part of the needle matches
566             let start = if long_period { self.crit_pos }
567                         else { cmp::max(self.crit_pos, self.memory) };
568             for i in range(start, needle.len()) {
569                 if needle[i] != haystack[self.position + i] {
570                     self.position += i - self.crit_pos + 1;
571                     if !long_period {
572                         self.memory = 0;
573                     }
574                     continue 'search;
575                 }
576             }
577
578             // See if the left part of the needle matches
579             let start = if long_period { 0 } else { self.memory };
580             for i in range(start, self.crit_pos).rev() {
581                 if needle[i] != haystack[self.position + i] {
582                     self.position += self.period;
583                     if !long_period {
584                         self.memory = needle.len() - self.period;
585                     }
586                     continue 'search;
587                 }
588             }
589
590             // We have found a match!
591             let match_pos = self.position;
592             self.position += needle.len(); // add self.period for all matches
593             if !long_period {
594                 self.memory = 0; // set to needle.len() - self.period for all matches
595             }
596             return Some((match_pos, match_pos + needle.len()));
597         }
598     }
599
600     // Computes a critical factorization (u, v) of `arr`.
601     // Specifically, returns (i, p), where i is the starting index of v in some
602     // critical factorization (u, v) and p = period(v)
603     #[inline]
604     fn maximal_suffix(arr: &[u8], reversed: bool) -> (uint, uint) {
605         let mut left = -1; // Corresponds to i in the paper
606         let mut right = 0; // Corresponds to j in the paper
607         let mut offset = 1; // Corresponds to k in the paper
608         let mut period = 1; // Corresponds to p in the paper
609
610         while right + offset < arr.len() {
611             let a;
612             let b;
613             if reversed {
614                 a = arr[left + offset];
615                 b = arr[right + offset];
616             } else {
617                 a = arr[right + offset];
618                 b = arr[left + offset];
619             }
620             if a < b {
621                 // Suffix is smaller, period is entire prefix so far.
622                 right += offset;
623                 offset = 1;
624                 period = right - left;
625             } else if a == b {
626                 // Advance through repetition of the current period.
627                 if offset == period {
628                     right += offset;
629                     offset = 1;
630                 } else {
631                     offset += 1;
632                 }
633             } else {
634                 // Suffix is larger, start over from current location.
635                 left = right;
636                 right += 1;
637                 offset = 1;
638                 period = 1;
639             }
640         }
641         (left + 1, period)
642     }
643 }
644
645 /// The internal state of an iterator that searches for matches of a substring
646 /// within a larger string using a dynamically chosen search algorithm
647 #[deriving(Clone)]
648 enum Searcher {
649     Naive(NaiveSearcher),
650     TwoWay(TwoWaySearcher),
651     TwoWayLong(TwoWaySearcher)
652 }
653
654 impl Searcher {
655     fn new(haystack: &[u8], needle: &[u8]) -> Searcher {
656         // FIXME: Tune this.
657         // FIXME(#16715): This unsigned integer addition will probably not
658         // overflow because that would mean that the memory almost solely
659         // consists of the needle. Needs #16715 to be formally fixed.
660         if needle.len() + 20 > haystack.len() {
661             Naive(NaiveSearcher::new())
662         } else {
663             let searcher = TwoWaySearcher::new(needle);
664             if searcher.memory == uint::MAX { // If the period is long
665                 TwoWayLong(searcher)
666             } else {
667                 TwoWay(searcher)
668             }
669         }
670     }
671 }
672
673 /// An iterator over the start and end indices of the matches of a
674 /// substring within a larger string
675 #[deriving(Clone)]
676 pub struct MatchIndices<'a> {
677     // constants
678     haystack: &'a str,
679     needle: &'a str,
680     searcher: Searcher
681 }
682
683 /// An iterator over the substrings of a string separated by a given
684 /// search string
685 #[deriving(Clone)]
686 pub struct StrSplits<'a> {
687     it: MatchIndices<'a>,
688     last_end: uint,
689     finished: bool
690 }
691
692 impl<'a> Iterator<(uint, uint)> for MatchIndices<'a> {
693     #[inline]
694     fn next(&mut self) -> Option<(uint, uint)> {
695         match self.searcher {
696             Naive(ref mut searcher)
697                 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes()),
698             TwoWay(ref mut searcher)
699                 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), false),
700             TwoWayLong(ref mut searcher)
701                 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), true)
702         }
703     }
704 }
705
706 impl<'a> Iterator<&'a str> for StrSplits<'a> {
707     #[inline]
708     fn next(&mut self) -> Option<&'a str> {
709         if self.finished { return None; }
710
711         match self.it.next() {
712             Some((from, to)) => {
713                 let ret = Some(self.it.haystack.slice(self.last_end, from));
714                 self.last_end = to;
715                 ret
716             }
717             None => {
718                 self.finished = true;
719                 Some(self.it.haystack.slice(self.last_end, self.it.haystack.len()))
720             }
721         }
722     }
723 }
724
725 /// External iterator for a string's UTF16 codeunits.
726 /// Use with the `std::iter` module.
727 #[deriving(Clone)]
728 pub struct Utf16CodeUnits<'a> {
729     chars: Chars<'a>,
730     extra: u16
731 }
732
733 impl<'a> Iterator<u16> for Utf16CodeUnits<'a> {
734     #[inline]
735     fn next(&mut self) -> Option<u16> {
736         if self.extra != 0 {
737             let tmp = self.extra;
738             self.extra = 0;
739             return Some(tmp);
740         }
741
742         let mut buf = [0u16, ..2];
743         self.chars.next().map(|ch| {
744             let n = ch.encode_utf16(buf.as_mut_slice()).unwrap_or(0);
745             if n == 2 { self.extra = buf[1]; }
746             buf[0]
747         })
748     }
749
750     #[inline]
751     fn size_hint(&self) -> (uint, Option<uint>) {
752         let (low, high) = self.chars.size_hint();
753         // every char gets either one u16 or two u16,
754         // so this iterator is between 1 or 2 times as
755         // long as the underlying iterator.
756         (low, high.and_then(|n| n.checked_mul(&2)))
757     }
758 }
759
760 /*
761 Section: Comparing strings
762 */
763
764 // share the implementation of the lang-item vs. non-lang-item
765 // eq_slice.
766 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
767 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
768 #[inline]
769 fn eq_slice_(a: &str, b: &str) -> bool {
770     #[allow(ctypes)]
771     extern { fn memcmp(s1: *const i8, s2: *const i8, n: uint) -> i32; }
772     a.len() == b.len() && unsafe {
773         memcmp(a.as_ptr() as *const i8,
774                b.as_ptr() as *const i8,
775                a.len()) == 0
776     }
777 }
778
779 /// Bytewise slice equality
780 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
781 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
782 #[lang="str_eq"]
783 #[inline]
784 pub fn eq_slice(a: &str, b: &str) -> bool {
785     eq_slice_(a, b)
786 }
787
788 /*
789 Section: Misc
790 */
791
792 /// Walk through `iter` checking that it's a valid UTF-8 sequence,
793 /// returning `true` in that case, or, if it is invalid, `false` with
794 /// `iter` reset such that it is pointing at the first byte in the
795 /// invalid sequence.
796 #[inline(always)]
797 fn run_utf8_validation_iterator(iter: &mut slice::Items<u8>) -> bool {
798     loop {
799         // save the current thing we're pointing at.
800         let old = *iter;
801
802         // restore the iterator we had at the start of this codepoint.
803         macro_rules! err ( () => { {*iter = old; return false} });
804         macro_rules! next ( () => {
805                 match iter.next() {
806                     Some(a) => *a,
807                     // we needed data, but there was none: error!
808                     None => err!()
809                 }
810             });
811
812         let first = match iter.next() {
813             Some(&b) => b,
814             // we're at the end of the iterator and a codepoint
815             // boundary at the same time, so this string is valid.
816             None => return true
817         };
818
819         // ASCII characters are always valid, so only large
820         // bytes need more examination.
821         if first >= 128 {
822             let w = utf8_char_width(first);
823             let second = next!();
824             // 2-byte encoding is for codepoints  \u0080 to  \u07ff
825             //        first  C2 80        last DF BF
826             // 3-byte encoding is for codepoints  \u0800 to  \uffff
827             //        first  E0 A0 80     last EF BF BF
828             //   excluding surrogates codepoints  \ud800 to  \udfff
829             //               ED A0 80 to       ED BF BF
830             // 4-byte encoding is for codepoints \u10000 to \u10ffff
831             //        first  F0 90 80 80  last F4 8F BF BF
832             //
833             // Use the UTF-8 syntax from the RFC
834             //
835             // https://tools.ietf.org/html/rfc3629
836             // UTF8-1      = %x00-7F
837             // UTF8-2      = %xC2-DF UTF8-tail
838             // UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
839             //               %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
840             // UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
841             //               %xF4 %x80-8F 2( UTF8-tail )
842             match w {
843                 2 => if second & !CONT_MASK != TAG_CONT_U8 {err!()},
844                 3 => {
845                     match (first, second, next!() & !CONT_MASK) {
846                         (0xE0        , 0xA0 .. 0xBF, TAG_CONT_U8) |
847                         (0xE1 .. 0xEC, 0x80 .. 0xBF, TAG_CONT_U8) |
848                         (0xED        , 0x80 .. 0x9F, TAG_CONT_U8) |
849                         (0xEE .. 0xEF, 0x80 .. 0xBF, TAG_CONT_U8) => {}
850                         _ => err!()
851                     }
852                 }
853                 4 => {
854                     match (first, second, next!() & !CONT_MASK, next!() & !CONT_MASK) {
855                         (0xF0        , 0x90 .. 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
856                         (0xF1 .. 0xF3, 0x80 .. 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
857                         (0xF4        , 0x80 .. 0x8F, TAG_CONT_U8, TAG_CONT_U8) => {}
858                         _ => err!()
859                     }
860                 }
861                 _ => err!()
862             }
863         }
864     }
865 }
866
867 /// Determines if a vector of bytes contains valid UTF-8.
868 pub fn is_utf8(v: &[u8]) -> bool {
869     run_utf8_validation_iterator(&mut v.iter())
870 }
871
872 /// Determines if a vector of `u16` contains valid UTF-16
873 pub fn is_utf16(v: &[u16]) -> bool {
874     let mut it = v.iter();
875     macro_rules! next ( ($ret:expr) => {
876             match it.next() { Some(u) => *u, None => return $ret }
877         }
878     )
879     loop {
880         let u = next!(true);
881
882         match char::from_u32(u as u32) {
883             Some(_) => {}
884             None => {
885                 let u2 = next!(false);
886                 if u < 0xD7FF || u > 0xDBFF ||
887                     u2 < 0xDC00 || u2 > 0xDFFF { return false; }
888             }
889         }
890     }
891 }
892
893 /// An iterator that decodes UTF-16 encoded codepoints from a vector
894 /// of `u16`s.
895 #[deriving(Clone)]
896 pub struct Utf16Items<'a> {
897     iter: slice::Items<'a, u16>
898 }
899 /// The possibilities for values decoded from a `u16` stream.
900 #[deriving(PartialEq, Eq, Clone, Show)]
901 pub enum Utf16Item {
902     /// A valid codepoint.
903     ScalarValue(char),
904     /// An invalid surrogate without its pair.
905     LoneSurrogate(u16)
906 }
907
908 impl Utf16Item {
909     /// Convert `self` to a `char`, taking `LoneSurrogate`s to the
910     /// replacement character (U+FFFD).
911     #[inline]
912     pub fn to_char_lossy(&self) -> char {
913         match *self {
914             ScalarValue(c) => c,
915             LoneSurrogate(_) => '\uFFFD'
916         }
917     }
918 }
919
920 impl<'a> Iterator<Utf16Item> for Utf16Items<'a> {
921     fn next(&mut self) -> Option<Utf16Item> {
922         let u = match self.iter.next() {
923             Some(u) => *u,
924             None => return None
925         };
926
927         if u < 0xD800 || 0xDFFF < u {
928             // not a surrogate
929             Some(ScalarValue(unsafe {mem::transmute(u as u32)}))
930         } else if u >= 0xDC00 {
931             // a trailing surrogate
932             Some(LoneSurrogate(u))
933         } else {
934             // preserve state for rewinding.
935             let old = self.iter;
936
937             let u2 = match self.iter.next() {
938                 Some(u2) => *u2,
939                 // eof
940                 None => return Some(LoneSurrogate(u))
941             };
942             if u2 < 0xDC00 || u2 > 0xDFFF {
943                 // not a trailing surrogate so we're not a valid
944                 // surrogate pair, so rewind to redecode u2 next time.
945                 self.iter = old;
946                 return Some(LoneSurrogate(u))
947             }
948
949             // all ok, so lets decode it.
950             let c = ((u - 0xD800) as u32 << 10 | (u2 - 0xDC00) as u32) + 0x1_0000;
951             Some(ScalarValue(unsafe {mem::transmute(c)}))
952         }
953     }
954
955     #[inline]
956     fn size_hint(&self) -> (uint, Option<uint>) {
957         let (low, high) = self.iter.size_hint();
958         // we could be entirely valid surrogates (2 elements per
959         // char), or entirely non-surrogates (1 element per char)
960         (low / 2, high)
961     }
962 }
963
964 /// Create an iterator over the UTF-16 encoded codepoints in `v`,
965 /// returning invalid surrogates as `LoneSurrogate`s.
966 ///
967 /// # Example
968 ///
969 /// ```rust
970 /// use std::str;
971 /// use std::str::{ScalarValue, LoneSurrogate};
972 ///
973 /// // 𝄞mus<invalid>ic<invalid>
974 /// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
975 ///          0x0073, 0xDD1E, 0x0069, 0x0063,
976 ///          0xD834];
977 ///
978 /// assert_eq!(str::utf16_items(v).collect::<Vec<_>>(),
979 ///            vec![ScalarValue('𝄞'),
980 ///                 ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
981 ///                 LoneSurrogate(0xDD1E),
982 ///                 ScalarValue('i'), ScalarValue('c'),
983 ///                 LoneSurrogate(0xD834)]);
984 /// ```
985 pub fn utf16_items<'a>(v: &'a [u16]) -> Utf16Items<'a> {
986     Utf16Items { iter : v.iter() }
987 }
988
989 /// Return a slice of `v` ending at (and not including) the first NUL
990 /// (0).
991 ///
992 /// # Example
993 ///
994 /// ```rust
995 /// use std::str;
996 ///
997 /// // "abcd"
998 /// let mut v = ['a' as u16, 'b' as u16, 'c' as u16, 'd' as u16];
999 /// // no NULs so no change
1000 /// assert_eq!(str::truncate_utf16_at_nul(v), v.as_slice());
1001 ///
1002 /// // "ab\0d"
1003 /// v[2] = 0;
1004 /// let b: &[_] = &['a' as u16, 'b' as u16];
1005 /// assert_eq!(str::truncate_utf16_at_nul(v), b);
1006 /// ```
1007 pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] {
1008     match v.iter().position(|c| *c == 0) {
1009         // don't include the 0
1010         Some(i) => v.slice_to(i),
1011         None => v
1012     }
1013 }
1014
1015 // https://tools.ietf.org/html/rfc3629
1016 static UTF8_CHAR_WIDTH: [u8, ..256] = [
1017 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1018 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1019 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1020 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1021 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1022 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1023 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1024 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1025 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1026 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1027 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1028 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1029 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1030 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1031 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1032 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1033 ];
1034
1035 /// Given a first byte, determine how many bytes are in this UTF-8 character
1036 #[inline]
1037 pub fn utf8_char_width(b: u8) -> uint {
1038     return UTF8_CHAR_WIDTH[b as uint] as uint;
1039 }
1040
1041 /// Struct that contains a `char` and the index of the first byte of
1042 /// the next `char` in a string.  This can be used as a data structure
1043 /// for iterating over the UTF-8 bytes of a string.
1044 pub struct CharRange {
1045     /// Current `char`
1046     pub ch: char,
1047     /// Index of the first byte of the next `char`
1048     pub next: uint,
1049 }
1050
1051 /// Mask of the value bits of a continuation byte
1052 static CONT_MASK: u8 = 0b0011_1111u8;
1053 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte
1054 static TAG_CONT_U8: u8 = 0b1000_0000u8;
1055
1056 /// Unsafe operations
1057 pub mod raw {
1058     use mem;
1059     use collections::Collection;
1060     use ptr::RawPtr;
1061     use raw::Slice;
1062     use slice::{ImmutableSlice};
1063     use str::{is_utf8, StrSlice};
1064
1065     /// Converts a slice of bytes to a string slice without checking
1066     /// that the string contains valid UTF-8.
1067     pub unsafe fn from_utf8<'a>(v: &'a [u8]) -> &'a str {
1068         mem::transmute(v)
1069     }
1070
1071     /// Form a slice from a C string. Unsafe because the caller must ensure the
1072     /// C string has the static lifetime, or else the return value may be
1073     /// invalidated later.
1074     pub unsafe fn c_str_to_static_slice(s: *const i8) -> &'static str {
1075         let s = s as *const u8;
1076         let mut curr = s;
1077         let mut len = 0u;
1078         while *curr != 0u8 {
1079             len += 1u;
1080             curr = s.offset(len as int);
1081         }
1082         let v = Slice { data: s, len: len };
1083         assert!(is_utf8(::mem::transmute(v)));
1084         ::mem::transmute(v)
1085     }
1086
1087     /// Takes a bytewise (not UTF-8) slice from a string.
1088     ///
1089     /// Returns the substring from [`begin`..`end`).
1090     ///
1091     /// # Failure
1092     ///
1093     /// If begin is greater than end.
1094     /// If end is greater than the length of the string.
1095     #[inline]
1096     pub unsafe fn slice_bytes<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
1097         assert!(begin <= end);
1098         assert!(end <= s.len());
1099         slice_unchecked(s, begin, end)
1100     }
1101
1102     /// Takes a bytewise (not UTF-8) slice from a string.
1103     ///
1104     /// Returns the substring from [`begin`..`end`).
1105     ///
1106     /// Caller must check slice boundaries!
1107     #[inline]
1108     pub unsafe fn slice_unchecked<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
1109         mem::transmute(Slice {
1110                 data: s.as_ptr().offset(begin as int),
1111                 len: end - begin,
1112             })
1113     }
1114 }
1115
1116 /*
1117 Section: Trait implementations
1118 */
1119
1120 #[allow(missing_doc)]
1121 pub mod traits {
1122     use cmp::{Ord, Ordering, Less, Equal, Greater, PartialEq, PartialOrd, Equiv, Eq};
1123     use collections::Collection;
1124     use iter::Iterator;
1125     use option::{Option, Some};
1126     use ops;
1127     use str::{Str, StrSlice, eq_slice};
1128
1129     impl<'a> Ord for &'a str {
1130         #[inline]
1131         fn cmp(&self, other: & &'a str) -> Ordering {
1132             for (s_b, o_b) in self.bytes().zip(other.bytes()) {
1133                 match s_b.cmp(&o_b) {
1134                     Greater => return Greater,
1135                     Less => return Less,
1136                     Equal => ()
1137                 }
1138             }
1139
1140             self.len().cmp(&other.len())
1141         }
1142     }
1143
1144     impl<'a> PartialEq for &'a str {
1145         #[inline]
1146         fn eq(&self, other: & &'a str) -> bool {
1147             eq_slice((*self), (*other))
1148         }
1149         #[inline]
1150         fn ne(&self, other: & &'a str) -> bool { !(*self).eq(other) }
1151     }
1152
1153     impl<'a> Eq for &'a str {}
1154
1155     impl<'a> PartialOrd for &'a str {
1156         #[inline]
1157         fn partial_cmp(&self, other: &&'a str) -> Option<Ordering> {
1158             Some(self.cmp(other))
1159         }
1160     }
1161
1162     impl<'a, S: Str> Equiv<S> for &'a str {
1163         #[inline]
1164         fn equiv(&self, other: &S) -> bool { eq_slice(*self, other.as_slice()) }
1165     }
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     }
1188 }
1189
1190 /// Any string that can be represented as a slice
1191 pub trait Str {
1192     /// Work with `self` as a slice.
1193     fn as_slice<'a>(&'a self) -> &'a str;
1194 }
1195
1196 impl<'a> Str for &'a str {
1197     #[inline]
1198     fn as_slice<'a>(&'a self) -> &'a str { *self }
1199 }
1200
1201 impl<'a> Collection for &'a str {
1202     #[inline]
1203     fn len(&self) -> uint {
1204         self.repr().len
1205     }
1206 }
1207
1208 /// Methods for string slices
1209 pub trait StrSlice<'a> {
1210     /// Returns true if one string contains another
1211     ///
1212     /// # Arguments
1213     ///
1214     /// - needle - The string to look for
1215     ///
1216     /// # Example
1217     ///
1218     /// ```rust
1219     /// assert!("bananas".contains("nana"));
1220     /// ```
1221     fn contains<'a>(&self, needle: &'a str) -> bool;
1222
1223     /// Returns true if a string contains a char.
1224     ///
1225     /// # Arguments
1226     ///
1227     /// - needle - The char to look for
1228     ///
1229     /// # Example
1230     ///
1231     /// ```rust
1232     /// assert!("hello".contains_char('e'));
1233     /// ```
1234     fn contains_char(&self, needle: char) -> bool;
1235
1236     /// An iterator over the characters of `self`. Note, this iterates
1237     /// over Unicode code-points, not Unicode graphemes.
1238     ///
1239     /// # Example
1240     ///
1241     /// ```rust
1242     /// let v: Vec<char> = "abc åäö".chars().collect();
1243     /// assert_eq!(v, vec!['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
1244     /// ```
1245     fn chars(&self) -> Chars<'a>;
1246
1247     /// An iterator over the bytes of `self`
1248     ///
1249     /// # Example
1250     ///
1251     /// ```rust
1252     /// let v: Vec<u8> = "bors".bytes().collect();
1253     /// assert_eq!(v, b"bors".to_vec());
1254     /// ```
1255     fn bytes(&self) -> Bytes<'a>;
1256
1257     /// An iterator over the characters of `self` and their byte offsets.
1258     fn char_indices(&self) -> CharOffsets<'a>;
1259
1260     /// An iterator over substrings of `self`, separated by characters
1261     /// matched by `sep`.
1262     ///
1263     /// # Example
1264     ///
1265     /// ```rust
1266     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1267     /// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
1268     ///
1269     /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_digit()).collect();
1270     /// assert_eq!(v, vec!["abc", "def", "ghi"]);
1271     ///
1272     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1273     /// assert_eq!(v, vec!["lion", "", "tiger", "leopard"]);
1274     ///
1275     /// let v: Vec<&str> = "".split('X').collect();
1276     /// assert_eq!(v, vec![""]);
1277     /// ```
1278     fn split<Sep: CharEq>(&self, sep: Sep) -> CharSplits<'a, Sep>;
1279
1280     /// An iterator over substrings of `self`, separated by characters
1281     /// matched by `sep`, restricted to splitting at most `count`
1282     /// times.
1283     ///
1284     /// # Example
1285     ///
1286     /// ```rust
1287     /// let v: Vec<&str> = "Mary had a little lambda".splitn(2, ' ').collect();
1288     /// assert_eq!(v, vec!["Mary", "had", "a little lambda"]);
1289     ///
1290     /// let v: Vec<&str> = "abc1def2ghi".splitn(1, |c: char| c.is_digit()).collect();
1291     /// assert_eq!(v, vec!["abc", "def2ghi"]);
1292     ///
1293     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(2, 'X').collect();
1294     /// assert_eq!(v, vec!["lion", "", "tigerXleopard"]);
1295     ///
1296     /// let v: Vec<&str> = "abcXdef".splitn(0, 'X').collect();
1297     /// assert_eq!(v, vec!["abcXdef"]);
1298     ///
1299     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1300     /// assert_eq!(v, vec![""]);
1301     /// ```
1302     fn splitn<Sep: CharEq>(&self, count: uint, sep: Sep) -> CharSplitsN<'a, Sep>;
1303
1304     /// An iterator over substrings of `self`, separated by characters
1305     /// matched by `sep`.
1306     ///
1307     /// Equivalent to `split`, except that the trailing substring
1308     /// is skipped if empty (terminator semantics).
1309     ///
1310     /// # Example
1311     ///
1312     /// ```rust
1313     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1314     /// assert_eq!(v, vec!["A", "B"]);
1315     ///
1316     /// let v: Vec<&str> = "A..B..".split_terminator('.').collect();
1317     /// assert_eq!(v, vec!["A", "", "B", ""]);
1318     ///
1319     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').rev().collect();
1320     /// assert_eq!(v, vec!["lamb", "little", "a", "had", "Mary"]);
1321     ///
1322     /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_digit()).rev().collect();
1323     /// assert_eq!(v, vec!["ghi", "def", "abc"]);
1324     ///
1325     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').rev().collect();
1326     /// assert_eq!(v, vec!["leopard", "tiger", "", "lion"]);
1327     /// ```
1328     fn split_terminator<Sep: CharEq>(&self, sep: Sep) -> CharSplits<'a, Sep>;
1329
1330     /// An iterator over substrings of `self`, separated by characters
1331     /// matched by `sep`, starting from the end of the string.
1332     /// Restricted to splitting at most `count` times.
1333     ///
1334     /// # Example
1335     ///
1336     /// ```rust
1337     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(2, ' ').collect();
1338     /// assert_eq!(v, vec!["lamb", "little", "Mary had a"]);
1339     ///
1340     /// let v: Vec<&str> = "abc1def2ghi".rsplitn(1, |c: char| c.is_digit()).collect();
1341     /// assert_eq!(v, vec!["ghi", "abc1def"]);
1342     ///
1343     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(2, 'X').collect();
1344     /// assert_eq!(v, vec!["leopard", "tiger", "lionX"]);
1345     /// ```
1346     fn rsplitn<Sep: CharEq>(&self, count: uint, sep: Sep) -> CharSplitsN<'a, Sep>;
1347
1348     /// An iterator over the start and end indices of the disjoint
1349     /// matches of `sep` within `self`.
1350     ///
1351     /// That is, each returned value `(start, end)` satisfies
1352     /// `self.slice(start, end) == sep`. For matches of `sep` within
1353     /// `self` that overlap, only the indices corresponding to the
1354     /// first match are returned.
1355     ///
1356     /// # Example
1357     ///
1358     /// ```rust
1359     /// let v: Vec<(uint, uint)> = "abcXXXabcYYYabc".match_indices("abc").collect();
1360     /// assert_eq!(v, vec![(0,3), (6,9), (12,15)]);
1361     ///
1362     /// let v: Vec<(uint, uint)> = "1abcabc2".match_indices("abc").collect();
1363     /// assert_eq!(v, vec![(1,4), (4,7)]);
1364     ///
1365     /// let v: Vec<(uint, uint)> = "ababa".match_indices("aba").collect();
1366     /// assert_eq!(v, vec![(0, 3)]); // only the first `aba`
1367     /// ```
1368     fn match_indices(&self, sep: &'a str) -> MatchIndices<'a>;
1369
1370     /// An iterator over the substrings of `self` separated by `sep`.
1371     ///
1372     /// # Example
1373     ///
1374     /// ```rust
1375     /// let v: Vec<&str> = "abcXXXabcYYYabc".split_str("abc").collect();
1376     /// assert_eq!(v, vec!["", "XXX", "YYY", ""]);
1377     ///
1378     /// let v: Vec<&str> = "1abcabc2".split_str("abc").collect();
1379     /// assert_eq!(v, vec!["1", "", "2"]);
1380     /// ```
1381     fn split_str(&self, &'a str) -> StrSplits<'a>;
1382
1383     /// An iterator over the lines of a string (subsequences separated
1384     /// by `\n`). This does not include the empty string after a
1385     /// trailing `\n`.
1386     ///
1387     /// # Example
1388     ///
1389     /// ```rust
1390     /// let four_lines = "foo\nbar\n\nbaz\n";
1391     /// let v: Vec<&str> = four_lines.lines().collect();
1392     /// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
1393     /// ```
1394     fn lines(&self) -> CharSplits<'a, char>;
1395
1396     /// An iterator over the lines of a string, separated by either
1397     /// `\n` or `\r\n`. As with `.lines()`, this does not include an
1398     /// empty trailing line.
1399     ///
1400     /// # Example
1401     ///
1402     /// ```rust
1403     /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
1404     /// let v: Vec<&str> = four_lines.lines_any().collect();
1405     /// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
1406     /// ```
1407     fn lines_any(&self) -> AnyLines<'a>;
1408
1409     /// Returns the number of Unicode code points (`char`) that a
1410     /// string holds.
1411     ///
1412     /// This does not perform any normalization, and is `O(n)`, since
1413     /// UTF-8 is a variable width encoding of code points.
1414     ///
1415     /// *Warning*: The number of code points in a string does not directly
1416     /// correspond to the number of visible characters or width of the
1417     /// visible text due to composing characters, and double- and
1418     /// zero-width ones.
1419     ///
1420     /// See also `.len()` for the byte length.
1421     ///
1422     /// # Example
1423     ///
1424     /// ```rust
1425     /// // composed forms of `ö` and `é`
1426     /// let c = "Löwe 老虎 Léopard"; // German, Simplified Chinese, French
1427     /// // decomposed forms of `ö` and `é`
1428     /// let d = "Lo\u0308we 老虎 Le\u0301opard";
1429     ///
1430     /// assert_eq!(c.char_len(), 15);
1431     /// assert_eq!(d.char_len(), 17);
1432     ///
1433     /// assert_eq!(c.len(), 21);
1434     /// assert_eq!(d.len(), 23);
1435     ///
1436     /// // the two strings *look* the same
1437     /// println!("{}", c);
1438     /// println!("{}", d);
1439     /// ```
1440     fn char_len(&self) -> uint;
1441
1442     /// Returns a slice of the given string from the byte range
1443     /// [`begin`..`end`).
1444     ///
1445     /// This operation is `O(1)`.
1446     ///
1447     /// Fails when `begin` and `end` do not point to valid characters
1448     /// or point beyond the last character of the string.
1449     ///
1450     /// See also `slice_to` and `slice_from` for slicing prefixes and
1451     /// suffixes of strings, and `slice_chars` for slicing based on
1452     /// code point counts.
1453     ///
1454     /// # Example
1455     ///
1456     /// ```rust
1457     /// let s = "Löwe 老虎 Léopard";
1458     /// assert_eq!(s.slice(0, 1), "L");
1459     ///
1460     /// assert_eq!(s.slice(1, 9), "öwe 老");
1461     ///
1462     /// // these will fail:
1463     /// // byte 2 lies within `ö`:
1464     /// // s.slice(2, 3);
1465     ///
1466     /// // byte 8 lies within `老`
1467     /// // s.slice(1, 8);
1468     ///
1469     /// // byte 100 is outside the string
1470     /// // s.slice(3, 100);
1471     /// ```
1472     fn slice(&self, begin: uint, end: uint) -> &'a str;
1473
1474     /// Returns a slice of the string from `begin` to its end.
1475     ///
1476     /// Equivalent to `self.slice(begin, self.len())`.
1477     ///
1478     /// Fails when `begin` does not point to a valid character, or is
1479     /// out of bounds.
1480     ///
1481     /// See also `slice`, `slice_to` and `slice_chars`.
1482     fn slice_from(&self, begin: uint) -> &'a str;
1483
1484     /// Returns a slice of the string from the beginning to byte
1485     /// `end`.
1486     ///
1487     /// Equivalent to `self.slice(0, end)`.
1488     ///
1489     /// Fails when `end` does not point to a valid character, or is
1490     /// out of bounds.
1491     ///
1492     /// See also `slice`, `slice_from` and `slice_chars`.
1493     fn slice_to(&self, end: uint) -> &'a str;
1494
1495     /// Returns a slice of the string from the character range
1496     /// [`begin`..`end`).
1497     ///
1498     /// That is, start at the `begin`-th code point of the string and
1499     /// continue to the `end`-th code point. This does not detect or
1500     /// handle edge cases such as leaving a combining character as the
1501     /// first code point of the string.
1502     ///
1503     /// Due to the design of UTF-8, this operation is `O(end)`.
1504     /// See `slice`, `slice_to` and `slice_from` for `O(1)`
1505     /// variants that use byte indices rather than code point
1506     /// indices.
1507     ///
1508     /// Fails if `begin` > `end` or the either `begin` or `end` are
1509     /// beyond the last character of the string.
1510     ///
1511     /// # Example
1512     ///
1513     /// ```rust
1514     /// let s = "Löwe 老虎 Léopard";
1515     /// assert_eq!(s.slice_chars(0, 4), "Löwe");
1516     /// assert_eq!(s.slice_chars(5, 7), "老虎");
1517     /// ```
1518     fn slice_chars(&self, begin: uint, end: uint) -> &'a str;
1519
1520     /// Returns true if `needle` is a prefix of the string.
1521     ///
1522     /// # Example
1523     ///
1524     /// ```rust
1525     /// assert!("banana".starts_with("ba"));
1526     /// ```
1527     fn starts_with(&self, needle: &str) -> bool;
1528
1529     /// Returns true if `needle` is a suffix of the string.
1530     ///
1531     /// # Example
1532     ///
1533     /// ```rust
1534     /// assert!("banana".ends_with("nana"));
1535     /// ```
1536     fn ends_with(&self, needle: &str) -> bool;
1537
1538     /// Returns a string with characters that match `to_trim` removed.
1539     ///
1540     /// # Arguments
1541     ///
1542     /// * to_trim - a character matcher
1543     ///
1544     /// # Example
1545     ///
1546     /// ```rust
1547     /// assert_eq!("11foo1bar11".trim_chars('1'), "foo1bar")
1548     /// let x: &[_] = &['1', '2'];
1549     /// assert_eq!("12foo1bar12".trim_chars(x), "foo1bar")
1550     /// assert_eq!("123foo1bar123".trim_chars(|c: char| c.is_digit()), "foo1bar")
1551     /// ```
1552     fn trim_chars<C: CharEq>(&self, to_trim: C) -> &'a str;
1553
1554     /// Returns a string with leading `chars_to_trim` removed.
1555     ///
1556     /// # Arguments
1557     ///
1558     /// * to_trim - a character matcher
1559     ///
1560     /// # Example
1561     ///
1562     /// ```rust
1563     /// assert_eq!("11foo1bar11".trim_left_chars('1'), "foo1bar11")
1564     /// let x: &[_] = &['1', '2'];
1565     /// assert_eq!("12foo1bar12".trim_left_chars(x), "foo1bar12")
1566     /// assert_eq!("123foo1bar123".trim_left_chars(|c: char| c.is_digit()), "foo1bar123")
1567     /// ```
1568     fn trim_left_chars<C: CharEq>(&self, to_trim: C) -> &'a str;
1569
1570     /// Returns a string with trailing `chars_to_trim` removed.
1571     ///
1572     /// # Arguments
1573     ///
1574     /// * to_trim - a character matcher
1575     ///
1576     /// # Example
1577     ///
1578     /// ```rust
1579     /// assert_eq!("11foo1bar11".trim_right_chars('1'), "11foo1bar")
1580     /// let x: &[_] = &['1', '2'];
1581     /// assert_eq!("12foo1bar12".trim_right_chars(x), "12foo1bar")
1582     /// assert_eq!("123foo1bar123".trim_right_chars(|c: char| c.is_digit()), "123foo1bar")
1583     /// ```
1584     fn trim_right_chars<C: CharEq>(&self, to_trim: C) -> &'a str;
1585
1586     /// Check that `index`-th byte lies at the start and/or end of a
1587     /// UTF-8 code point sequence.
1588     ///
1589     /// The start and end of the string (when `index == self.len()`)
1590     /// are considered to be boundaries.
1591     ///
1592     /// Fails if `index` is greater than `self.len()`.
1593     ///
1594     /// # Example
1595     ///
1596     /// ```rust
1597     /// let s = "Löwe 老虎 Léopard";
1598     /// assert!(s.is_char_boundary(0));
1599     /// // start of `老`
1600     /// assert!(s.is_char_boundary(6));
1601     /// assert!(s.is_char_boundary(s.len()));
1602     ///
1603     /// // second byte of `ö`
1604     /// assert!(!s.is_char_boundary(2));
1605     ///
1606     /// // third byte of `老`
1607     /// assert!(!s.is_char_boundary(8));
1608     /// ```
1609     fn is_char_boundary(&self, index: uint) -> bool;
1610
1611     /// Pluck a character out of a string and return the index of the next
1612     /// character.
1613     ///
1614     /// This function can be used to iterate over the Unicode characters of a
1615     /// string.
1616     ///
1617     /// # Example
1618     ///
1619     /// This example manually iterates through the characters of a
1620     /// string; this should normally be done by `.chars()` or
1621     /// `.char_indices`.
1622     ///
1623     /// ```rust
1624     /// use std::str::CharRange;
1625     ///
1626     /// let s = "中华Việt Nam";
1627     /// let mut i = 0u;
1628     /// while i < s.len() {
1629     ///     let CharRange {ch, next} = s.char_range_at(i);
1630     ///     println!("{}: {}", i, ch);
1631     ///     i = next;
1632     /// }
1633     /// ```
1634     ///
1635     /// ## Output
1636     ///
1637     /// ```ignore
1638     /// 0: 中
1639     /// 3: 华
1640     /// 6: V
1641     /// 7: i
1642     /// 8: ệ
1643     /// 11: t
1644     /// 12:
1645     /// 13: N
1646     /// 14: a
1647     /// 15: m
1648     /// ```
1649     ///
1650     /// # Arguments
1651     ///
1652     /// * s - The string
1653     /// * i - The byte offset of the char to extract
1654     ///
1655     /// # Return value
1656     ///
1657     /// A record {ch: char, next: uint} containing the char value and the byte
1658     /// index of the next Unicode character.
1659     ///
1660     /// # Failure
1661     ///
1662     /// If `i` is greater than or equal to the length of the string.
1663     /// If `i` is not the index of the beginning of a valid UTF-8 character.
1664     fn char_range_at(&self, start: uint) -> CharRange;
1665
1666     /// Given a byte position and a str, return the previous char and its position.
1667     ///
1668     /// This function can be used to iterate over a Unicode string in reverse.
1669     ///
1670     /// Returns 0 for next index if called on start index 0.
1671     ///
1672     /// # Failure
1673     ///
1674     /// If `i` is greater than the length of the string.
1675     /// If `i` is not an index following a valid UTF-8 character.
1676     fn char_range_at_reverse(&self, start: uint) -> CharRange;
1677
1678     /// Plucks the character starting at the `i`th byte of a string.
1679     ///
1680     /// # Example
1681     ///
1682     /// ```rust
1683     /// let s = "abπc";
1684     /// assert_eq!(s.char_at(1), 'b');
1685     /// assert_eq!(s.char_at(2), 'π');
1686     /// assert_eq!(s.char_at(4), 'c');
1687     /// ```
1688     ///
1689     /// # Failure
1690     ///
1691     /// If `i` is greater than or equal to the length of the string.
1692     /// If `i` is not the index of the beginning of a valid UTF-8 character.
1693     fn char_at(&self, i: uint) -> char;
1694
1695     /// Plucks the character ending at the `i`th byte of a string.
1696     ///
1697     /// # Failure
1698     ///
1699     /// If `i` is greater than the length of the string.
1700     /// If `i` is not an index following a valid UTF-8 character.
1701     fn char_at_reverse(&self, i: uint) -> char;
1702
1703     /// Work with the byte buffer of a string as a byte slice.
1704     ///
1705     /// # Example
1706     ///
1707     /// ```rust
1708     /// assert_eq!("bors".as_bytes(), b"bors");
1709     /// ```
1710     fn as_bytes(&self) -> &'a [u8];
1711
1712     /// Returns the byte index of the first character of `self` that
1713     /// matches `search`.
1714     ///
1715     /// # Return value
1716     ///
1717     /// `Some` containing the byte index of the last matching character
1718     /// or `None` if there is no match
1719     ///
1720     /// # Example
1721     ///
1722     /// ```rust
1723     /// let s = "Löwe 老虎 Léopard";
1724     ///
1725     /// assert_eq!(s.find('L'), Some(0));
1726     /// assert_eq!(s.find('é'), Some(14));
1727     ///
1728     /// // the first space
1729     /// assert_eq!(s.find(|c: char| c.is_whitespace()), Some(5));
1730     ///
1731     /// // neither are found
1732     /// let x: &[_] = &['1', '2'];
1733     /// assert_eq!(s.find(x), None);
1734     /// ```
1735     fn find<C: CharEq>(&self, search: C) -> Option<uint>;
1736
1737     /// Returns the byte index of the last character of `self` that
1738     /// matches `search`.
1739     ///
1740     /// # Return value
1741     ///
1742     /// `Some` containing the byte index of the last matching character
1743     /// or `None` if there is no match.
1744     ///
1745     /// # Example
1746     ///
1747     /// ```rust
1748     /// let s = "Löwe 老虎 Léopard";
1749     ///
1750     /// assert_eq!(s.rfind('L'), Some(13));
1751     /// assert_eq!(s.rfind('é'), Some(14));
1752     ///
1753     /// // the second space
1754     /// assert_eq!(s.rfind(|c: char| c.is_whitespace()), Some(12));
1755     ///
1756     /// // searches for an occurrence of either `1` or `2`, but neither are found
1757     /// let x: &[_] = &['1', '2'];
1758     /// assert_eq!(s.rfind(x), None);
1759     /// ```
1760     fn rfind<C: CharEq>(&self, search: C) -> Option<uint>;
1761
1762     /// Returns the byte index of the first matching substring
1763     ///
1764     /// # Arguments
1765     ///
1766     /// * `needle` - The string to search for
1767     ///
1768     /// # Return value
1769     ///
1770     /// `Some` containing the byte index of the first matching substring
1771     /// or `None` if there is no match.
1772     ///
1773     /// # Example
1774     ///
1775     /// ```rust
1776     /// let s = "Löwe 老虎 Léopard";
1777     ///
1778     /// assert_eq!(s.find_str("老虎 L"), Some(6));
1779     /// assert_eq!(s.find_str("muffin man"), None);
1780     /// ```
1781     fn find_str(&self, &str) -> Option<uint>;
1782
1783     /// Retrieves the first character from a string slice and returns
1784     /// it. This does not allocate a new string; instead, it returns a
1785     /// slice that point one character beyond the character that was
1786     /// shifted. If the string does not contain any characters,
1787     /// a tuple of None and an empty string is returned instead.
1788     ///
1789     /// # Example
1790     ///
1791     /// ```rust
1792     /// let s = "Löwe 老虎 Léopard";
1793     /// let (c, s1) = s.slice_shift_char();
1794     /// assert_eq!(c, Some('L'));
1795     /// assert_eq!(s1, "öwe 老虎 Léopard");
1796     ///
1797     /// let (c, s2) = s1.slice_shift_char();
1798     /// assert_eq!(c, Some('ö'));
1799     /// assert_eq!(s2, "we 老虎 Léopard");
1800     /// ```
1801     fn slice_shift_char(&self) -> (Option<char>, &'a str);
1802
1803     /// Returns the byte offset of an inner slice relative to an enclosing outer slice.
1804     ///
1805     /// Fails if `inner` is not a direct slice contained within self.
1806     ///
1807     /// # Example
1808     ///
1809     /// ```rust
1810     /// let string = "a\nb\nc";
1811     /// let lines: Vec<&str> = string.lines().collect();
1812     /// let lines = lines.as_slice();
1813     ///
1814     /// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
1815     /// assert!(string.subslice_offset(lines[1]) == 2); // &"b"
1816     /// assert!(string.subslice_offset(lines[2]) == 4); // &"c"
1817     /// ```
1818     fn subslice_offset(&self, inner: &str) -> uint;
1819
1820     /// Return an unsafe pointer to the strings buffer.
1821     ///
1822     /// The caller must ensure that the string outlives this pointer,
1823     /// and that it is not reallocated (e.g. by pushing to the
1824     /// string).
1825     fn as_ptr(&self) -> *const u8;
1826
1827     /// Return an iterator of `u16` over the string encoded as UTF-16.
1828     fn utf16_units(&self) -> Utf16CodeUnits<'a>;
1829 }
1830
1831 #[inline(never)]
1832 fn slice_error_fail(s: &str, begin: uint, end: uint) -> ! {
1833     assert!(begin <= end);
1834     fail!("index {} and/or {} in `{}` do not lie on character boundary",
1835           begin, end, s);
1836 }
1837
1838 impl<'a> StrSlice<'a> for &'a str {
1839     #[inline]
1840     fn contains<'a>(&self, needle: &'a str) -> bool {
1841         self.find_str(needle).is_some()
1842     }
1843
1844     #[inline]
1845     fn contains_char(&self, needle: char) -> bool {
1846         self.find(needle).is_some()
1847     }
1848
1849     #[inline]
1850     fn chars(&self) -> Chars<'a> {
1851         Chars{iter: self.as_bytes().iter()}
1852     }
1853
1854     #[inline]
1855     fn bytes(&self) -> Bytes<'a> {
1856         self.as_bytes().iter().map(|&b| b)
1857     }
1858
1859     #[inline]
1860     fn char_indices(&self) -> CharOffsets<'a> {
1861         CharOffsets{front_offset: 0, iter: self.chars()}
1862     }
1863
1864     #[inline]
1865     fn split<Sep: CharEq>(&self, sep: Sep) -> CharSplits<'a, Sep> {
1866         CharSplits {
1867             string: *self,
1868             only_ascii: sep.only_ascii(),
1869             sep: sep,
1870             allow_trailing_empty: true,
1871             finished: false,
1872         }
1873     }
1874
1875     #[inline]
1876     fn splitn<Sep: CharEq>(&self, count: uint, sep: Sep)
1877         -> CharSplitsN<'a, Sep> {
1878         CharSplitsN {
1879             iter: self.split(sep),
1880             count: count,
1881             invert: false,
1882         }
1883     }
1884
1885     #[inline]
1886     fn split_terminator<Sep: CharEq>(&self, sep: Sep)
1887         -> CharSplits<'a, Sep> {
1888         CharSplits {
1889             allow_trailing_empty: false,
1890             ..self.split(sep)
1891         }
1892     }
1893
1894     #[inline]
1895     fn rsplitn<Sep: CharEq>(&self, count: uint, sep: Sep)
1896         -> CharSplitsN<'a, Sep> {
1897         CharSplitsN {
1898             iter: self.split(sep),
1899             count: count,
1900             invert: true,
1901         }
1902     }
1903
1904     #[inline]
1905     fn match_indices(&self, sep: &'a str) -> MatchIndices<'a> {
1906         assert!(!sep.is_empty())
1907         MatchIndices {
1908             haystack: *self,
1909             needle: sep,
1910             searcher: Searcher::new(self.as_bytes(), sep.as_bytes())
1911         }
1912     }
1913
1914     #[inline]
1915     fn split_str(&self, sep: &'a str) -> StrSplits<'a> {
1916         StrSplits {
1917             it: self.match_indices(sep),
1918             last_end: 0,
1919             finished: false
1920         }
1921     }
1922
1923     #[inline]
1924     fn lines(&self) -> CharSplits<'a, char> {
1925         self.split_terminator('\n')
1926     }
1927
1928     fn lines_any(&self) -> AnyLines<'a> {
1929         self.lines().map(|line| {
1930             let l = line.len();
1931             if l > 0 && line.as_bytes()[l - 1] == b'\r' { line.slice(0, l - 1) }
1932             else { line }
1933         })
1934     }
1935
1936     #[inline]
1937     fn char_len(&self) -> uint { self.chars().count() }
1938
1939     #[inline]
1940     fn slice(&self, begin: uint, end: uint) -> &'a str {
1941         // is_char_boundary checks that the index is in [0, .len()]
1942         if begin <= end &&
1943            self.is_char_boundary(begin) &&
1944            self.is_char_boundary(end) {
1945             unsafe { raw::slice_unchecked(*self, begin, end) }
1946         } else {
1947             slice_error_fail(*self, begin, end)
1948         }
1949     }
1950
1951     #[inline]
1952     fn slice_from(&self, begin: uint) -> &'a str {
1953         // is_char_boundary checks that the index is in [0, .len()]
1954         if self.is_char_boundary(begin) {
1955             unsafe { raw::slice_unchecked(*self, begin, self.len()) }
1956         } else {
1957             slice_error_fail(*self, begin, self.len())
1958         }
1959     }
1960
1961     #[inline]
1962     fn slice_to(&self, end: uint) -> &'a str {
1963         // is_char_boundary checks that the index is in [0, .len()]
1964         if self.is_char_boundary(end) {
1965             unsafe { raw::slice_unchecked(*self, 0, end) }
1966         } else {
1967             slice_error_fail(*self, 0, end)
1968         }
1969     }
1970
1971     fn slice_chars(&self, begin: uint, end: uint) -> &'a str {
1972         assert!(begin <= end);
1973         let mut count = 0;
1974         let mut begin_byte = None;
1975         let mut end_byte = None;
1976
1977         // This could be even more efficient by not decoding,
1978         // only finding the char boundaries
1979         for (idx, _) in self.char_indices() {
1980             if count == begin { begin_byte = Some(idx); }
1981             if count == end { end_byte = Some(idx); break; }
1982             count += 1;
1983         }
1984         if begin_byte.is_none() && count == begin { begin_byte = Some(self.len()) }
1985         if end_byte.is_none() && count == end { end_byte = Some(self.len()) }
1986
1987         match (begin_byte, end_byte) {
1988             (None, _) => fail!("slice_chars: `begin` is beyond end of string"),
1989             (_, None) => fail!("slice_chars: `end` is beyond end of string"),
1990             (Some(a), Some(b)) => unsafe { raw::slice_bytes(*self, a, b) }
1991         }
1992     }
1993
1994     #[inline]
1995     fn starts_with<'a>(&self, needle: &'a str) -> bool {
1996         let n = needle.len();
1997         self.len() >= n && needle.as_bytes() == self.as_bytes().slice_to(n)
1998     }
1999
2000     #[inline]
2001     fn ends_with(&self, needle: &str) -> bool {
2002         let (m, n) = (self.len(), needle.len());
2003         m >= n && needle.as_bytes() == self.as_bytes().slice_from(m - n)
2004     }
2005
2006     #[inline]
2007     fn trim_chars<C: CharEq>(&self, mut to_trim: C) -> &'a str {
2008         let cur = match self.find(|c: char| !to_trim.matches(c)) {
2009             None => "",
2010             Some(i) => unsafe { raw::slice_bytes(*self, i, self.len()) }
2011         };
2012         match cur.rfind(|c: char| !to_trim.matches(c)) {
2013             None => "",
2014             Some(i) => {
2015                 let right = cur.char_range_at(i).next;
2016                 unsafe { raw::slice_bytes(cur, 0, right) }
2017             }
2018         }
2019     }
2020
2021     #[inline]
2022     fn trim_left_chars<C: CharEq>(&self, mut to_trim: C) -> &'a str {
2023         match self.find(|c: char| !to_trim.matches(c)) {
2024             None => "",
2025             Some(first) => unsafe { raw::slice_bytes(*self, first, self.len()) }
2026         }
2027     }
2028
2029     #[inline]
2030     fn trim_right_chars<C: CharEq>(&self, mut to_trim: C) -> &'a str {
2031         match self.rfind(|c: char| !to_trim.matches(c)) {
2032             None => "",
2033             Some(last) => {
2034                 let next = self.char_range_at(last).next;
2035                 unsafe { raw::slice_bytes(*self, 0u, next) }
2036             }
2037         }
2038     }
2039
2040     #[inline]
2041     fn is_char_boundary(&self, index: uint) -> bool {
2042         if index == self.len() { return true; }
2043         match self.as_bytes().get(index) {
2044             None => false,
2045             Some(&b) => b < 128u8 || b >= 192u8,
2046         }
2047     }
2048
2049     #[inline]
2050     fn char_range_at(&self, i: uint) -> CharRange {
2051         if self.as_bytes()[i] < 128u8 {
2052             return CharRange {ch: self.as_bytes()[i] as char, next: i + 1 };
2053         }
2054
2055         // Multibyte case is a fn to allow char_range_at to inline cleanly
2056         fn multibyte_char_range_at(s: &str, i: uint) -> CharRange {
2057             let mut val = s.as_bytes()[i] as u32;
2058             let w = UTF8_CHAR_WIDTH[val as uint] as uint;
2059             assert!((w != 0));
2060
2061             val = utf8_first_byte!(val, w);
2062             val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 1]);
2063             if w > 2 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 2]); }
2064             if w > 3 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 3]); }
2065
2066             return CharRange {ch: unsafe { mem::transmute(val) }, next: i + w};
2067         }
2068
2069         return multibyte_char_range_at(*self, i);
2070     }
2071
2072     #[inline]
2073     fn char_range_at_reverse(&self, start: uint) -> CharRange {
2074         let mut prev = start;
2075
2076         prev = prev.saturating_sub(1);
2077         if self.as_bytes()[prev] < 128 {
2078             return CharRange{ch: self.as_bytes()[prev] as char, next: prev}
2079         }
2080
2081         // Multibyte case is a fn to allow char_range_at_reverse to inline cleanly
2082         fn multibyte_char_range_at_reverse(s: &str, mut i: uint) -> CharRange {
2083             // while there is a previous byte == 10......
2084             while i > 0 && s.as_bytes()[i] & !CONT_MASK == TAG_CONT_U8 {
2085                 i -= 1u;
2086             }
2087
2088             let mut val = s.as_bytes()[i] as u32;
2089             let w = UTF8_CHAR_WIDTH[val as uint] as uint;
2090             assert!((w != 0));
2091
2092             val = utf8_first_byte!(val, w);
2093             val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 1]);
2094             if w > 2 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 2]); }
2095             if w > 3 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 3]); }
2096
2097             return CharRange {ch: unsafe { mem::transmute(val) }, next: i};
2098         }
2099
2100         return multibyte_char_range_at_reverse(*self, prev);
2101     }
2102
2103     #[inline]
2104     fn char_at(&self, i: uint) -> char {
2105         self.char_range_at(i).ch
2106     }
2107
2108     #[inline]
2109     fn char_at_reverse(&self, i: uint) -> char {
2110         self.char_range_at_reverse(i).ch
2111     }
2112
2113     #[inline]
2114     fn as_bytes(&self) -> &'a [u8] {
2115         unsafe { mem::transmute(*self) }
2116     }
2117
2118     fn find<C: CharEq>(&self, mut search: C) -> Option<uint> {
2119         if search.only_ascii() {
2120             self.bytes().position(|b| search.matches(b as char))
2121         } else {
2122             for (index, c) in self.char_indices() {
2123                 if search.matches(c) { return Some(index); }
2124             }
2125             None
2126         }
2127     }
2128
2129     fn rfind<C: CharEq>(&self, mut search: C) -> Option<uint> {
2130         if search.only_ascii() {
2131             self.bytes().rposition(|b| search.matches(b as char))
2132         } else {
2133             for (index, c) in self.char_indices().rev() {
2134                 if search.matches(c) { return Some(index); }
2135             }
2136             None
2137         }
2138     }
2139
2140     fn find_str(&self, needle: &str) -> Option<uint> {
2141         if needle.is_empty() {
2142             Some(0)
2143         } else {
2144             self.match_indices(needle)
2145                 .next()
2146                 .map(|(start, _end)| start)
2147         }
2148     }
2149
2150     #[inline]
2151     fn slice_shift_char(&self) -> (Option<char>, &'a str) {
2152         if self.is_empty() {
2153             return (None, *self);
2154         } else {
2155             let CharRange {ch, next} = self.char_range_at(0u);
2156             let next_s = unsafe { raw::slice_bytes(*self, next, self.len()) };
2157             return (Some(ch), next_s);
2158         }
2159     }
2160
2161     fn subslice_offset(&self, inner: &str) -> uint {
2162         let a_start = self.as_ptr() as uint;
2163         let a_end = a_start + self.len();
2164         let b_start = inner.as_ptr() as uint;
2165         let b_end = b_start + inner.len();
2166
2167         assert!(a_start <= b_start);
2168         assert!(b_end <= a_end);
2169         b_start - a_start
2170     }
2171
2172     #[inline]
2173     fn as_ptr(&self) -> *const u8 {
2174         self.repr().data
2175     }
2176
2177     #[inline]
2178     fn utf16_units(&self) -> Utf16CodeUnits<'a> {
2179         Utf16CodeUnits{ chars: self.chars(), extra: 0}
2180     }
2181 }
2182
2183 impl<'a> Default for &'a str {
2184     fn default() -> &'a str { "" }
2185 }