]> git.lizzy.rs Git - rust.git/blob - src/libcore/str/mod.rs
d9cf6dc086d9972099544924198cdf313333f096
[rust.git] / src / libcore / str / mod.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 self::Searcher::{Naive, TwoWay, TwoWayLong};
20
21 use cmp::{self, Eq};
22 use default::Default;
23 use iter::range;
24 use iter::ExactSizeIterator;
25 use iter::{Map, Iterator, IteratorExt, DoubleEndedIterator};
26 use marker::Sized;
27 use mem;
28 use num::Int;
29 use ops::{Fn, FnMut};
30 use option::Option::{self, None, Some};
31 use ptr::PtrExt;
32 use raw::{Repr, Slice};
33 use result::Result::{self, Ok, Err};
34 use slice::{self, SliceExt};
35 use uint;
36
37 macro_rules! delegate_iter {
38     (exact $te:ty : $ti:ty) => {
39         delegate_iter!{$te : $ti}
40         impl<'a> ExactSizeIterator for $ti {
41             #[inline]
42             fn len(&self) -> uint {
43                 self.0.len()
44             }
45         }
46     };
47     ($te:ty : $ti:ty) => {
48         #[stable]
49         impl<'a> Iterator for $ti {
50             type Item = $te;
51
52             #[inline]
53             fn next(&mut self) -> Option<$te> {
54                 self.0.next()
55             }
56             #[inline]
57             fn size_hint(&self) -> (uint, Option<uint>) {
58                 self.0.size_hint()
59             }
60         }
61         #[stable]
62         impl<'a> DoubleEndedIterator for $ti {
63             #[inline]
64             fn next_back(&mut self) -> Option<$te> {
65                 self.0.next_back()
66             }
67         }
68     };
69     (pattern $te:ty : $ti:ty) => {
70         #[stable]
71         impl<'a, P: CharEq> Iterator for $ti {
72             type Item = $te;
73
74             #[inline]
75             fn next(&mut self) -> Option<$te> {
76                 self.0.next()
77             }
78             #[inline]
79             fn size_hint(&self) -> (uint, Option<uint>) {
80                 self.0.size_hint()
81             }
82         }
83         #[stable]
84         impl<'a, P: CharEq> DoubleEndedIterator for $ti {
85             #[inline]
86             fn next_back(&mut self) -> Option<$te> {
87                 self.0.next_back()
88             }
89         }
90     };
91     (pattern forward $te:ty : $ti:ty) => {
92         #[stable]
93         impl<'a, P: CharEq> Iterator for $ti {
94             type Item = $te;
95
96             #[inline]
97             fn next(&mut self) -> Option<$te> {
98                 self.0.next()
99             }
100             #[inline]
101             fn size_hint(&self) -> (uint, Option<uint>) {
102                 self.0.size_hint()
103             }
104         }
105     }
106 }
107
108 /// A trait to abstract the idea of creating a new instance of a type from a
109 /// string.
110 // FIXME(#17307): there should be an `E` associated type for a `Result` return
111 #[unstable = "will return a Result once associated types are working"]
112 pub trait FromStr {
113     /// Parses a string `s` to return an optional value of this type. If the
114     /// string is ill-formatted, the None is returned.
115     fn from_str(s: &str) -> Option<Self>;
116 }
117
118 impl FromStr for bool {
119     /// Parse a `bool` from a string.
120     ///
121     /// Yields an `Option<bool>`, because `s` may or may not actually be parseable.
122     ///
123     /// # Examples
124     ///
125     /// ```rust
126     /// assert_eq!("true".parse(), Some(true));
127     /// assert_eq!("false".parse(), Some(false));
128     /// assert_eq!("not even a boolean".parse::<bool>(), None);
129     /// ```
130     #[inline]
131     fn from_str(s: &str) -> Option<bool> {
132         match s {
133             "true"  => Some(true),
134             "false" => Some(false),
135             _       => None,
136         }
137     }
138 }
139
140 /*
141 Section: Creating a string
142 */
143
144 /// Errors which can occur when attempting to interpret a byte slice as a `str`.
145 #[derive(Copy, Eq, PartialEq, Clone, Show)]
146 #[unstable = "error enumeration recently added and definitions may be refined"]
147 pub enum Utf8Error {
148     /// An invalid byte was detected at the byte offset given.
149     ///
150     /// The offset is guaranteed to be in bounds of the slice in question, and
151     /// the byte at the specified offset was the first invalid byte in the
152     /// sequence detected.
153     InvalidByte(uint),
154
155     /// The byte slice was invalid because more bytes were needed but no more
156     /// bytes were available.
157     TooShort,
158 }
159
160 /// Converts a slice of bytes to a string slice without performing any
161 /// allocations.
162 ///
163 /// Once the slice has been validated as utf-8, it is transmuted in-place and
164 /// returned as a '&str' instead of a '&[u8]'
165 ///
166 /// # Failure
167 ///
168 /// Returns `Err` if the slice is not utf-8 with a description as to why the
169 /// provided slice is not utf-8.
170 #[stable]
171 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
172     try!(run_utf8_validation_iterator(&mut v.iter()));
173     Ok(unsafe { from_utf8_unchecked(v) })
174 }
175
176 /// Converts a slice of bytes to a string slice without checking
177 /// that the string contains valid UTF-8.
178 #[stable]
179 pub unsafe fn from_utf8_unchecked<'a>(v: &'a [u8]) -> &'a str {
180     mem::transmute(v)
181 }
182
183 /// Constructs a static string slice from a given raw pointer.
184 ///
185 /// This function will read memory starting at `s` until it finds a 0, and then
186 /// transmute the memory up to that point as a string slice, returning the
187 /// corresponding `&'static str` value.
188 ///
189 /// This function is unsafe because the caller must ensure the C string itself
190 /// has the static lifetime and that the memory `s` is valid up to and including
191 /// the first null byte.
192 ///
193 /// # Panics
194 ///
195 /// This function will panic if the string pointed to by `s` is not valid UTF-8.
196 #[deprecated = "use std::ffi::c_str_to_bytes + str::from_utf8"]
197 pub unsafe fn from_c_str(s: *const i8) -> &'static str {
198     let s = s as *const u8;
199     let mut len = 0u;
200     while *s.offset(len as int) != 0 {
201         len += 1u;
202     }
203     let v: &'static [u8] = ::mem::transmute(Slice { data: s, len: len });
204     from_utf8(v).ok().expect("from_c_str passed invalid utf-8 data")
205 }
206
207 /// Something that can be used to compare against a character
208 #[unstable = "definition may change as pattern-related methods are stabilized"]
209 pub trait CharEq {
210     /// Determine if the splitter should split at the given character
211     fn matches(&mut self, char) -> bool;
212     /// Indicate if this is only concerned about ASCII characters,
213     /// which can allow for a faster implementation.
214     fn only_ascii(&self) -> bool;
215 }
216
217 impl CharEq for char {
218     #[inline]
219     fn matches(&mut self, c: char) -> bool { *self == c }
220
221     #[inline]
222     fn only_ascii(&self) -> bool { (*self as uint) < 128 }
223 }
224
225 impl<F> CharEq for F where F: FnMut(char) -> bool {
226     #[inline]
227     fn matches(&mut self, c: char) -> bool { (*self)(c) }
228
229     #[inline]
230     fn only_ascii(&self) -> bool { false }
231 }
232
233 impl<'a> CharEq for &'a [char] {
234     #[inline]
235     fn matches(&mut self, c: char) -> bool {
236         self.iter().any(|&m| { let mut m = m; m.matches(c) })
237     }
238
239     #[inline]
240     fn only_ascii(&self) -> bool {
241         self.iter().all(|m| m.only_ascii())
242     }
243 }
244
245 /*
246 Section: Iterators
247 */
248
249 /// Iterator for the char (representing *Unicode Scalar Values*) of a string
250 ///
251 /// Created with the method `.chars()`.
252 #[derive(Clone, Copy)]
253 #[stable]
254 pub struct Chars<'a> {
255     iter: slice::Iter<'a, u8>
256 }
257
258 // Return the initial codepoint accumulator for the first byte.
259 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
260 // for width 3, and 3 bits for width 4
261 macro_rules! utf8_first_byte {
262     ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
263 }
264
265 // return the value of $ch updated with continuation byte $byte
266 macro_rules! utf8_acc_cont_byte {
267     ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & CONT_MASK) as u32)
268 }
269
270 macro_rules! utf8_is_cont_byte {
271     ($byte:expr) => (($byte & !CONT_MASK) == TAG_CONT_U8)
272 }
273
274 #[inline]
275 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
276     match opt {
277         Some(&byte) => byte,
278         None => 0,
279     }
280 }
281
282 #[stable]
283 impl<'a> Iterator for Chars<'a> {
284     type Item = char;
285
286     #[inline]
287     fn next(&mut self) -> Option<char> {
288         // Decode UTF-8, using the valid UTF-8 invariant
289         let x = match self.iter.next() {
290             None => return None,
291             Some(&next_byte) if next_byte < 128 => return Some(next_byte as char),
292             Some(&next_byte) => next_byte,
293         };
294
295         // Multibyte case follows
296         // Decode from a byte combination out of: [[[x y] z] w]
297         // NOTE: Performance is sensitive to the exact formulation here
298         let init = utf8_first_byte!(x, 2);
299         let y = unwrap_or_0(self.iter.next());
300         let mut ch = utf8_acc_cont_byte!(init, y);
301         if x >= 0xE0 {
302             // [[x y z] w] case
303             // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
304             let z = unwrap_or_0(self.iter.next());
305             let y_z = utf8_acc_cont_byte!((y & CONT_MASK) as u32, z);
306             ch = init << 12 | y_z;
307             if x >= 0xF0 {
308                 // [x y z w] case
309                 // use only the lower 3 bits of `init`
310                 let w = unwrap_or_0(self.iter.next());
311                 ch = (init & 7) << 18 | utf8_acc_cont_byte!(y_z, w);
312             }
313         }
314
315         // str invariant says `ch` is a valid Unicode Scalar Value
316         unsafe {
317             Some(mem::transmute(ch))
318         }
319     }
320
321     #[inline]
322     fn size_hint(&self) -> (uint, Option<uint>) {
323         let (len, _) = self.iter.size_hint();
324         (len.saturating_add(3) / 4, Some(len))
325     }
326 }
327
328 #[stable]
329 impl<'a> DoubleEndedIterator for Chars<'a> {
330     #[inline]
331     fn next_back(&mut self) -> Option<char> {
332         let w = match self.iter.next_back() {
333             None => return None,
334             Some(&back_byte) if back_byte < 128 => return Some(back_byte as char),
335             Some(&back_byte) => back_byte,
336         };
337
338         // Multibyte case follows
339         // Decode from a byte combination out of: [x [y [z w]]]
340         let mut ch;
341         let z = unwrap_or_0(self.iter.next_back());
342         ch = utf8_first_byte!(z, 2);
343         if utf8_is_cont_byte!(z) {
344             let y = unwrap_or_0(self.iter.next_back());
345             ch = utf8_first_byte!(y, 3);
346             if utf8_is_cont_byte!(y) {
347                 let x = unwrap_or_0(self.iter.next_back());
348                 ch = utf8_first_byte!(x, 4);
349                 ch = utf8_acc_cont_byte!(ch, y);
350             }
351             ch = utf8_acc_cont_byte!(ch, z);
352         }
353         ch = utf8_acc_cont_byte!(ch, w);
354
355         // str invariant says `ch` is a valid Unicode Scalar Value
356         unsafe {
357             Some(mem::transmute(ch))
358         }
359     }
360 }
361
362 /// External iterator for a string's characters and their byte offsets.
363 /// Use with the `std::iter` module.
364 #[derive(Clone)]
365 #[stable]
366 pub struct CharIndices<'a> {
367     front_offset: uint,
368     iter: Chars<'a>,
369 }
370
371 #[stable]
372 impl<'a> Iterator for CharIndices<'a> {
373     type Item = (uint, char);
374
375     #[inline]
376     fn next(&mut self) -> Option<(uint, char)> {
377         let (pre_len, _) = self.iter.iter.size_hint();
378         match self.iter.next() {
379             None => None,
380             Some(ch) => {
381                 let index = self.front_offset;
382                 let (len, _) = self.iter.iter.size_hint();
383                 self.front_offset += pre_len - len;
384                 Some((index, ch))
385             }
386         }
387     }
388
389     #[inline]
390     fn size_hint(&self) -> (uint, Option<uint>) {
391         self.iter.size_hint()
392     }
393 }
394
395 #[stable]
396 impl<'a> DoubleEndedIterator for CharIndices<'a> {
397     #[inline]
398     fn next_back(&mut self) -> Option<(uint, char)> {
399         match self.iter.next_back() {
400             None => None,
401             Some(ch) => {
402                 let (len, _) = self.iter.iter.size_hint();
403                 let index = self.front_offset + len;
404                 Some((index, ch))
405             }
406         }
407     }
408 }
409
410 /// External iterator for a string's bytes.
411 /// Use with the `std::iter` module.
412 ///
413 /// Created with `StrExt::bytes`
414 #[stable]
415 #[derive(Clone)]
416 pub struct Bytes<'a>(Map<&'a u8, u8, slice::Iter<'a, u8>, BytesDeref>);
417 delegate_iter!{exact u8 : Bytes<'a>}
418
419 /// A temporary fn new type that ensures that the `Bytes` iterator
420 /// is cloneable.
421 #[derive(Copy, Clone)]
422 struct BytesDeref;
423
424 impl<'a> Fn(&'a u8) -> u8 for BytesDeref {
425     #[inline]
426     extern "rust-call" fn call(&self, (ptr,): (&'a u8,)) -> u8 {
427         *ptr
428     }
429 }
430
431 /// An iterator over the substrings of a string, separated by `sep`.
432 #[derive(Clone)]
433 struct CharSplits<'a, Sep> {
434     /// The slice remaining to be iterated
435     string: &'a str,
436     sep: Sep,
437     /// Whether an empty string at the end is allowed
438     allow_trailing_empty: bool,
439     only_ascii: bool,
440     finished: bool,
441 }
442
443 /// An iterator over the substrings of a string, separated by `sep`,
444 /// splitting at most `count` times.
445 #[derive(Clone)]
446 struct CharSplitsN<'a, Sep> {
447     iter: CharSplits<'a, Sep>,
448     /// The number of splits remaining
449     count: uint,
450     invert: bool,
451 }
452
453 /// An iterator over the lines of a string, separated by `\n`.
454 #[stable]
455 pub struct Lines<'a> {
456     inner: CharSplits<'a, char>,
457 }
458
459 /// An iterator over the lines of a string, separated by either `\n` or (`\r\n`).
460 #[stable]
461 pub struct LinesAny<'a> {
462     inner: Map<&'a str, &'a str, Lines<'a>, fn(&str) -> &str>,
463 }
464
465 impl<'a, Sep> CharSplits<'a, Sep> {
466     #[inline]
467     fn get_end(&mut self) -> Option<&'a str> {
468         if !self.finished && (self.allow_trailing_empty || self.string.len() > 0) {
469             self.finished = true;
470             Some(self.string)
471         } else {
472             None
473         }
474     }
475 }
476
477 #[stable]
478 impl<'a, Sep: CharEq> Iterator for CharSplits<'a, Sep> {
479     type Item = &'a str;
480
481     #[inline]
482     fn next(&mut self) -> Option<&'a str> {
483         if self.finished { return None }
484
485         let mut next_split = None;
486         if self.only_ascii {
487             for (idx, byte) in self.string.bytes().enumerate() {
488                 if self.sep.matches(byte as char) && byte < 128u8 {
489                     next_split = Some((idx, idx + 1));
490                     break;
491                 }
492             }
493         } else {
494             for (idx, ch) in self.string.char_indices() {
495                 if self.sep.matches(ch) {
496                     next_split = Some((idx, self.string.char_range_at(idx).next));
497                     break;
498                 }
499             }
500         }
501         match next_split {
502             Some((a, b)) => unsafe {
503                 let elt = self.string.slice_unchecked(0, a);
504                 self.string = self.string.slice_unchecked(b, self.string.len());
505                 Some(elt)
506             },
507             None => self.get_end(),
508         }
509     }
510 }
511
512 #[stable]
513 impl<'a, Sep: CharEq> DoubleEndedIterator for CharSplits<'a, Sep> {
514     #[inline]
515     fn next_back(&mut self) -> Option<&'a str> {
516         if self.finished { return None }
517
518         if !self.allow_trailing_empty {
519             self.allow_trailing_empty = true;
520             match self.next_back() {
521                 Some(elt) if !elt.is_empty() => return Some(elt),
522                 _ => if self.finished { return None }
523             }
524         }
525         let len = self.string.len();
526         let mut next_split = None;
527
528         if self.only_ascii {
529             for (idx, byte) in self.string.bytes().enumerate().rev() {
530                 if self.sep.matches(byte as char) && byte < 128u8 {
531                     next_split = Some((idx, idx + 1));
532                     break;
533                 }
534             }
535         } else {
536             for (idx, ch) in self.string.char_indices().rev() {
537                 if self.sep.matches(ch) {
538                     next_split = Some((idx, self.string.char_range_at(idx).next));
539                     break;
540                 }
541             }
542         }
543         match next_split {
544             Some((a, b)) => unsafe {
545                 let elt = self.string.slice_unchecked(b, len);
546                 self.string = self.string.slice_unchecked(0, a);
547                 Some(elt)
548             },
549             None => { self.finished = true; Some(self.string) }
550         }
551     }
552 }
553
554 #[stable]
555 impl<'a, Sep: CharEq> Iterator for CharSplitsN<'a, Sep> {
556     type Item = &'a str;
557
558     #[inline]
559     fn next(&mut self) -> Option<&'a str> {
560         if self.count != 0 {
561             self.count -= 1;
562             if self.invert { self.iter.next_back() } else { self.iter.next() }
563         } else {
564             self.iter.get_end()
565         }
566     }
567 }
568
569 /// The internal state of an iterator that searches for matches of a substring
570 /// within a larger string using naive search
571 #[derive(Clone)]
572 struct NaiveSearcher {
573     position: uint
574 }
575
576 impl NaiveSearcher {
577     fn new() -> NaiveSearcher {
578         NaiveSearcher { position: 0 }
579     }
580
581     fn next(&mut self, haystack: &[u8], needle: &[u8]) -> Option<(uint, uint)> {
582         while self.position + needle.len() <= haystack.len() {
583             if &haystack[self.position .. self.position + needle.len()] == needle {
584                 let match_pos = self.position;
585                 self.position += needle.len(); // add 1 for all matches
586                 return Some((match_pos, match_pos + needle.len()));
587             } else {
588                 self.position += 1;
589             }
590         }
591         None
592     }
593 }
594
595 /// The internal state of an iterator that searches for matches of a substring
596 /// within a larger string using two-way search
597 #[derive(Clone)]
598 struct TwoWaySearcher {
599     // constants
600     crit_pos: uint,
601     period: uint,
602     byteset: u64,
603
604     // variables
605     position: uint,
606     memory: uint
607 }
608
609 /*
610     This is the Two-Way search algorithm, which was introduced in the paper:
611     Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
612
613     Here's some background information.
614
615     A *word* is a string of symbols. The *length* of a word should be a familiar
616     notion, and here we denote it for any word x by |x|.
617     (We also allow for the possibility of the *empty word*, a word of length zero).
618
619     If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
620     *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
621     For example, both 1 and 2 are periods for the string "aa". As another example,
622     the only period of the string "abcd" is 4.
623
624     We denote by period(x) the *smallest* period of x (provided that x is non-empty).
625     This is always well-defined since every non-empty word x has at least one period,
626     |x|. We sometimes call this *the period* of x.
627
628     If u, v and x are words such that x = uv, where uv is the concatenation of u and
629     v, then we say that (u, v) is a *factorization* of x.
630
631     Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
632     that both of the following hold
633
634       - either w is a suffix of u or u is a suffix of w
635       - either w is a prefix of v or v is a prefix of w
636
637     then w is said to be a *repetition* for the factorization (u, v).
638
639     Just to unpack this, there are four possibilities here. Let w = "abc". Then we
640     might have:
641
642       - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
643       - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
644       - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
645       - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
646
647     Note that the word vu is a repetition for any factorization (u,v) of x = uv,
648     so every factorization has at least one repetition.
649
650     If x is a string and (u, v) is a factorization for x, then a *local period* for
651     (u, v) is an integer r such that there is some word w such that |w| = r and w is
652     a repetition for (u, v).
653
654     We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
655     call this *the local period* of (u, v). Provided that x = uv is non-empty, this
656     is well-defined (because each non-empty word has at least one factorization, as
657     noted above).
658
659     It can be proven that the following is an equivalent definition of a local period
660     for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
661     all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
662     defined. (i.e. i > 0 and i + r < |x|).
663
664     Using the above reformulation, it is easy to prove that
665
666         1 <= local_period(u, v) <= period(uv)
667
668     A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
669     *critical factorization*.
670
671     The algorithm hinges on the following theorem, which is stated without proof:
672
673     **Critical Factorization Theorem** Any word x has at least one critical
674     factorization (u, v) such that |u| < period(x).
675
676     The purpose of maximal_suffix is to find such a critical factorization.
677
678 */
679 impl TwoWaySearcher {
680     fn new(needle: &[u8]) -> TwoWaySearcher {
681         let (crit_pos1, period1) = TwoWaySearcher::maximal_suffix(needle, false);
682         let (crit_pos2, period2) = TwoWaySearcher::maximal_suffix(needle, true);
683
684         let crit_pos;
685         let period;
686         if crit_pos1 > crit_pos2 {
687             crit_pos = crit_pos1;
688             period = period1;
689         } else {
690             crit_pos = crit_pos2;
691             period = period2;
692         }
693
694         // This isn't in the original algorithm, as far as I'm aware.
695         let byteset = needle.iter()
696                             .fold(0, |a, &b| (1 << ((b & 0x3f) as uint)) | a);
697
698         // A particularly readable explanation of what's going on here can be found
699         // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
700         // see the code for "Algorithm CP" on p. 323.
701         //
702         // What's going on is we have some critical factorization (u, v) of the
703         // needle, and we want to determine whether u is a suffix of
704         // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
705         // "Algorithm CP2", which is optimized for when the period of the needle
706         // is large.
707         if &needle[..crit_pos] == &needle[period.. period + crit_pos] {
708             TwoWaySearcher {
709                 crit_pos: crit_pos,
710                 period: period,
711                 byteset: byteset,
712
713                 position: 0,
714                 memory: 0
715             }
716         } else {
717             TwoWaySearcher {
718                 crit_pos: crit_pos,
719                 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
720                 byteset: byteset,
721
722                 position: 0,
723                 memory: uint::MAX // Dummy value to signify that the period is long
724             }
725         }
726     }
727
728     // One of the main ideas of Two-Way is that we factorize the needle into
729     // two halves, (u, v), and begin trying to find v in the haystack by scanning
730     // left to right. If v matches, we try to match u by scanning right to left.
731     // How far we can jump when we encounter a mismatch is all based on the fact
732     // that (u, v) is a critical factorization for the needle.
733     #[inline]
734     fn next(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> Option<(uint, uint)> {
735         'search: loop {
736             // Check that we have room to search in
737             if self.position + needle.len() > haystack.len() {
738                 return None;
739             }
740
741             // Quickly skip by large portions unrelated to our substring
742             if (self.byteset >>
743                     ((haystack[self.position + needle.len() - 1] & 0x3f)
744                      as uint)) & 1 == 0 {
745                 self.position += needle.len();
746                 if !long_period {
747                     self.memory = 0;
748                 }
749                 continue 'search;
750             }
751
752             // See if the right part of the needle matches
753             let start = if long_period { self.crit_pos }
754                         else { cmp::max(self.crit_pos, self.memory) };
755             for i in range(start, needle.len()) {
756                 if needle[i] != haystack[self.position + i] {
757                     self.position += i - self.crit_pos + 1;
758                     if !long_period {
759                         self.memory = 0;
760                     }
761                     continue 'search;
762                 }
763             }
764
765             // See if the left part of the needle matches
766             let start = if long_period { 0 } else { self.memory };
767             for i in range(start, self.crit_pos).rev() {
768                 if needle[i] != haystack[self.position + i] {
769                     self.position += self.period;
770                     if !long_period {
771                         self.memory = needle.len() - self.period;
772                     }
773                     continue 'search;
774                 }
775             }
776
777             // We have found a match!
778             let match_pos = self.position;
779             self.position += needle.len(); // add self.period for all matches
780             if !long_period {
781                 self.memory = 0; // set to needle.len() - self.period for all matches
782             }
783             return Some((match_pos, match_pos + needle.len()));
784         }
785     }
786
787     // Computes a critical factorization (u, v) of `arr`.
788     // Specifically, returns (i, p), where i is the starting index of v in some
789     // critical factorization (u, v) and p = period(v)
790     #[inline]
791     fn maximal_suffix(arr: &[u8], reversed: bool) -> (uint, uint) {
792         let mut left = -1; // Corresponds to i in the paper
793         let mut right = 0; // Corresponds to j in the paper
794         let mut offset = 1; // Corresponds to k in the paper
795         let mut period = 1; // Corresponds to p in the paper
796
797         while right + offset < arr.len() {
798             let a;
799             let b;
800             if reversed {
801                 a = arr[left + offset];
802                 b = arr[right + offset];
803             } else {
804                 a = arr[right + offset];
805                 b = arr[left + offset];
806             }
807             if a < b {
808                 // Suffix is smaller, period is entire prefix so far.
809                 right += offset;
810                 offset = 1;
811                 period = right - left;
812             } else if a == b {
813                 // Advance through repetition of the current period.
814                 if offset == period {
815                     right += offset;
816                     offset = 1;
817                 } else {
818                     offset += 1;
819                 }
820             } else {
821                 // Suffix is larger, start over from current location.
822                 left = right;
823                 right += 1;
824                 offset = 1;
825                 period = 1;
826             }
827         }
828         (left + 1, period)
829     }
830 }
831
832 /// The internal state of an iterator that searches for matches of a substring
833 /// within a larger string using a dynamically chosen search algorithm
834 #[derive(Clone)]
835 enum Searcher {
836     Naive(NaiveSearcher),
837     TwoWay(TwoWaySearcher),
838     TwoWayLong(TwoWaySearcher)
839 }
840
841 impl Searcher {
842     fn new(haystack: &[u8], needle: &[u8]) -> Searcher {
843         // FIXME: Tune this.
844         // FIXME(#16715): This unsigned integer addition will probably not
845         // overflow because that would mean that the memory almost solely
846         // consists of the needle. Needs #16715 to be formally fixed.
847         if needle.len() + 20 > haystack.len() {
848             Naive(NaiveSearcher::new())
849         } else {
850             let searcher = TwoWaySearcher::new(needle);
851             if searcher.memory == uint::MAX { // If the period is long
852                 TwoWayLong(searcher)
853             } else {
854                 TwoWay(searcher)
855             }
856         }
857     }
858 }
859
860 /// An iterator over the start and end indices of the matches of a
861 /// substring within a larger string
862 #[derive(Clone)]
863 #[unstable = "type may be removed"]
864 pub struct MatchIndices<'a> {
865     // constants
866     haystack: &'a str,
867     needle: &'a str,
868     searcher: Searcher
869 }
870
871 /// An iterator over the substrings of a string separated by a given
872 /// search string
873 #[derive(Clone)]
874 #[unstable = "type may be removed"]
875 pub struct SplitStr<'a> {
876     it: MatchIndices<'a>,
877     last_end: uint,
878     finished: bool
879 }
880
881 #[stable]
882 impl<'a> Iterator for MatchIndices<'a> {
883     type Item = (uint, uint);
884
885     #[inline]
886     fn next(&mut self) -> Option<(uint, uint)> {
887         match self.searcher {
888             Naive(ref mut searcher)
889                 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes()),
890             TwoWay(ref mut searcher)
891                 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), false),
892             TwoWayLong(ref mut searcher)
893                 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), true)
894         }
895     }
896 }
897
898 #[stable]
899 impl<'a> Iterator for SplitStr<'a> {
900     type Item = &'a str;
901
902     #[inline]
903     fn next(&mut self) -> Option<&'a str> {
904         if self.finished { return None; }
905
906         match self.it.next() {
907             Some((from, to)) => {
908                 let ret = Some(self.it.haystack.slice(self.last_end, from));
909                 self.last_end = to;
910                 ret
911             }
912             None => {
913                 self.finished = true;
914                 Some(self.it.haystack.slice(self.last_end, self.it.haystack.len()))
915             }
916         }
917     }
918 }
919
920
921 /*
922 Section: Comparing strings
923 */
924
925 // share the implementation of the lang-item vs. non-lang-item
926 // eq_slice.
927 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
928 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
929 #[inline]
930 fn eq_slice_(a: &str, b: &str) -> bool {
931     #[allow(improper_ctypes)]
932     extern { fn memcmp(s1: *const i8, s2: *const i8, n: uint) -> i32; }
933     a.len() == b.len() && unsafe {
934         memcmp(a.as_ptr() as *const i8,
935                b.as_ptr() as *const i8,
936                a.len()) == 0
937     }
938 }
939
940 /// Bytewise slice equality
941 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
942 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
943 #[lang="str_eq"]
944 #[inline]
945 fn eq_slice(a: &str, b: &str) -> bool {
946     eq_slice_(a, b)
947 }
948
949 /*
950 Section: Misc
951 */
952
953 /// Walk through `iter` checking that it's a valid UTF-8 sequence,
954 /// returning `true` in that case, or, if it is invalid, `false` with
955 /// `iter` reset such that it is pointing at the first byte in the
956 /// invalid sequence.
957 #[inline(always)]
958 fn run_utf8_validation_iterator(iter: &mut slice::Iter<u8>)
959                                 -> Result<(), Utf8Error> {
960     let whole = iter.as_slice();
961     loop {
962         // save the current thing we're pointing at.
963         let old = *iter;
964
965         // restore the iterator we had at the start of this codepoint.
966         macro_rules! err { () => {{
967             *iter = old;
968             return Err(Utf8Error::InvalidByte(whole.len() - iter.as_slice().len()))
969         }}}
970
971         macro_rules! next { () => {
972             match iter.next() {
973                 Some(a) => *a,
974                 // we needed data, but there was none: error!
975                 None => return Err(Utf8Error::TooShort),
976             }
977         }}
978
979         let first = match iter.next() {
980             Some(&b) => b,
981             // we're at the end of the iterator and a codepoint
982             // boundary at the same time, so this string is valid.
983             None => return Ok(())
984         };
985
986         // ASCII characters are always valid, so only large
987         // bytes need more examination.
988         if first >= 128 {
989             let w = UTF8_CHAR_WIDTH[first as uint] as uint;
990             let second = next!();
991             // 2-byte encoding is for codepoints  \u{0080} to  \u{07ff}
992             //        first  C2 80        last DF BF
993             // 3-byte encoding is for codepoints  \u{0800} to  \u{ffff}
994             //        first  E0 A0 80     last EF BF BF
995             //   excluding surrogates codepoints  \u{d800} to  \u{dfff}
996             //               ED A0 80 to       ED BF BF
997             // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
998             //        first  F0 90 80 80  last F4 8F BF BF
999             //
1000             // Use the UTF-8 syntax from the RFC
1001             //
1002             // https://tools.ietf.org/html/rfc3629
1003             // UTF8-1      = %x00-7F
1004             // UTF8-2      = %xC2-DF UTF8-tail
1005             // UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
1006             //               %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
1007             // UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
1008             //               %xF4 %x80-8F 2( UTF8-tail )
1009             match w {
1010                 2 => if second & !CONT_MASK != TAG_CONT_U8 {err!()},
1011                 3 => {
1012                     match (first, second, next!() & !CONT_MASK) {
1013                         (0xE0         , 0xA0 ... 0xBF, TAG_CONT_U8) |
1014                         (0xE1 ... 0xEC, 0x80 ... 0xBF, TAG_CONT_U8) |
1015                         (0xED         , 0x80 ... 0x9F, TAG_CONT_U8) |
1016                         (0xEE ... 0xEF, 0x80 ... 0xBF, TAG_CONT_U8) => {}
1017                         _ => err!()
1018                     }
1019                 }
1020                 4 => {
1021                     match (first, second, next!() & !CONT_MASK, next!() & !CONT_MASK) {
1022                         (0xF0         , 0x90 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
1023                         (0xF1 ... 0xF3, 0x80 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
1024                         (0xF4         , 0x80 ... 0x8F, TAG_CONT_U8, TAG_CONT_U8) => {}
1025                         _ => err!()
1026                     }
1027                 }
1028                 _ => err!()
1029             }
1030         }
1031     }
1032 }
1033
1034 // https://tools.ietf.org/html/rfc3629
1035 static UTF8_CHAR_WIDTH: [u8; 256] = [
1036 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1037 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1038 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1039 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1040 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1041 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1042 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1043 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1044 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1045 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1046 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1047 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1048 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1049 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1050 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1051 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1052 ];
1053
1054 /// Struct that contains a `char` and the index of the first byte of
1055 /// the next `char` in a string.  This can be used as a data structure
1056 /// for iterating over the UTF-8 bytes of a string.
1057 #[derive(Copy)]
1058 #[unstable = "naming is uncertain with container conventions"]
1059 pub struct CharRange {
1060     /// Current `char`
1061     pub ch: char,
1062     /// Index of the first byte of the next `char`
1063     pub next: uint,
1064 }
1065
1066 /// Mask of the value bits of a continuation byte
1067 const CONT_MASK: u8 = 0b0011_1111u8;
1068 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte
1069 const TAG_CONT_U8: u8 = 0b1000_0000u8;
1070
1071 /*
1072 Section: Trait implementations
1073 */
1074
1075 mod traits {
1076     use cmp::{Ordering, Ord, PartialEq, PartialOrd, Eq};
1077     use cmp::Ordering::{Less, Equal, Greater};
1078     use iter::IteratorExt;
1079     use option::Option;
1080     use option::Option::Some;
1081     use ops;
1082     use str::{StrExt, eq_slice};
1083
1084     #[stable]
1085     impl Ord for str {
1086         #[inline]
1087         fn cmp(&self, other: &str) -> Ordering {
1088             for (s_b, o_b) in self.bytes().zip(other.bytes()) {
1089                 match s_b.cmp(&o_b) {
1090                     Greater => return Greater,
1091                     Less => return Less,
1092                     Equal => ()
1093                 }
1094             }
1095
1096             self.len().cmp(&other.len())
1097         }
1098     }
1099
1100     #[stable]
1101     impl PartialEq for str {
1102         #[inline]
1103         fn eq(&self, other: &str) -> bool {
1104             eq_slice(self, other)
1105         }
1106         #[inline]
1107         fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1108     }
1109
1110     #[stable]
1111     impl Eq for str {}
1112
1113     #[stable]
1114     impl PartialOrd for str {
1115         #[inline]
1116         fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1117             Some(self.cmp(other))
1118         }
1119     }
1120
1121     impl ops::Index<ops::Range<uint>> for str {
1122         type Output = str;
1123         #[inline]
1124         fn index(&self, index: &ops::Range<uint>) -> &str {
1125             self.slice(index.start, index.end)
1126         }
1127     }
1128     impl ops::Index<ops::RangeTo<uint>> for str {
1129         type Output = str;
1130         #[inline]
1131         fn index(&self, index: &ops::RangeTo<uint>) -> &str {
1132             self.slice_to(index.end)
1133         }
1134     }
1135     impl ops::Index<ops::RangeFrom<uint>> for str {
1136         type Output = str;
1137         #[inline]
1138         fn index(&self, index: &ops::RangeFrom<uint>) -> &str {
1139             self.slice_from(index.start)
1140         }
1141     }
1142     impl ops::Index<ops::FullRange> for str {
1143         type Output = str;
1144         #[inline]
1145         fn index(&self, _index: &ops::FullRange) -> &str {
1146             self
1147         }
1148     }
1149 }
1150
1151 /// Any string that can be represented as a slice
1152 #[unstable = "Instead of taking this bound generically, this trait will be \
1153               replaced with one of slicing syntax, deref coercions, or \
1154               a more generic conversion trait"]
1155 pub trait Str {
1156     /// Work with `self` as a slice.
1157     fn as_slice<'a>(&'a self) -> &'a str;
1158 }
1159
1160 impl Str for str {
1161     #[inline]
1162     fn as_slice<'a>(&'a self) -> &'a str { self }
1163 }
1164
1165 impl<'a, S: ?Sized> Str for &'a S where S: Str {
1166     #[inline]
1167     fn as_slice(&self) -> &str { Str::as_slice(*self) }
1168 }
1169
1170 /// Return type of `StrExt::split`
1171 #[derive(Clone)]
1172 #[stable]
1173 pub struct Split<'a, P>(CharSplits<'a, P>);
1174 delegate_iter!{pattern &'a str : Split<'a, P>}
1175
1176 /// Return type of `StrExt::split_terminator`
1177 #[derive(Clone)]
1178 #[unstable = "might get removed in favour of a constructor method on Split"]
1179 pub struct SplitTerminator<'a, P>(CharSplits<'a, P>);
1180 delegate_iter!{pattern &'a str : SplitTerminator<'a, P>}
1181
1182 /// Return type of `StrExt::splitn`
1183 #[derive(Clone)]
1184 #[stable]
1185 pub struct SplitN<'a, P>(CharSplitsN<'a, P>);
1186 delegate_iter!{pattern forward &'a str : SplitN<'a, P>}
1187
1188 /// Return type of `StrExt::rsplitn`
1189 #[derive(Clone)]
1190 #[stable]
1191 pub struct RSplitN<'a, P>(CharSplitsN<'a, P>);
1192 delegate_iter!{pattern forward &'a str : RSplitN<'a, P>}
1193
1194 /// Methods for string slices
1195 #[allow(missing_docs)]
1196 pub trait StrExt {
1197     // NB there are no docs here are they're all located on the StrExt trait in
1198     // libcollections, not here.
1199
1200     fn contains(&self, pat: &str) -> bool;
1201     fn contains_char<P: CharEq>(&self, pat: P) -> bool;
1202     fn chars<'a>(&'a self) -> Chars<'a>;
1203     fn bytes<'a>(&'a self) -> Bytes<'a>;
1204     fn char_indices<'a>(&'a self) -> CharIndices<'a>;
1205     fn split<'a, P: CharEq>(&'a self, pat: P) -> Split<'a, P>;
1206     fn splitn<'a, P: CharEq>(&'a self, count: uint, pat: P) -> SplitN<'a, P>;
1207     fn split_terminator<'a, P: CharEq>(&'a self, pat: P) -> SplitTerminator<'a, P>;
1208     fn rsplitn<'a, P: CharEq>(&'a self, count: uint, pat: P) -> RSplitN<'a, P>;
1209     fn match_indices<'a>(&'a self, sep: &'a str) -> MatchIndices<'a>;
1210     fn split_str<'a>(&'a self, pat: &'a str) -> SplitStr<'a>;
1211     fn lines<'a>(&'a self) -> Lines<'a>;
1212     fn lines_any<'a>(&'a self) -> LinesAny<'a>;
1213     fn char_len(&self) -> uint;
1214     fn slice<'a>(&'a self, begin: uint, end: uint) -> &'a str;
1215     fn slice_from<'a>(&'a self, begin: uint) -> &'a str;
1216     fn slice_to<'a>(&'a self, end: uint) -> &'a str;
1217     fn slice_chars<'a>(&'a self, begin: uint, end: uint) -> &'a str;
1218     unsafe fn slice_unchecked<'a>(&'a self, begin: uint, end: uint) -> &'a str;
1219     fn starts_with(&self, pat: &str) -> bool;
1220     fn ends_with(&self, pat: &str) -> bool;
1221     fn trim_matches<'a, P: CharEq>(&'a self, pat: P) -> &'a str;
1222     fn trim_left_matches<'a, P: CharEq>(&'a self, pat: P) -> &'a str;
1223     fn trim_right_matches<'a, P: CharEq>(&'a self, pat: P) -> &'a str;
1224     fn is_char_boundary(&self, index: uint) -> bool;
1225     fn char_range_at(&self, start: uint) -> CharRange;
1226     fn char_range_at_reverse(&self, start: uint) -> CharRange;
1227     fn char_at(&self, i: uint) -> char;
1228     fn char_at_reverse(&self, i: uint) -> char;
1229     fn as_bytes<'a>(&'a self) -> &'a [u8];
1230     fn find<P: CharEq>(&self, pat: P) -> Option<uint>;
1231     fn rfind<P: CharEq>(&self, pat: P) -> Option<uint>;
1232     fn find_str(&self, pat: &str) -> Option<uint>;
1233     fn slice_shift_char<'a>(&'a self) -> Option<(char, &'a str)>;
1234     fn subslice_offset(&self, inner: &str) -> uint;
1235     fn as_ptr(&self) -> *const u8;
1236     fn len(&self) -> uint;
1237     fn is_empty(&self) -> bool;
1238     fn parse<T: FromStr>(&self) -> Option<T>;
1239 }
1240
1241 #[inline(never)]
1242 fn slice_error_fail(s: &str, begin: uint, end: uint) -> ! {
1243     assert!(begin <= end);
1244     panic!("index {} and/or {} in `{}` do not lie on character boundary",
1245           begin, end, s);
1246 }
1247
1248 impl StrExt for str {
1249     #[inline]
1250     fn contains(&self, needle: &str) -> bool {
1251         self.find_str(needle).is_some()
1252     }
1253
1254     #[inline]
1255     fn contains_char<P: CharEq>(&self, pat: P) -> bool {
1256         self.find(pat).is_some()
1257     }
1258
1259     #[inline]
1260     fn chars(&self) -> Chars {
1261         Chars{iter: self.as_bytes().iter()}
1262     }
1263
1264     #[inline]
1265     fn bytes(&self) -> Bytes {
1266         Bytes(self.as_bytes().iter().map(BytesDeref))
1267     }
1268
1269     #[inline]
1270     fn char_indices(&self) -> CharIndices {
1271         CharIndices { front_offset: 0, iter: self.chars() }
1272     }
1273
1274     #[inline]
1275     fn split<P: CharEq>(&self, pat: P) -> Split<P> {
1276         Split(CharSplits {
1277             string: self,
1278             only_ascii: pat.only_ascii(),
1279             sep: pat,
1280             allow_trailing_empty: true,
1281             finished: false,
1282         })
1283     }
1284
1285     #[inline]
1286     fn splitn<P: CharEq>(&self, count: uint, pat: P) -> SplitN<P> {
1287         SplitN(CharSplitsN {
1288             iter: self.split(pat).0,
1289             count: count,
1290             invert: false,
1291         })
1292     }
1293
1294     #[inline]
1295     fn split_terminator<P: CharEq>(&self, pat: P) -> SplitTerminator<P> {
1296         SplitTerminator(CharSplits {
1297             allow_trailing_empty: false,
1298             ..self.split(pat).0
1299         })
1300     }
1301
1302     #[inline]
1303     fn rsplitn<P: CharEq>(&self, count: uint, pat: P) -> RSplitN<P> {
1304         RSplitN(CharSplitsN {
1305             iter: self.split(pat).0,
1306             count: count,
1307             invert: true,
1308         })
1309     }
1310
1311     #[inline]
1312     fn match_indices<'a>(&'a self, sep: &'a str) -> MatchIndices<'a> {
1313         assert!(!sep.is_empty());
1314         MatchIndices {
1315             haystack: self,
1316             needle: sep,
1317             searcher: Searcher::new(self.as_bytes(), sep.as_bytes())
1318         }
1319     }
1320
1321     #[inline]
1322     fn split_str<'a>(&'a self, sep: &'a str) -> SplitStr<'a> {
1323         SplitStr {
1324             it: self.match_indices(sep),
1325             last_end: 0,
1326             finished: false
1327         }
1328     }
1329
1330     #[inline]
1331     fn lines(&self) -> Lines {
1332         Lines { inner: self.split_terminator('\n').0 }
1333     }
1334
1335     fn lines_any(&self) -> LinesAny {
1336         fn f(line: &str) -> &str {
1337             let l = line.len();
1338             if l > 0 && line.as_bytes()[l - 1] == b'\r' { line.slice(0, l - 1) }
1339             else { line }
1340         }
1341
1342         let f: fn(&str) -> &str = f; // coerce to fn pointer
1343         LinesAny { inner: self.lines().map(f) }
1344     }
1345
1346     #[inline]
1347     fn char_len(&self) -> uint { self.chars().count() }
1348
1349     #[inline]
1350     fn slice(&self, begin: uint, end: uint) -> &str {
1351         // is_char_boundary checks that the index is in [0, .len()]
1352         if begin <= end &&
1353            self.is_char_boundary(begin) &&
1354            self.is_char_boundary(end) {
1355             unsafe { self.slice_unchecked(begin, end) }
1356         } else {
1357             slice_error_fail(self, begin, end)
1358         }
1359     }
1360
1361     #[inline]
1362     fn slice_from(&self, begin: uint) -> &str {
1363         // is_char_boundary checks that the index is in [0, .len()]
1364         if self.is_char_boundary(begin) {
1365             unsafe { self.slice_unchecked(begin, self.len()) }
1366         } else {
1367             slice_error_fail(self, begin, self.len())
1368         }
1369     }
1370
1371     #[inline]
1372     fn slice_to(&self, end: uint) -> &str {
1373         // is_char_boundary checks that the index is in [0, .len()]
1374         if self.is_char_boundary(end) {
1375             unsafe { self.slice_unchecked(0, end) }
1376         } else {
1377             slice_error_fail(self, 0, end)
1378         }
1379     }
1380
1381     fn slice_chars(&self, begin: uint, end: uint) -> &str {
1382         assert!(begin <= end);
1383         let mut count = 0;
1384         let mut begin_byte = None;
1385         let mut end_byte = None;
1386
1387         // This could be even more efficient by not decoding,
1388         // only finding the char boundaries
1389         for (idx, _) in self.char_indices() {
1390             if count == begin { begin_byte = Some(idx); }
1391             if count == end { end_byte = Some(idx); break; }
1392             count += 1;
1393         }
1394         if begin_byte.is_none() && count == begin { begin_byte = Some(self.len()) }
1395         if end_byte.is_none() && count == end { end_byte = Some(self.len()) }
1396
1397         match (begin_byte, end_byte) {
1398             (None, _) => panic!("slice_chars: `begin` is beyond end of string"),
1399             (_, None) => panic!("slice_chars: `end` is beyond end of string"),
1400             (Some(a), Some(b)) => unsafe { self.slice_unchecked(a, b) }
1401         }
1402     }
1403
1404     #[inline]
1405     unsafe fn slice_unchecked(&self, begin: uint, end: uint) -> &str {
1406         mem::transmute(Slice {
1407             data: self.as_ptr().offset(begin as int),
1408             len: end - begin,
1409         })
1410     }
1411
1412     #[inline]
1413     fn starts_with(&self, needle: &str) -> bool {
1414         let n = needle.len();
1415         self.len() >= n && needle.as_bytes() == &self.as_bytes()[..n]
1416     }
1417
1418     #[inline]
1419     fn ends_with(&self, needle: &str) -> bool {
1420         let (m, n) = (self.len(), needle.len());
1421         m >= n && needle.as_bytes() == &self.as_bytes()[(m-n)..]
1422     }
1423
1424     #[inline]
1425     fn trim_matches<P: CharEq>(&self, mut pat: P) -> &str {
1426         let cur = match self.find(|&mut: c: char| !pat.matches(c)) {
1427             None => "",
1428             Some(i) => unsafe { self.slice_unchecked(i, self.len()) }
1429         };
1430         match cur.rfind(|&mut: c: char| !pat.matches(c)) {
1431             None => "",
1432             Some(i) => {
1433                 let right = cur.char_range_at(i).next;
1434                 unsafe { cur.slice_unchecked(0, right) }
1435             }
1436         }
1437     }
1438
1439     #[inline]
1440     fn trim_left_matches<P: CharEq>(&self, mut pat: P) -> &str {
1441         match self.find(|&mut: c: char| !pat.matches(c)) {
1442             None => "",
1443             Some(first) => unsafe { self.slice_unchecked(first, self.len()) }
1444         }
1445     }
1446
1447     #[inline]
1448     fn trim_right_matches<P: CharEq>(&self, mut pat: P) -> &str {
1449         match self.rfind(|&mut: c: char| !pat.matches(c)) {
1450             None => "",
1451             Some(last) => {
1452                 let next = self.char_range_at(last).next;
1453                 unsafe { self.slice_unchecked(0u, next) }
1454             }
1455         }
1456     }
1457
1458     #[inline]
1459     fn is_char_boundary(&self, index: uint) -> bool {
1460         if index == self.len() { return true; }
1461         match self.as_bytes().get(index) {
1462             None => false,
1463             Some(&b) => b < 128u8 || b >= 192u8,
1464         }
1465     }
1466
1467     #[inline]
1468     fn char_range_at(&self, i: uint) -> CharRange {
1469         if self.as_bytes()[i] < 128u8 {
1470             return CharRange {ch: self.as_bytes()[i] as char, next: i + 1 };
1471         }
1472
1473         // Multibyte case is a fn to allow char_range_at to inline cleanly
1474         fn multibyte_char_range_at(s: &str, i: uint) -> CharRange {
1475             let mut val = s.as_bytes()[i] as u32;
1476             let w = UTF8_CHAR_WIDTH[val as uint] as uint;
1477             assert!((w != 0));
1478
1479             val = utf8_first_byte!(val, w);
1480             val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 1]);
1481             if w > 2 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 2]); }
1482             if w > 3 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 3]); }
1483
1484             return CharRange {ch: unsafe { mem::transmute(val) }, next: i + w};
1485         }
1486
1487         return multibyte_char_range_at(self, i);
1488     }
1489
1490     #[inline]
1491     fn char_range_at_reverse(&self, start: uint) -> CharRange {
1492         let mut prev = start;
1493
1494         prev = prev.saturating_sub(1);
1495         if self.as_bytes()[prev] < 128 {
1496             return CharRange{ch: self.as_bytes()[prev] as char, next: prev}
1497         }
1498
1499         // Multibyte case is a fn to allow char_range_at_reverse to inline cleanly
1500         fn multibyte_char_range_at_reverse(s: &str, mut i: uint) -> CharRange {
1501             // while there is a previous byte == 10......
1502             while i > 0 && s.as_bytes()[i] & !CONT_MASK == TAG_CONT_U8 {
1503                 i -= 1u;
1504             }
1505
1506             let mut val = s.as_bytes()[i] as u32;
1507             let w = UTF8_CHAR_WIDTH[val as uint] as uint;
1508             assert!((w != 0));
1509
1510             val = utf8_first_byte!(val, w);
1511             val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 1]);
1512             if w > 2 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 2]); }
1513             if w > 3 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 3]); }
1514
1515             return CharRange {ch: unsafe { mem::transmute(val) }, next: i};
1516         }
1517
1518         return multibyte_char_range_at_reverse(self, prev);
1519     }
1520
1521     #[inline]
1522     fn char_at(&self, i: uint) -> char {
1523         self.char_range_at(i).ch
1524     }
1525
1526     #[inline]
1527     fn char_at_reverse(&self, i: uint) -> char {
1528         self.char_range_at_reverse(i).ch
1529     }
1530
1531     #[inline]
1532     fn as_bytes(&self) -> &[u8] {
1533         unsafe { mem::transmute(self) }
1534     }
1535
1536     fn find<P: CharEq>(&self, mut pat: P) -> Option<uint> {
1537         if pat.only_ascii() {
1538             self.bytes().position(|b| pat.matches(b as char))
1539         } else {
1540             for (index, c) in self.char_indices() {
1541                 if pat.matches(c) { return Some(index); }
1542             }
1543             None
1544         }
1545     }
1546
1547     fn rfind<P: CharEq>(&self, mut pat: P) -> Option<uint> {
1548         if pat.only_ascii() {
1549             self.bytes().rposition(|b| pat.matches(b as char))
1550         } else {
1551             for (index, c) in self.char_indices().rev() {
1552                 if pat.matches(c) { return Some(index); }
1553             }
1554             None
1555         }
1556     }
1557
1558     fn find_str(&self, needle: &str) -> Option<uint> {
1559         if needle.is_empty() {
1560             Some(0)
1561         } else {
1562             self.match_indices(needle)
1563                 .next()
1564                 .map(|(start, _end)| start)
1565         }
1566     }
1567
1568     #[inline]
1569     fn slice_shift_char(&self) -> Option<(char, &str)> {
1570         if self.is_empty() {
1571             None
1572         } else {
1573             let CharRange {ch, next} = self.char_range_at(0u);
1574             let next_s = unsafe { self.slice_unchecked(next, self.len()) };
1575             Some((ch, next_s))
1576         }
1577     }
1578
1579     fn subslice_offset(&self, inner: &str) -> uint {
1580         let a_start = self.as_ptr() as uint;
1581         let a_end = a_start + self.len();
1582         let b_start = inner.as_ptr() as uint;
1583         let b_end = b_start + inner.len();
1584
1585         assert!(a_start <= b_start);
1586         assert!(b_end <= a_end);
1587         b_start - a_start
1588     }
1589
1590     #[inline]
1591     fn as_ptr(&self) -> *const u8 {
1592         self.repr().data
1593     }
1594
1595     #[inline]
1596     fn len(&self) -> uint { self.repr().len }
1597
1598     #[inline]
1599     fn is_empty(&self) -> bool { self.len() == 0 }
1600
1601     #[inline]
1602     fn parse<T: FromStr>(&self) -> Option<T> { FromStr::from_str(self) }
1603 }
1604
1605 #[stable]
1606 impl<'a> Default for &'a str {
1607     #[stable]
1608     fn default() -> &'a str { "" }
1609 }
1610
1611 #[stable]
1612 impl<'a> Iterator for Lines<'a> {
1613     type Item = &'a str;
1614
1615     #[inline]
1616     fn next(&mut self) -> Option<&'a str> { self.inner.next() }
1617     #[inline]
1618     fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1619 }
1620
1621 #[stable]
1622 impl<'a> DoubleEndedIterator for Lines<'a> {
1623     #[inline]
1624     fn next_back(&mut self) -> Option<&'a str> { self.inner.next_back() }
1625 }
1626
1627 #[stable]
1628 impl<'a> Iterator for LinesAny<'a> {
1629     type Item = &'a str;
1630
1631     #[inline]
1632     fn next(&mut self) -> Option<&'a str> { self.inner.next() }
1633     #[inline]
1634     fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1635 }
1636
1637 #[stable]
1638 impl<'a> DoubleEndedIterator for LinesAny<'a> {
1639     #[inline]
1640     fn next_back(&mut self) -> Option<&'a str> { self.inner.next_back() }
1641 }