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