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