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