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