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.
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.
11 // ignore-lexer-test FIXME #15679
13 //! String manipulation
15 //! For more details, see std::str
17 #![doc(primitive = "str")]
19 use self::Searcher::{Naive, TwoWay, TwoWayLong};
24 use iter::{DoubleEndedIteratorExt, ExactSizeIterator};
25 use iter::{Map, Iterator, IteratorExt, DoubleEndedIterator};
30 use option::Option::{mod, None, Some};
32 use raw::{Repr, Slice};
33 use result::Result::{mod, Ok, Err};
34 use slice::{mod, SliceExt};
37 macro_rules! delegate_iter {
38 (exact $te:ty in $ti:ty) => {
39 delegate_iter!{$te in $ti}
40 impl<'a> ExactSizeIterator<$te> for $ti {
42 fn rposition<P>(&mut self, predicate: P) -> Option<uint> where P: FnMut($te) -> bool{
43 self.0.rposition(predicate)
46 fn len(&self) -> uint {
51 ($te:ty in $ti:ty) => {
52 impl<'a> Iterator<$te> for $ti {
54 fn next(&mut self) -> Option<$te> {
58 fn size_hint(&self) -> (uint, Option<uint>) {
62 impl<'a> DoubleEndedIterator<$te> for $ti {
64 fn next_back(&mut self) -> Option<$te> {
69 (pattern $te:ty in $ti:ty) => {
70 impl<'a, P: CharEq> Iterator<$te> for $ti {
72 fn next(&mut self) -> Option<$te> {
76 fn size_hint(&self) -> (uint, Option<uint>) {
80 impl<'a, P: CharEq> DoubleEndedIterator<$te> for $ti {
82 fn next_back(&mut self) -> Option<$te> {
87 (pattern forward $te:ty in $ti:ty) => {
88 impl<'a, P: CharEq> Iterator<$te> for $ti {
90 fn next(&mut self) -> Option<$te> {
94 fn size_hint(&self) -> (uint, Option<uint>) {
101 /// A trait to abstract the idea of creating a new instance of a type from a
103 // FIXME(#17307): there should be an `E` associated type for a `Result` return
104 #[unstable = "will return a Result once associated types are working"]
106 /// Parses a string `s` to return an optional value of this type. If the
107 /// string is ill-formatted, the None is returned.
108 fn from_str(s: &str) -> Option<Self>;
111 /// A utility function that just calls FromStr::from_str
112 #[deprecated = "call the .parse() method on the string instead"]
113 pub fn from_str<A: FromStr>(s: &str) -> Option<A> {
117 impl FromStr for bool {
118 /// Parse a `bool` from a string.
120 /// Yields an `Option<bool>`, because `s` may or may not actually be parseable.
125 /// assert_eq!("true".parse(), Some(true));
126 /// assert_eq!("false".parse(), Some(false));
127 /// assert_eq!("not even a boolean".parse::<bool>(), None);
130 fn from_str(s: &str) -> Option<bool> {
132 "true" => Some(true),
133 "false" => Some(false),
140 Section: Creating a string
143 /// Errors which can occur when attempting to interpret a byte slice as a `str`.
144 #[deriving(Copy, Eq, PartialEq, Clone)]
146 /// An invalid byte was detected at the byte offset given.
148 /// The offset is guaranteed to be in bounds of the slice in question, and
149 /// the byte at the specified offset was the first invalid byte in the
150 /// sequence detected.
153 /// The byte slice was invalid because more bytes were needed but no more
154 /// bytes were available.
158 /// Converts a slice of bytes to a string slice without performing any
161 /// Once the slice has been validated as utf-8, it is transmuted in-place and
162 /// returned as a '&str' instead of a '&[u8]'
166 /// Returns `Err` if the slice is not utf-8 with a description as to why the
167 /// provided slice is not utf-8.
168 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
169 try!(run_utf8_validation_iterator(&mut v.iter()));
170 Ok(unsafe { from_utf8_unchecked(v) })
173 /// Converts a slice of bytes to a string slice without checking
174 /// that the string contains valid UTF-8.
176 pub unsafe fn from_utf8_unchecked<'a>(v: &'a [u8]) -> &'a str {
180 /// Constructs a static string slice from a given raw pointer.
182 /// This function will read memory starting at `s` until it finds a 0, and then
183 /// transmute the memory up to that point as a string slice, returning the
184 /// corresponding `&'static str` value.
186 /// This function is unsafe because the caller must ensure the C string itself
187 /// has the static lifetime and that the memory `s` is valid up to and including
188 /// the first null byte.
192 /// This function will panic if the string pointed to by `s` is not valid UTF-8.
193 #[unstable = "may change location based on the outcome of the c_str module"]
194 pub unsafe fn from_c_str(s: *const i8) -> &'static str {
195 let s = s as *const u8;
197 while *s.offset(len as int) != 0 {
200 let v: &'static [u8] = ::mem::transmute(Slice { data: s, len: len });
201 from_utf8(v).ok().expect("from_c_str passed invalid utf-8 data")
204 /// Something that can be used to compare against a character
205 #[unstable = "definition may change as pattern-related methods are stabilized"]
207 /// Determine if the splitter should split at the given character
208 fn matches(&mut self, char) -> bool;
209 /// Indicate if this is only concerned about ASCII characters,
210 /// which can allow for a faster implementation.
211 fn only_ascii(&self) -> bool;
214 impl CharEq for char {
216 fn matches(&mut self, c: char) -> bool { *self == c }
219 fn only_ascii(&self) -> bool { (*self as uint) < 128 }
222 impl<F> CharEq for F where F: FnMut(char) -> bool {
224 fn matches(&mut self, c: char) -> bool { (*self)(c) }
227 fn only_ascii(&self) -> bool { false }
230 impl<'a> CharEq for &'a [char] {
232 fn matches(&mut self, c: char) -> bool {
233 self.iter().any(|&mut m| m.matches(c))
237 fn only_ascii(&self) -> bool {
238 self.iter().all(|m| m.only_ascii())
246 /// Iterator for the char (representing *Unicode Scalar Values*) of a string
248 /// Created with the method `.chars()`.
249 #[deriving(Clone, Copy)]
250 pub struct Chars<'a> {
251 iter: slice::Iter<'a, u8>
254 // Return the initial codepoint accumulator for the first byte.
255 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
256 // for width 3, and 3 bits for width 4
257 macro_rules! utf8_first_byte {
258 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
261 // return the value of $ch updated with continuation byte $byte
262 macro_rules! utf8_acc_cont_byte {
263 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & CONT_MASK) as u32)
266 macro_rules! utf8_is_cont_byte {
267 ($byte:expr) => (($byte & !CONT_MASK) == TAG_CONT_U8)
271 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
278 impl<'a> Iterator<char> for Chars<'a> {
280 fn next(&mut self) -> Option<char> {
281 // Decode UTF-8, using the valid UTF-8 invariant
282 let x = match self.iter.next() {
284 Some(&next_byte) if next_byte < 128 => return Some(next_byte as char),
285 Some(&next_byte) => next_byte,
288 // Multibyte case follows
289 // Decode from a byte combination out of: [[[x y] z] w]
290 // NOTE: Performance is sensitive to the exact formulation here
291 let init = utf8_first_byte!(x, 2);
292 let y = unwrap_or_0(self.iter.next());
293 let mut ch = utf8_acc_cont_byte!(init, y);
296 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
297 let z = unwrap_or_0(self.iter.next());
298 let y_z = utf8_acc_cont_byte!((y & CONT_MASK) as u32, z);
299 ch = init << 12 | y_z;
302 // use only the lower 3 bits of `init`
303 let w = unwrap_or_0(self.iter.next());
304 ch = (init & 7) << 18 | utf8_acc_cont_byte!(y_z, w);
308 // str invariant says `ch` is a valid Unicode Scalar Value
310 Some(mem::transmute(ch))
315 fn size_hint(&self) -> (uint, Option<uint>) {
316 let (len, _) = self.iter.size_hint();
317 (len.saturating_add(3) / 4, Some(len))
321 impl<'a> DoubleEndedIterator<char> for Chars<'a> {
323 fn next_back(&mut self) -> Option<char> {
324 let w = match self.iter.next_back() {
326 Some(&back_byte) if back_byte < 128 => return Some(back_byte as char),
327 Some(&back_byte) => back_byte,
330 // Multibyte case follows
331 // Decode from a byte combination out of: [x [y [z w]]]
333 let z = unwrap_or_0(self.iter.next_back());
334 ch = utf8_first_byte!(z, 2);
335 if utf8_is_cont_byte!(z) {
336 let y = unwrap_or_0(self.iter.next_back());
337 ch = utf8_first_byte!(y, 3);
338 if utf8_is_cont_byte!(y) {
339 let x = unwrap_or_0(self.iter.next_back());
340 ch = utf8_first_byte!(x, 4);
341 ch = utf8_acc_cont_byte!(ch, y);
343 ch = utf8_acc_cont_byte!(ch, z);
345 ch = utf8_acc_cont_byte!(ch, w);
347 // str invariant says `ch` is a valid Unicode Scalar Value
349 Some(mem::transmute(ch))
354 /// External iterator for a string's characters and their byte offsets.
355 /// Use with the `std::iter` module.
357 pub struct CharIndices<'a> {
362 impl<'a> Iterator<(uint, char)> for CharIndices<'a> {
364 fn next(&mut self) -> Option<(uint, char)> {
365 let (pre_len, _) = self.iter.iter.size_hint();
366 match self.iter.next() {
369 let index = self.front_offset;
370 let (len, _) = self.iter.iter.size_hint();
371 self.front_offset += pre_len - len;
378 fn size_hint(&self) -> (uint, Option<uint>) {
379 self.iter.size_hint()
383 impl<'a> DoubleEndedIterator<(uint, char)> for CharIndices<'a> {
385 fn next_back(&mut self) -> Option<(uint, char)> {
386 match self.iter.next_back() {
389 let (len, _) = self.iter.iter.size_hint();
390 let index = self.front_offset + len;
397 /// External iterator for a string's bytes.
398 /// Use with the `std::iter` module.
400 /// Created with `StrExt::bytes`
403 pub struct Bytes<'a>(Map<&'a u8, u8, slice::Iter<'a, u8>, BytesDeref>);
404 delegate_iter!{exact u8 in Bytes<'a>}
406 /// A temporary fn new type that ensures that the `Bytes` iterator
408 #[deriving(Copy, Clone)]
411 impl<'a> Fn(&'a u8) -> u8 for BytesDeref {
413 extern "rust-call" fn call(&self, (ptr,): (&'a u8,)) -> u8 {
418 /// An iterator over the substrings of a string, separated by `sep`.
420 #[deprecated = "Type is now named `Split` or `SplitTerminator`"]
421 pub struct CharSplits<'a, Sep> {
422 /// The slice remaining to be iterated
425 /// Whether an empty string at the end is allowed
426 allow_trailing_empty: bool,
431 /// An iterator over the substrings of a string, separated by `sep`,
432 /// splitting at most `count` times.
434 #[deprecated = "Type is now named `SplitN` or `RSplitN`"]
435 pub struct CharSplitsN<'a, Sep> {
436 iter: CharSplits<'a, Sep>,
437 /// The number of splits remaining
442 /// An iterator over the lines of a string, separated by `\n`.
444 pub struct Lines<'a> {
445 inner: CharSplits<'a, char>,
448 /// An iterator over the lines of a string, separated by either `\n` or (`\r\n`).
450 pub struct LinesAny<'a> {
451 inner: Map<&'a str, &'a str, Lines<'a>, fn(&str) -> &str>,
454 impl<'a, Sep> CharSplits<'a, Sep> {
456 fn get_end(&mut self) -> Option<&'a str> {
457 if !self.finished && (self.allow_trailing_empty || self.string.len() > 0) {
458 self.finished = true;
466 impl<'a, Sep: CharEq> Iterator<&'a str> for CharSplits<'a, Sep> {
468 fn next(&mut self) -> Option<&'a str> {
469 if self.finished { return None }
471 let mut next_split = None;
473 for (idx, byte) in self.string.bytes().enumerate() {
474 if self.sep.matches(byte as char) && byte < 128u8 {
475 next_split = Some((idx, idx + 1));
480 for (idx, ch) in self.string.char_indices() {
481 if self.sep.matches(ch) {
482 next_split = Some((idx, self.string.char_range_at(idx).next));
488 Some((a, b)) => unsafe {
489 let elt = self.string.slice_unchecked(0, a);
490 self.string = self.string.slice_unchecked(b, self.string.len());
493 None => self.get_end(),
498 impl<'a, Sep: CharEq> DoubleEndedIterator<&'a str>
499 for CharSplits<'a, Sep> {
501 fn next_back(&mut self) -> Option<&'a str> {
502 if self.finished { return None }
504 if !self.allow_trailing_empty {
505 self.allow_trailing_empty = true;
506 match self.next_back() {
507 Some(elt) if !elt.is_empty() => return Some(elt),
508 _ => if self.finished { return None }
511 let len = self.string.len();
512 let mut next_split = None;
515 for (idx, byte) in self.string.bytes().enumerate().rev() {
516 if self.sep.matches(byte as char) && byte < 128u8 {
517 next_split = Some((idx, idx + 1));
522 for (idx, ch) in self.string.char_indices().rev() {
523 if self.sep.matches(ch) {
524 next_split = Some((idx, self.string.char_range_at(idx).next));
530 Some((a, b)) => unsafe {
531 let elt = self.string.slice_unchecked(b, len);
532 self.string = self.string.slice_unchecked(0, a);
535 None => { self.finished = true; Some(self.string) }
540 impl<'a, Sep: CharEq> Iterator<&'a str> for CharSplitsN<'a, Sep> {
542 fn next(&mut self) -> Option<&'a str> {
545 if self.invert { self.iter.next_back() } else { self.iter.next() }
552 /// The internal state of an iterator that searches for matches of a substring
553 /// within a larger string using naive search
555 struct NaiveSearcher {
560 fn new() -> NaiveSearcher {
561 NaiveSearcher { position: 0 }
564 fn next(&mut self, haystack: &[u8], needle: &[u8]) -> Option<(uint, uint)> {
565 while self.position + needle.len() <= haystack.len() {
566 if haystack[self.position .. self.position + needle.len()] == needle {
567 let match_pos = self.position;
568 self.position += needle.len(); // add 1 for all matches
569 return Some((match_pos, match_pos + needle.len()));
578 /// The internal state of an iterator that searches for matches of a substring
579 /// within a larger string using two-way search
581 struct TwoWaySearcher {
593 This is the Two-Way search algorithm, which was introduced in the paper:
594 Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
596 Here's some background information.
598 A *word* is a string of symbols. The *length* of a word should be a familiar
599 notion, and here we denote it for any word x by |x|.
600 (We also allow for the possibility of the *empty word*, a word of length zero).
602 If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
603 *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
604 For example, both 1 and 2 are periods for the string "aa". As another example,
605 the only period of the string "abcd" is 4.
607 We denote by period(x) the *smallest* period of x (provided that x is non-empty).
608 This is always well-defined since every non-empty word x has at least one period,
609 |x|. We sometimes call this *the period* of x.
611 If u, v and x are words such that x = uv, where uv is the concatenation of u and
612 v, then we say that (u, v) is a *factorization* of x.
614 Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
615 that both of the following hold
617 - either w is a suffix of u or u is a suffix of w
618 - either w is a prefix of v or v is a prefix of w
620 then w is said to be a *repetition* for the factorization (u, v).
622 Just to unpack this, there are four possibilities here. Let w = "abc". Then we
625 - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
626 - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
627 - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
628 - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
630 Note that the word vu is a repetition for any factorization (u,v) of x = uv,
631 so every factorization has at least one repetition.
633 If x is a string and (u, v) is a factorization for x, then a *local period* for
634 (u, v) is an integer r such that there is some word w such that |w| = r and w is
635 a repetition for (u, v).
637 We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
638 call this *the local period* of (u, v). Provided that x = uv is non-empty, this
639 is well-defined (because each non-empty word has at least one factorization, as
642 It can be proven that the following is an equivalent definition of a local period
643 for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
644 all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
645 defined. (i.e. i > 0 and i + r < |x|).
647 Using the above reformulation, it is easy to prove that
649 1 <= local_period(u, v) <= period(uv)
651 A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
652 *critical factorization*.
654 The algorithm hinges on the following theorem, which is stated without proof:
656 **Critical Factorization Theorem** Any word x has at least one critical
657 factorization (u, v) such that |u| < period(x).
659 The purpose of maximal_suffix is to find such a critical factorization.
662 impl TwoWaySearcher {
663 fn new(needle: &[u8]) -> TwoWaySearcher {
664 let (crit_pos1, period1) = TwoWaySearcher::maximal_suffix(needle, false);
665 let (crit_pos2, period2) = TwoWaySearcher::maximal_suffix(needle, true);
669 if crit_pos1 > crit_pos2 {
670 crit_pos = crit_pos1;
673 crit_pos = crit_pos2;
677 // This isn't in the original algorithm, as far as I'm aware.
678 let byteset = needle.iter()
679 .fold(0, |a, &b| (1 << ((b & 0x3f) as uint)) | a);
681 // A particularly readable explanation of what's going on here can be found
682 // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
683 // see the code for "Algorithm CP" on p. 323.
685 // What's going on is we have some critical factorization (u, v) of the
686 // needle, and we want to determine whether u is a suffix of
687 // v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
688 // "Algorithm CP2", which is optimized for when the period of the needle
690 if needle[..crit_pos] == needle[period.. period + crit_pos] {
702 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
706 memory: uint::MAX // Dummy value to signify that the period is long
711 // One of the main ideas of Two-Way is that we factorize the needle into
712 // two halves, (u, v), and begin trying to find v in the haystack by scanning
713 // left to right. If v matches, we try to match u by scanning right to left.
714 // How far we can jump when we encounter a mismatch is all based on the fact
715 // that (u, v) is a critical factorization for the needle.
717 fn next(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> Option<(uint, uint)> {
719 // Check that we have room to search in
720 if self.position + needle.len() > haystack.len() {
724 // Quickly skip by large portions unrelated to our substring
726 ((haystack[self.position + needle.len() - 1] & 0x3f)
728 self.position += needle.len();
735 // See if the right part of the needle matches
736 let start = if long_period { self.crit_pos }
737 else { cmp::max(self.crit_pos, self.memory) };
738 for i in range(start, needle.len()) {
739 if needle[i] != haystack[self.position + i] {
740 self.position += i - self.crit_pos + 1;
748 // See if the left part of the needle matches
749 let start = if long_period { 0 } else { self.memory };
750 for i in range(start, self.crit_pos).rev() {
751 if needle[i] != haystack[self.position + i] {
752 self.position += self.period;
754 self.memory = needle.len() - self.period;
760 // We have found a match!
761 let match_pos = self.position;
762 self.position += needle.len(); // add self.period for all matches
764 self.memory = 0; // set to needle.len() - self.period for all matches
766 return Some((match_pos, match_pos + needle.len()));
770 // Computes a critical factorization (u, v) of `arr`.
771 // Specifically, returns (i, p), where i is the starting index of v in some
772 // critical factorization (u, v) and p = period(v)
774 fn maximal_suffix(arr: &[u8], reversed: bool) -> (uint, uint) {
775 let mut left = -1; // Corresponds to i in the paper
776 let mut right = 0; // Corresponds to j in the paper
777 let mut offset = 1; // Corresponds to k in the paper
778 let mut period = 1; // Corresponds to p in the paper
780 while right + offset < arr.len() {
784 a = arr[left + offset];
785 b = arr[right + offset];
787 a = arr[right + offset];
788 b = arr[left + offset];
791 // Suffix is smaller, period is entire prefix so far.
794 period = right - left;
796 // Advance through repetition of the current period.
797 if offset == period {
804 // Suffix is larger, start over from current location.
815 /// The internal state of an iterator that searches for matches of a substring
816 /// within a larger string using a dynamically chosen search algorithm
819 Naive(NaiveSearcher),
820 TwoWay(TwoWaySearcher),
821 TwoWayLong(TwoWaySearcher)
825 fn new(haystack: &[u8], needle: &[u8]) -> Searcher {
827 // FIXME(#16715): This unsigned integer addition will probably not
828 // overflow because that would mean that the memory almost solely
829 // consists of the needle. Needs #16715 to be formally fixed.
830 if needle.len() + 20 > haystack.len() {
831 Naive(NaiveSearcher::new())
833 let searcher = TwoWaySearcher::new(needle);
834 if searcher.memory == uint::MAX { // If the period is long
843 /// An iterator over the start and end indices of the matches of a
844 /// substring within a larger string
846 pub struct MatchIndices<'a> {
853 /// An iterator over the substrings of a string separated by a given
856 #[unstable = "Type might get removed"]
857 pub struct SplitStr<'a> {
858 it: MatchIndices<'a>,
864 #[deprecated = "Type is now named `SplitStr`"]
865 pub type StrSplits<'a> = SplitStr<'a>;
867 impl<'a> Iterator<(uint, uint)> for MatchIndices<'a> {
869 fn next(&mut self) -> Option<(uint, uint)> {
870 match self.searcher {
871 Naive(ref mut searcher)
872 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes()),
873 TwoWay(ref mut searcher)
874 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), false),
875 TwoWayLong(ref mut searcher)
876 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), true)
881 impl<'a> Iterator<&'a str> for SplitStr<'a> {
883 fn next(&mut self) -> Option<&'a str> {
884 if self.finished { return None; }
886 match self.it.next() {
887 Some((from, to)) => {
888 let ret = Some(self.it.haystack.slice(self.last_end, from));
893 self.finished = true;
894 Some(self.it.haystack.slice(self.last_end, self.it.haystack.len()))
902 Section: Comparing strings
905 // share the implementation of the lang-item vs. non-lang-item
907 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
908 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
910 fn eq_slice_(a: &str, b: &str) -> bool {
911 #[allow(improper_ctypes)]
912 extern { fn memcmp(s1: *const i8, s2: *const i8, n: uint) -> i32; }
913 a.len() == b.len() && unsafe {
914 memcmp(a.as_ptr() as *const i8,
915 b.as_ptr() as *const i8,
920 /// Bytewise slice equality
921 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
922 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
925 fn eq_slice(a: &str, b: &str) -> bool {
933 /// Walk through `iter` checking that it's a valid UTF-8 sequence,
934 /// returning `true` in that case, or, if it is invalid, `false` with
935 /// `iter` reset such that it is pointing at the first byte in the
936 /// invalid sequence.
938 fn run_utf8_validation_iterator(iter: &mut slice::Iter<u8>)
939 -> Result<(), Utf8Error> {
940 let whole = iter.as_slice();
942 // save the current thing we're pointing at.
945 // restore the iterator we had at the start of this codepoint.
946 macro_rules! err (() => { {
948 return Err(Utf8Error::InvalidByte(whole.len() - iter.as_slice().len()))
950 macro_rules! next ( () => {
953 // we needed data, but there was none: error!
954 None => return Err(Utf8Error::TooShort),
958 let first = match iter.next() {
960 // we're at the end of the iterator and a codepoint
961 // boundary at the same time, so this string is valid.
962 None => return Ok(())
965 // ASCII characters are always valid, so only large
966 // bytes need more examination.
968 let w = UTF8_CHAR_WIDTH[first as uint] as uint;
969 let second = next!();
970 // 2-byte encoding is for codepoints \u{0080} to \u{07ff}
971 // first C2 80 last DF BF
972 // 3-byte encoding is for codepoints \u{0800} to \u{ffff}
973 // first E0 A0 80 last EF BF BF
974 // excluding surrogates codepoints \u{d800} to \u{dfff}
975 // ED A0 80 to ED BF BF
976 // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
977 // first F0 90 80 80 last F4 8F BF BF
979 // Use the UTF-8 syntax from the RFC
981 // https://tools.ietf.org/html/rfc3629
983 // UTF8-2 = %xC2-DF UTF8-tail
984 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
985 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
986 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
987 // %xF4 %x80-8F 2( UTF8-tail )
989 2 => if second & !CONT_MASK != TAG_CONT_U8 {err!()},
991 match (first, second, next!() & !CONT_MASK) {
992 (0xE0 , 0xA0 ... 0xBF, TAG_CONT_U8) |
993 (0xE1 ... 0xEC, 0x80 ... 0xBF, TAG_CONT_U8) |
994 (0xED , 0x80 ... 0x9F, TAG_CONT_U8) |
995 (0xEE ... 0xEF, 0x80 ... 0xBF, TAG_CONT_U8) => {}
1000 match (first, second, next!() & !CONT_MASK, next!() & !CONT_MASK) {
1001 (0xF0 , 0x90 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
1002 (0xF1 ... 0xF3, 0x80 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
1003 (0xF4 , 0x80 ... 0x8F, TAG_CONT_U8, TAG_CONT_U8) => {}
1013 /// Determines if a vector of bytes contains valid UTF-8.
1014 #[deprecated = "call from_utf8 instead"]
1015 pub fn is_utf8(v: &[u8]) -> bool {
1016 run_utf8_validation_iterator(&mut v.iter()).is_ok()
1019 /// Deprecated function
1020 #[deprecated = "this function will be removed"]
1021 pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] {
1022 match v.iter().position(|c| *c == 0) {
1023 // don't include the 0
1029 // https://tools.ietf.org/html/rfc3629
1030 static UTF8_CHAR_WIDTH: [u8, ..256] = [
1031 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1032 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1033 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1034 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1035 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1036 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1037 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1038 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1039 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1040 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1041 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1042 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1043 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1044 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1045 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1046 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1049 /// Given a first byte, determine how many bytes are in this UTF-8 character
1051 #[deprecated = "this function has moved to libunicode"]
1052 pub fn utf8_char_width(b: u8) -> uint {
1053 return UTF8_CHAR_WIDTH[b as uint] as uint;
1056 /// Struct that contains a `char` and the index of the first byte of
1057 /// the next `char` in a string. This can be used as a data structure
1058 /// for iterating over the UTF-8 bytes of a string.
1060 #[unstable = "naming is uncertain with container conventions"]
1061 pub struct CharRange {
1064 /// Index of the first byte of the next `char`
1068 /// Mask of the value bits of a continuation byte
1069 const CONT_MASK: u8 = 0b0011_1111u8;
1070 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte
1071 const TAG_CONT_U8: u8 = 0b1000_0000u8;
1073 /// Unsafe operations
1078 use slice::SliceExt;
1081 /// Converts a slice of bytes to a string slice without checking
1082 /// that the string contains valid UTF-8.
1083 #[deprecated = "renamed to str::from_utf8_unchecked"]
1084 pub unsafe fn from_utf8<'a>(v: &'a [u8]) -> &'a str {
1085 super::from_utf8_unchecked(v)
1088 /// Form a slice from a C string. Unsafe because the caller must ensure the
1089 /// C string has the static lifetime, or else the return value may be
1090 /// invalidated later.
1091 #[deprecated = "renamed to str::from_c_str"]
1092 pub unsafe fn c_str_to_static_slice(s: *const i8) -> &'static str {
1093 let s = s as *const u8;
1096 while *curr != 0u8 {
1098 curr = s.offset(len as int);
1100 let v = Slice { data: s, len: len };
1101 super::from_utf8(::mem::transmute(v)).unwrap()
1104 /// Takes a bytewise (not UTF-8) slice from a string.
1106 /// Returns the substring from [`begin`..`end`).
1110 /// If begin is greater than end.
1111 /// If end is greater than the length of the string.
1113 #[deprecated = "call the slice_unchecked method instead"]
1114 pub unsafe fn slice_bytes<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
1115 assert!(begin <= end);
1116 assert!(end <= s.len());
1117 s.slice_unchecked(begin, end)
1120 /// Takes a bytewise (not UTF-8) slice from a string.
1122 /// Returns the substring from [`begin`..`end`).
1124 /// Caller must check slice boundaries!
1126 #[deprecated = "this has moved to a method on `str` directly"]
1127 pub unsafe fn slice_unchecked<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
1128 s.slice_unchecked(begin, end)
1133 Section: Trait implementations
1136 #[allow(missing_docs)]
1138 use cmp::{Ordering, Ord, PartialEq, PartialOrd, Equiv, Eq};
1139 use cmp::Ordering::{Less, Equal, Greater};
1140 use iter::IteratorExt;
1142 use option::Option::Some;
1144 use str::{Str, StrExt, eq_slice};
1148 fn cmp(&self, other: &str) -> Ordering {
1149 for (s_b, o_b) in self.bytes().zip(other.bytes()) {
1150 match s_b.cmp(&o_b) {
1151 Greater => return Greater,
1152 Less => return Less,
1157 self.len().cmp(&other.len())
1161 impl PartialEq for str {
1163 fn eq(&self, other: &str) -> bool {
1164 eq_slice(self, other)
1167 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1172 impl PartialOrd for str {
1174 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1175 Some(self.cmp(other))
1179 #[allow(deprecated)]
1180 #[deprecated = "Use overloaded `core::cmp::PartialEq`"]
1181 impl<S: Str> Equiv<S> for str {
1183 fn equiv(&self, other: &S) -> bool { eq_slice(self, other.as_slice()) }
1186 impl ops::Slice<uint, str> for str {
1188 fn as_slice_<'a>(&'a self) -> &'a str {
1193 fn slice_from_or_fail<'a>(&'a self, from: &uint) -> &'a str {
1194 self.slice_from(*from)
1198 fn slice_to_or_fail<'a>(&'a self, to: &uint) -> &'a str {
1203 fn slice_or_fail<'a>(&'a self, from: &uint, to: &uint) -> &'a str {
1204 self.slice(*from, *to)
1209 /// Any string that can be represented as a slice
1210 #[unstable = "Instead of taking this bound generically, this trait will be \
1211 replaced with one of slicing syntax, deref coercions, or \
1212 a more generic conversion trait"]
1213 pub trait Str for Sized? {
1214 /// Work with `self` as a slice.
1215 fn as_slice<'a>(&'a self) -> &'a str;
1218 #[allow(deprecated)]
1221 fn as_slice<'a>(&'a self) -> &'a str { self }
1224 #[allow(deprecated)]
1225 impl<'a, Sized? S> Str for &'a S where S: Str {
1227 fn as_slice(&self) -> &str { Str::as_slice(*self) }
1230 /// Return type of `StrExt::split`
1233 pub struct Split<'a, P>(CharSplits<'a, P>);
1234 delegate_iter!{pattern &'a str in Split<'a, P>}
1236 /// Return type of `StrExt::split_terminator`
1238 #[unstable = "might get removed in favour of a constructor method on Split"]
1239 pub struct SplitTerminator<'a, P>(CharSplits<'a, P>);
1240 delegate_iter!{pattern &'a str in SplitTerminator<'a, P>}
1242 /// Return type of `StrExt::splitn`
1245 pub struct SplitN<'a, P>(CharSplitsN<'a, P>);
1246 delegate_iter!{pattern forward &'a str in SplitN<'a, P>}
1248 /// Return type of `StrExt::rsplitn`
1251 pub struct RSplitN<'a, P>(CharSplitsN<'a, P>);
1252 delegate_iter!{pattern forward &'a str in RSplitN<'a, P>}
1254 /// Methods for string slices
1255 #[allow(missing_docs)]
1256 pub trait StrExt for Sized? {
1257 // NB there are no docs here are they're all located on the StrExt trait in
1258 // libcollections, not here.
1260 fn contains(&self, pat: &str) -> bool;
1261 fn contains_char<P: CharEq>(&self, pat: P) -> bool;
1262 fn chars<'a>(&'a self) -> Chars<'a>;
1263 fn bytes<'a>(&'a self) -> Bytes<'a>;
1264 fn char_indices<'a>(&'a self) -> CharIndices<'a>;
1265 fn split<'a, P: CharEq>(&'a self, pat: P) -> Split<'a, P>;
1266 fn splitn<'a, P: CharEq>(&'a self, count: uint, pat: P) -> SplitN<'a, P>;
1267 fn split_terminator<'a, P: CharEq>(&'a self, pat: P) -> SplitTerminator<'a, P>;
1268 fn rsplitn<'a, P: CharEq>(&'a self, count: uint, pat: P) -> RSplitN<'a, P>;
1269 fn match_indices<'a>(&'a self, sep: &'a str) -> MatchIndices<'a>;
1270 fn split_str<'a>(&'a self, pat: &'a str) -> SplitStr<'a>;
1271 fn lines<'a>(&'a self) -> Lines<'a>;
1272 fn lines_any<'a>(&'a self) -> LinesAny<'a>;
1273 fn char_len(&self) -> uint;
1274 fn slice<'a>(&'a self, begin: uint, end: uint) -> &'a str;
1275 fn slice_from<'a>(&'a self, begin: uint) -> &'a str;
1276 fn slice_to<'a>(&'a self, end: uint) -> &'a str;
1277 fn slice_chars<'a>(&'a self, begin: uint, end: uint) -> &'a str;
1278 unsafe fn slice_unchecked<'a>(&'a self, begin: uint, end: uint) -> &'a str;
1279 fn starts_with(&self, pat: &str) -> bool;
1280 fn ends_with(&self, pat: &str) -> bool;
1281 fn trim_matches<'a, P: CharEq>(&'a self, pat: P) -> &'a str;
1282 fn trim_left_matches<'a, P: CharEq>(&'a self, pat: P) -> &'a str;
1283 fn trim_right_matches<'a, P: CharEq>(&'a self, pat: P) -> &'a str;
1284 fn is_char_boundary(&self, index: uint) -> bool;
1285 fn char_range_at(&self, start: uint) -> CharRange;
1286 fn char_range_at_reverse(&self, start: uint) -> CharRange;
1287 fn char_at(&self, i: uint) -> char;
1288 fn char_at_reverse(&self, i: uint) -> char;
1289 fn as_bytes<'a>(&'a self) -> &'a [u8];
1290 fn find<P: CharEq>(&self, pat: P) -> Option<uint>;
1291 fn rfind<P: CharEq>(&self, pat: P) -> Option<uint>;
1292 fn find_str(&self, pat: &str) -> Option<uint>;
1293 fn slice_shift_char<'a>(&'a self) -> Option<(char, &'a str)>;
1294 fn subslice_offset(&self, inner: &str) -> uint;
1295 fn as_ptr(&self) -> *const u8;
1296 fn len(&self) -> uint;
1297 fn is_empty(&self) -> bool;
1301 fn slice_error_fail(s: &str, begin: uint, end: uint) -> ! {
1302 assert!(begin <= end);
1303 panic!("index {} and/or {} in `{}` do not lie on character boundary",
1307 impl StrExt for str {
1309 fn contains(&self, needle: &str) -> bool {
1310 self.find_str(needle).is_some()
1314 fn contains_char<P: CharEq>(&self, pat: P) -> bool {
1315 self.find(pat).is_some()
1319 fn chars(&self) -> Chars {
1320 Chars{iter: self.as_bytes().iter()}
1324 fn bytes(&self) -> Bytes {
1325 Bytes(self.as_bytes().iter().map(BytesDeref))
1329 fn char_indices(&self) -> CharIndices {
1330 CharIndices { front_offset: 0, iter: self.chars() }
1334 #[allow(deprecated)] // For using CharSplits
1335 fn split<P: CharEq>(&self, pat: P) -> Split<P> {
1338 only_ascii: pat.only_ascii(),
1340 allow_trailing_empty: true,
1346 #[allow(deprecated)] // For using CharSplitsN
1347 fn splitn<P: CharEq>(&self, count: uint, pat: P) -> SplitN<P> {
1348 SplitN(CharSplitsN {
1349 iter: self.split(pat).0,
1356 #[allow(deprecated)] // For using CharSplits
1357 fn split_terminator<P: CharEq>(&self, pat: P) -> SplitTerminator<P> {
1358 SplitTerminator(CharSplits {
1359 allow_trailing_empty: false,
1365 #[allow(deprecated)] // For using CharSplitsN
1366 fn rsplitn<P: CharEq>(&self, count: uint, pat: P) -> RSplitN<P> {
1367 RSplitN(CharSplitsN {
1368 iter: self.split(pat).0,
1375 fn match_indices<'a>(&'a self, sep: &'a str) -> MatchIndices<'a> {
1376 assert!(!sep.is_empty());
1380 searcher: Searcher::new(self.as_bytes(), sep.as_bytes())
1385 fn split_str<'a>(&'a self, sep: &'a str) -> SplitStr<'a> {
1387 it: self.match_indices(sep),
1394 fn lines(&self) -> Lines {
1395 Lines { inner: self.split_terminator('\n').0 }
1398 fn lines_any(&self) -> LinesAny {
1399 fn f(line: &str) -> &str {
1401 if l > 0 && line.as_bytes()[l - 1] == b'\r' { line.slice(0, l - 1) }
1405 let f: fn(&str) -> &str = f; // coerce to fn pointer
1406 LinesAny { inner: self.lines().map(f) }
1410 fn char_len(&self) -> uint { self.chars().count() }
1413 fn slice(&self, begin: uint, end: uint) -> &str {
1414 // is_char_boundary checks that the index is in [0, .len()]
1416 self.is_char_boundary(begin) &&
1417 self.is_char_boundary(end) {
1418 unsafe { self.slice_unchecked(begin, end) }
1420 slice_error_fail(self, begin, end)
1425 fn slice_from(&self, begin: uint) -> &str {
1426 // is_char_boundary checks that the index is in [0, .len()]
1427 if self.is_char_boundary(begin) {
1428 unsafe { self.slice_unchecked(begin, self.len()) }
1430 slice_error_fail(self, begin, self.len())
1435 fn slice_to(&self, end: uint) -> &str {
1436 // is_char_boundary checks that the index is in [0, .len()]
1437 if self.is_char_boundary(end) {
1438 unsafe { self.slice_unchecked(0, end) }
1440 slice_error_fail(self, 0, end)
1444 fn slice_chars(&self, begin: uint, end: uint) -> &str {
1445 assert!(begin <= end);
1447 let mut begin_byte = None;
1448 let mut end_byte = None;
1450 // This could be even more efficient by not decoding,
1451 // only finding the char boundaries
1452 for (idx, _) in self.char_indices() {
1453 if count == begin { begin_byte = Some(idx); }
1454 if count == end { end_byte = Some(idx); break; }
1457 if begin_byte.is_none() && count == begin { begin_byte = Some(self.len()) }
1458 if end_byte.is_none() && count == end { end_byte = Some(self.len()) }
1460 match (begin_byte, end_byte) {
1461 (None, _) => panic!("slice_chars: `begin` is beyond end of string"),
1462 (_, None) => panic!("slice_chars: `end` is beyond end of string"),
1463 (Some(a), Some(b)) => unsafe { self.slice_unchecked(a, b) }
1468 unsafe fn slice_unchecked(&self, begin: uint, end: uint) -> &str {
1469 mem::transmute(Slice {
1470 data: self.as_ptr().offset(begin as int),
1476 fn starts_with(&self, needle: &str) -> bool {
1477 let n = needle.len();
1478 self.len() >= n && needle.as_bytes() == self.as_bytes()[..n]
1482 fn ends_with(&self, needle: &str) -> bool {
1483 let (m, n) = (self.len(), needle.len());
1484 m >= n && needle.as_bytes() == self.as_bytes()[m-n..]
1488 fn trim_matches<P: CharEq>(&self, mut pat: P) -> &str {
1489 let cur = match self.find(|&mut: c: char| !pat.matches(c)) {
1491 Some(i) => unsafe { self.slice_unchecked(i, self.len()) }
1493 match cur.rfind(|&mut: c: char| !pat.matches(c)) {
1496 let right = cur.char_range_at(i).next;
1497 unsafe { cur.slice_unchecked(0, right) }
1503 fn trim_left_matches<P: CharEq>(&self, mut pat: P) -> &str {
1504 match self.find(|&mut: c: char| !pat.matches(c)) {
1506 Some(first) => unsafe { self.slice_unchecked(first, self.len()) }
1511 fn trim_right_matches<P: CharEq>(&self, mut pat: P) -> &str {
1512 match self.rfind(|&mut: c: char| !pat.matches(c)) {
1515 let next = self.char_range_at(last).next;
1516 unsafe { self.slice_unchecked(0u, next) }
1522 fn is_char_boundary(&self, index: uint) -> bool {
1523 if index == self.len() { return true; }
1524 match self.as_bytes().get(index) {
1526 Some(&b) => b < 128u8 || b >= 192u8,
1531 fn char_range_at(&self, i: uint) -> CharRange {
1532 if self.as_bytes()[i] < 128u8 {
1533 return CharRange {ch: self.as_bytes()[i] as char, next: i + 1 };
1536 // Multibyte case is a fn to allow char_range_at to inline cleanly
1537 fn multibyte_char_range_at(s: &str, i: uint) -> CharRange {
1538 let mut val = s.as_bytes()[i] as u32;
1539 let w = UTF8_CHAR_WIDTH[val as uint] as uint;
1542 val = utf8_first_byte!(val, w);
1543 val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 1]);
1544 if w > 2 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 2]); }
1545 if w > 3 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 3]); }
1547 return CharRange {ch: unsafe { mem::transmute(val) }, next: i + w};
1550 return multibyte_char_range_at(self, i);
1554 fn char_range_at_reverse(&self, start: uint) -> CharRange {
1555 let mut prev = start;
1557 prev = prev.saturating_sub(1);
1558 if self.as_bytes()[prev] < 128 {
1559 return CharRange{ch: self.as_bytes()[prev] as char, next: prev}
1562 // Multibyte case is a fn to allow char_range_at_reverse to inline cleanly
1563 fn multibyte_char_range_at_reverse(s: &str, mut i: uint) -> CharRange {
1564 // while there is a previous byte == 10......
1565 while i > 0 && s.as_bytes()[i] & !CONT_MASK == TAG_CONT_U8 {
1569 let mut val = s.as_bytes()[i] as u32;
1570 let w = UTF8_CHAR_WIDTH[val as uint] as uint;
1573 val = utf8_first_byte!(val, w);
1574 val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 1]);
1575 if w > 2 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 2]); }
1576 if w > 3 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 3]); }
1578 return CharRange {ch: unsafe { mem::transmute(val) }, next: i};
1581 return multibyte_char_range_at_reverse(self, prev);
1585 fn char_at(&self, i: uint) -> char {
1586 self.char_range_at(i).ch
1590 fn char_at_reverse(&self, i: uint) -> char {
1591 self.char_range_at_reverse(i).ch
1595 fn as_bytes(&self) -> &[u8] {
1596 unsafe { mem::transmute(self) }
1599 fn find<P: CharEq>(&self, mut pat: P) -> Option<uint> {
1600 if pat.only_ascii() {
1601 self.bytes().position(|b| pat.matches(b as char))
1603 for (index, c) in self.char_indices() {
1604 if pat.matches(c) { return Some(index); }
1610 fn rfind<P: CharEq>(&self, mut pat: P) -> Option<uint> {
1611 if pat.only_ascii() {
1612 self.bytes().rposition(|b| pat.matches(b as char))
1614 for (index, c) in self.char_indices().rev() {
1615 if pat.matches(c) { return Some(index); }
1621 fn find_str(&self, needle: &str) -> Option<uint> {
1622 if needle.is_empty() {
1625 self.match_indices(needle)
1627 .map(|(start, _end)| start)
1632 fn slice_shift_char(&self) -> Option<(char, &str)> {
1633 if self.is_empty() {
1636 let CharRange {ch, next} = self.char_range_at(0u);
1637 let next_s = unsafe { self.slice_unchecked(next, self.len()) };
1642 fn subslice_offset(&self, inner: &str) -> uint {
1643 let a_start = self.as_ptr() as uint;
1644 let a_end = a_start + self.len();
1645 let b_start = inner.as_ptr() as uint;
1646 let b_end = b_start + inner.len();
1648 assert!(a_start <= b_start);
1649 assert!(b_end <= a_end);
1654 fn as_ptr(&self) -> *const u8 {
1659 fn len(&self) -> uint { self.repr().len }
1662 fn is_empty(&self) -> bool { self.len() == 0 }
1666 impl<'a> Default for &'a str {
1668 fn default() -> &'a str { "" }
1671 impl<'a> Iterator<&'a str> for Lines<'a> {
1673 fn next(&mut self) -> Option<&'a str> { self.inner.next() }
1675 fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1677 impl<'a> DoubleEndedIterator<&'a str> for Lines<'a> {
1679 fn next_back(&mut self) -> Option<&'a str> { self.inner.next_back() }
1681 impl<'a> Iterator<&'a str> for LinesAny<'a> {
1683 fn next(&mut self) -> Option<&'a str> { self.inner.next() }
1685 fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1687 impl<'a> DoubleEndedIterator<&'a str> for LinesAny<'a> {
1689 fn next_back(&mut self) -> Option<&'a str> { self.inner.next_back() }