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 pub use self::Utf16Item::*;
20 pub use self::Searcher::{Naive, TwoWay, TwoWayLong};
26 use iter::{Map, Iterator, IteratorExt, DoubleEndedIterator};
27 use iter::{DoubleEndedIteratorExt, ExactSizeIterator};
32 use option::{Option, None, Some};
34 use raw::{Repr, Slice};
35 use slice::{mod, SlicePrelude};
38 /// A trait to abstract the idea of creating a new instance of a type from a
40 #[experimental = "might need to return Result"]
42 /// Parses a string `s` to return an optional value of this type. If the
43 /// string is ill-formatted, the None is returned.
44 fn from_str(s: &str) -> Option<Self>;
47 /// A utility function that just calls FromStr::from_str
48 pub fn from_str<A: FromStr>(s: &str) -> Option<A> {
52 impl FromStr for bool {
53 /// Parse a `bool` from a string.
55 /// Yields an `Option<bool>`, because `s` may or may not actually be parseable.
60 /// assert_eq!(from_str::<bool>("true"), Some(true));
61 /// assert_eq!(from_str::<bool>("false"), Some(false));
62 /// assert_eq!(from_str::<bool>("not even a boolean"), None);
65 fn from_str(s: &str) -> Option<bool> {
68 "false" => Some(false),
75 Section: Creating a string
78 /// Converts a vector to a string slice without performing any allocations.
80 /// Once the slice has been validated as utf-8, it is transmuted in-place and
81 /// returned as a '&str' instead of a '&[u8]'
83 /// Returns None if the slice is not utf-8.
84 pub fn from_utf8<'a>(v: &'a [u8]) -> Option<&'a str> {
86 Some(unsafe { from_utf8_unchecked(v) })
92 /// Converts a slice of bytes to a string slice without checking
93 /// that the string contains valid UTF-8.
94 pub unsafe fn from_utf8_unchecked<'a>(v: &'a [u8]) -> &'a str {
98 /// Constructs a static string slice from a given raw pointer.
100 /// This function will read memory starting at `s` until it finds a 0, and then
101 /// transmute the memory up to that point as a string slice, returning the
102 /// corresponding `&'static str` value.
104 /// This function is unsafe because the caller must ensure the C string itself
105 /// has the static lifetime and that the memory `s` is valid up to and including
106 /// the first null byte.
110 /// This function will panic if the string pointed to by `s` is not valid UTF-8.
111 pub unsafe fn from_c_str(s: *const i8) -> &'static str {
112 let s = s as *const u8;
114 while *s.offset(len as int) != 0 {
117 let v: &'static [u8] = ::mem::transmute(Slice { data: s, len: len });
118 from_utf8(v).expect("from_c_str passed invalid utf-8 data")
121 /// Something that can be used to compare against a character
123 /// Determine if the splitter should split at the given character
124 fn matches(&mut self, char) -> bool;
125 /// Indicate if this is only concerned about ASCII characters,
126 /// which can allow for a faster implementation.
127 fn only_ascii(&self) -> bool;
130 impl CharEq for char {
132 fn matches(&mut self, c: char) -> bool { *self == c }
135 fn only_ascii(&self) -> bool { (*self as uint) < 128 }
138 impl<'a> CharEq for |char|: 'a -> bool {
140 fn matches(&mut self, c: char) -> bool { (*self)(c) }
143 fn only_ascii(&self) -> bool { false }
146 impl CharEq for extern "Rust" fn(char) -> bool {
148 fn matches(&mut self, c: char) -> bool { (*self)(c) }
151 fn only_ascii(&self) -> bool { false }
154 impl<'a> CharEq for &'a [char] {
156 fn matches(&mut self, c: char) -> bool {
157 self.iter().any(|&mut m| m.matches(c))
161 fn only_ascii(&self) -> bool {
162 self.iter().all(|m| m.only_ascii())
170 /// Iterator for the char (representing *Unicode Scalar Values*) of a string
172 /// Created with the method `.chars()`.
174 pub struct Chars<'a> {
175 iter: slice::Items<'a, u8>
178 // Return the initial codepoint accumulator for the first byte.
179 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
180 // for width 3, and 3 bits for width 4
181 macro_rules! utf8_first_byte(
182 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
185 // return the value of $ch updated with continuation byte $byte
186 macro_rules! utf8_acc_cont_byte(
187 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & CONT_MASK) as u32)
190 macro_rules! utf8_is_cont_byte(
191 ($byte:expr) => (($byte & !CONT_MASK) == TAG_CONT_U8)
195 fn unwrap_or_0(opt: Option<&u8>) -> u8 {
202 impl<'a> Iterator<char> for Chars<'a> {
204 fn next(&mut self) -> Option<char> {
205 // Decode UTF-8, using the valid UTF-8 invariant
206 let x = match self.iter.next() {
208 Some(&next_byte) if next_byte < 128 => return Some(next_byte as char),
209 Some(&next_byte) => next_byte,
212 // Multibyte case follows
213 // Decode from a byte combination out of: [[[x y] z] w]
214 // NOTE: Performance is sensitive to the exact formulation here
215 let init = utf8_first_byte!(x, 2);
216 let y = unwrap_or_0(self.iter.next());
217 let mut ch = utf8_acc_cont_byte!(init, y);
220 // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
221 let z = unwrap_or_0(self.iter.next());
222 let y_z = utf8_acc_cont_byte!((y & CONT_MASK) as u32, z);
223 ch = init << 12 | y_z;
226 // use only the lower 3 bits of `init`
227 let w = unwrap_or_0(self.iter.next());
228 ch = (init & 7) << 18 | utf8_acc_cont_byte!(y_z, w);
232 // str invariant says `ch` is a valid Unicode Scalar Value
234 Some(mem::transmute(ch))
239 fn size_hint(&self) -> (uint, Option<uint>) {
240 let (len, _) = self.iter.size_hint();
241 (len.saturating_add(3) / 4, Some(len))
245 impl<'a> DoubleEndedIterator<char> for Chars<'a> {
247 fn next_back(&mut self) -> Option<char> {
248 let w = match self.iter.next_back() {
250 Some(&back_byte) if back_byte < 128 => return Some(back_byte as char),
251 Some(&back_byte) => back_byte,
254 // Multibyte case follows
255 // Decode from a byte combination out of: [x [y [z w]]]
257 let z = unwrap_or_0(self.iter.next_back());
258 ch = utf8_first_byte!(z, 2);
259 if utf8_is_cont_byte!(z) {
260 let y = unwrap_or_0(self.iter.next_back());
261 ch = utf8_first_byte!(y, 3);
262 if utf8_is_cont_byte!(y) {
263 let x = unwrap_or_0(self.iter.next_back());
264 ch = utf8_first_byte!(x, 4);
265 ch = utf8_acc_cont_byte!(ch, y);
267 ch = utf8_acc_cont_byte!(ch, z);
269 ch = utf8_acc_cont_byte!(ch, w);
271 // str invariant says `ch` is a valid Unicode Scalar Value
273 Some(mem::transmute(ch))
278 /// External iterator for a string's characters and their byte offsets.
279 /// Use with the `std::iter` module.
281 pub struct CharOffsets<'a> {
286 impl<'a> Iterator<(uint, char)> for CharOffsets<'a> {
288 fn next(&mut self) -> Option<(uint, char)> {
289 let (pre_len, _) = self.iter.iter.size_hint();
290 match self.iter.next() {
293 let index = self.front_offset;
294 let (len, _) = self.iter.iter.size_hint();
295 self.front_offset += pre_len - len;
302 fn size_hint(&self) -> (uint, Option<uint>) {
303 self.iter.size_hint()
307 impl<'a> DoubleEndedIterator<(uint, char)> for CharOffsets<'a> {
309 fn next_back(&mut self) -> Option<(uint, char)> {
310 match self.iter.next_back() {
313 let (len, _) = self.iter.iter.size_hint();
314 let index = self.front_offset + len;
321 /// External iterator for a string's bytes.
322 /// Use with the `std::iter` module.
324 Map<'a, &'a u8, u8, slice::Items<'a, u8>>;
326 /// An iterator over the substrings of a string, separated by `sep`.
328 pub struct CharSplits<'a, Sep> {
329 /// The slice remaining to be iterated
332 /// Whether an empty string at the end is allowed
333 allow_trailing_empty: bool,
338 /// An iterator over the substrings of a string, separated by `sep`,
339 /// splitting at most `count` times.
341 pub struct CharSplitsN<'a, Sep> {
342 iter: CharSplits<'a, Sep>,
343 /// The number of splits remaining
348 /// An iterator over the lines of a string, separated by either `\n` or (`\r\n`).
349 pub type AnyLines<'a> =
350 Map<'a, &'a str, &'a str, CharSplits<'a, char>>;
352 impl<'a, Sep> CharSplits<'a, Sep> {
354 fn get_end(&mut self) -> Option<&'a str> {
355 if !self.finished && (self.allow_trailing_empty || self.string.len() > 0) {
356 self.finished = true;
364 impl<'a, Sep: CharEq> Iterator<&'a str> for CharSplits<'a, Sep> {
366 fn next(&mut self) -> Option<&'a str> {
367 if self.finished { return None }
369 let mut next_split = None;
371 for (idx, byte) in self.string.bytes().enumerate() {
372 if self.sep.matches(byte as char) && byte < 128u8 {
373 next_split = Some((idx, idx + 1));
378 for (idx, ch) in self.string.char_indices() {
379 if self.sep.matches(ch) {
380 next_split = Some((idx, self.string.char_range_at(idx).next));
386 Some((a, b)) => unsafe {
387 let elt = self.string.slice_unchecked(0, a);
388 self.string = self.string.slice_unchecked(b, self.string.len());
391 None => self.get_end(),
396 impl<'a, Sep: CharEq> DoubleEndedIterator<&'a str>
397 for CharSplits<'a, Sep> {
399 fn next_back(&mut self) -> Option<&'a str> {
400 if self.finished { return None }
402 if !self.allow_trailing_empty {
403 self.allow_trailing_empty = true;
404 match self.next_back() {
405 Some(elt) if !elt.is_empty() => return Some(elt),
406 _ => if self.finished { return None }
409 let len = self.string.len();
410 let mut next_split = None;
413 for (idx, byte) in self.string.bytes().enumerate().rev() {
414 if self.sep.matches(byte as char) && byte < 128u8 {
415 next_split = Some((idx, idx + 1));
420 for (idx, ch) in self.string.char_indices().rev() {
421 if self.sep.matches(ch) {
422 next_split = Some((idx, self.string.char_range_at(idx).next));
428 Some((a, b)) => unsafe {
429 let elt = self.string.slice_unchecked(b, len);
430 self.string = self.string.slice_unchecked(0, a);
433 None => { self.finished = true; Some(self.string) }
438 impl<'a, Sep: CharEq> Iterator<&'a str> for CharSplitsN<'a, Sep> {
440 fn next(&mut self) -> Option<&'a str> {
443 if self.invert { self.iter.next_back() } else { self.iter.next() }
450 /// The internal state of an iterator that searches for matches of a substring
451 /// within a larger string using naive search
453 struct NaiveSearcher {
458 fn new() -> NaiveSearcher {
459 NaiveSearcher { position: 0 }
462 fn next(&mut self, haystack: &[u8], needle: &[u8]) -> Option<(uint, uint)> {
463 while self.position + needle.len() <= haystack.len() {
464 if haystack[self.position .. self.position + needle.len()] == needle {
465 let match_pos = self.position;
466 self.position += needle.len(); // add 1 for all matches
467 return Some((match_pos, match_pos + needle.len()));
476 /// The internal state of an iterator that searches for matches of a substring
477 /// within a larger string using two-way search
479 struct TwoWaySearcher {
491 This is the Two-Way search algorithm, which was introduced in the paper:
492 Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.
494 Here's some background information.
496 A *word* is a string of symbols. The *length* of a word should be a familiar
497 notion, and here we denote it for any word x by |x|.
498 (We also allow for the possibility of the *empty word*, a word of length zero).
500 If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
501 *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
502 For example, both 1 and 2 are periods for the string "aa". As another example,
503 the only period of the string "abcd" is 4.
505 We denote by period(x) the *smallest* period of x (provided that x is non-empty).
506 This is always well-defined since every non-empty word x has at least one period,
507 |x|. We sometimes call this *the period* of x.
509 If u, v and x are words such that x = uv, where uv is the concatenation of u and
510 v, then we say that (u, v) is a *factorization* of x.
512 Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
513 that both of the following hold
515 - either w is a suffix of u or u is a suffix of w
516 - either w is a prefix of v or v is a prefix of w
518 then w is said to be a *repetition* for the factorization (u, v).
520 Just to unpack this, there are four possibilities here. Let w = "abc". Then we
523 - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
524 - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
525 - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
526 - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")
528 Note that the word vu is a repetition for any factorization (u,v) of x = uv,
529 so every factorization has at least one repetition.
531 If x is a string and (u, v) is a factorization for x, then a *local period* for
532 (u, v) is an integer r such that there is some word w such that |w| = r and w is
533 a repetition for (u, v).
535 We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
536 call this *the local period* of (u, v). Provided that x = uv is non-empty, this
537 is well-defined (because each non-empty word has at least one factorization, as
540 It can be proven that the following is an equivalent definition of a local period
541 for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
542 all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
543 defined. (i.e. i > 0 and i + r < |x|).
545 Using the above reformulation, it is easy to prove that
547 1 <= local_period(u, v) <= period(uv)
549 A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
550 *critical factorization*.
552 The algorithm hinges on the following theorem, which is stated without proof:
554 **Critical Factorization Theorem** Any word x has at least one critical
555 factorization (u, v) such that |u| < period(x).
557 The purpose of maximal_suffix is to find such a critical factorization.
560 impl TwoWaySearcher {
561 fn new(needle: &[u8]) -> TwoWaySearcher {
562 let (crit_pos1, period1) = TwoWaySearcher::maximal_suffix(needle, false);
563 let (crit_pos2, period2) = TwoWaySearcher::maximal_suffix(needle, true);
567 if crit_pos1 > crit_pos2 {
568 crit_pos = crit_pos1;
571 crit_pos = crit_pos2;
575 // This isn't in the original algorithm, as far as I'm aware.
576 let byteset = needle.iter()
577 .fold(0, |a, &b| (1 << ((b & 0x3f) as uint)) | a);
579 // A particularly readable explanation of what's going on here can be found
580 // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
581 // see the code for "Algorithm CP" on p. 323.
583 // What's going on is we have some critical factorization (u, v) of the
584 // needle, and we want to determine whether u is a suffix of
585 // v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
586 // "Algorithm CP2", which is optimized for when the period of the needle
588 if needle[..crit_pos] == needle[period.. period + crit_pos] {
600 period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
604 memory: uint::MAX // Dummy value to signify that the period is long
609 // One of the main ideas of Two-Way is that we factorize the needle into
610 // two halves, (u, v), and begin trying to find v in the haystack by scanning
611 // left to right. If v matches, we try to match u by scanning right to left.
612 // How far we can jump when we encounter a mismatch is all based on the fact
613 // that (u, v) is a critical factorization for the needle.
615 fn next(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> Option<(uint, uint)> {
617 // Check that we have room to search in
618 if self.position + needle.len() > haystack.len() {
622 // Quickly skip by large portions unrelated to our substring
624 ((haystack[self.position + needle.len() - 1] & 0x3f)
626 self.position += needle.len();
633 // See if the right part of the needle matches
634 let start = if long_period { self.crit_pos }
635 else { cmp::max(self.crit_pos, self.memory) };
636 for i in range(start, needle.len()) {
637 if needle[i] != haystack[self.position + i] {
638 self.position += i - self.crit_pos + 1;
646 // See if the left part of the needle matches
647 let start = if long_period { 0 } else { self.memory };
648 for i in range(start, self.crit_pos).rev() {
649 if needle[i] != haystack[self.position + i] {
650 self.position += self.period;
652 self.memory = needle.len() - self.period;
658 // We have found a match!
659 let match_pos = self.position;
660 self.position += needle.len(); // add self.period for all matches
662 self.memory = 0; // set to needle.len() - self.period for all matches
664 return Some((match_pos, match_pos + needle.len()));
668 // Computes a critical factorization (u, v) of `arr`.
669 // Specifically, returns (i, p), where i is the starting index of v in some
670 // critical factorization (u, v) and p = period(v)
672 fn maximal_suffix(arr: &[u8], reversed: bool) -> (uint, uint) {
673 let mut left = -1; // Corresponds to i in the paper
674 let mut right = 0; // Corresponds to j in the paper
675 let mut offset = 1; // Corresponds to k in the paper
676 let mut period = 1; // Corresponds to p in the paper
678 while right + offset < arr.len() {
682 a = arr[left + offset];
683 b = arr[right + offset];
685 a = arr[right + offset];
686 b = arr[left + offset];
689 // Suffix is smaller, period is entire prefix so far.
692 period = right - left;
694 // Advance through repetition of the current period.
695 if offset == period {
702 // Suffix is larger, start over from current location.
713 /// The internal state of an iterator that searches for matches of a substring
714 /// within a larger string using a dynamically chosen search algorithm
717 Naive(NaiveSearcher),
718 TwoWay(TwoWaySearcher),
719 TwoWayLong(TwoWaySearcher)
723 fn new(haystack: &[u8], needle: &[u8]) -> Searcher {
725 // FIXME(#16715): This unsigned integer addition will probably not
726 // overflow because that would mean that the memory almost solely
727 // consists of the needle. Needs #16715 to be formally fixed.
728 if needle.len() + 20 > haystack.len() {
729 Naive(NaiveSearcher::new())
731 let searcher = TwoWaySearcher::new(needle);
732 if searcher.memory == uint::MAX { // If the period is long
741 /// An iterator over the start and end indices of the matches of a
742 /// substring within a larger string
744 pub struct MatchIndices<'a> {
751 /// An iterator over the substrings of a string separated by a given
754 pub struct StrSplits<'a> {
755 it: MatchIndices<'a>,
760 impl<'a> Iterator<(uint, uint)> for MatchIndices<'a> {
762 fn next(&mut self) -> Option<(uint, uint)> {
763 match self.searcher {
764 Naive(ref mut searcher)
765 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes()),
766 TwoWay(ref mut searcher)
767 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), false),
768 TwoWayLong(ref mut searcher)
769 => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), true)
774 impl<'a> Iterator<&'a str> for StrSplits<'a> {
776 fn next(&mut self) -> Option<&'a str> {
777 if self.finished { return None; }
779 match self.it.next() {
780 Some((from, to)) => {
781 let ret = Some(self.it.haystack.slice(self.last_end, from));
786 self.finished = true;
787 Some(self.it.haystack.slice(self.last_end, self.it.haystack.len()))
793 /// External iterator for a string's UTF16 codeunits.
794 /// Use with the `std::iter` module.
796 pub struct Utf16CodeUnits<'a> {
797 encoder: Utf16Encoder<Chars<'a>>
800 impl<'a> Iterator<u16> for Utf16CodeUnits<'a> {
802 fn next(&mut self) -> Option<u16> { self.encoder.next() }
805 fn size_hint(&self) -> (uint, Option<uint>) { self.encoder.size_hint() }
809 /// Iterator adaptor for encoding `char`s to UTF-16.
811 pub struct Utf16Encoder<I> {
816 impl<I> Utf16Encoder<I> {
817 /// Create an UTF-16 encoder from any `char` iterator.
818 pub fn new(chars: I) -> Utf16Encoder<I> where I: Iterator<char> {
819 Utf16Encoder { chars: chars, extra: 0 }
823 impl<I> Iterator<u16> for Utf16Encoder<I> where I: Iterator<char> {
825 fn next(&mut self) -> Option<u16> {
827 let tmp = self.extra;
832 let mut buf = [0u16, ..2];
833 self.chars.next().map(|ch| {
834 let n = ch.encode_utf16(buf[mut]).unwrap_or(0);
835 if n == 2 { self.extra = buf[1]; }
841 fn size_hint(&self) -> (uint, Option<uint>) {
842 let (low, high) = self.chars.size_hint();
843 // every char gets either one u16 or two u16,
844 // so this iterator is between 1 or 2 times as
845 // long as the underlying iterator.
846 (low, high.and_then(|n| n.checked_mul(2)))
851 Section: Comparing strings
854 // share the implementation of the lang-item vs. non-lang-item
856 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
857 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
859 fn eq_slice_(a: &str, b: &str) -> bool {
860 #[allow(improper_ctypes)]
861 extern { fn memcmp(s1: *const i8, s2: *const i8, n: uint) -> i32; }
862 a.len() == b.len() && unsafe {
863 memcmp(a.as_ptr() as *const i8,
864 b.as_ptr() as *const i8,
869 /// Bytewise slice equality
870 /// NOTE: This function is (ab)used in rustc::middle::trans::_match
871 /// to compare &[u8] byte slices that are not necessarily valid UTF-8.
874 pub fn eq_slice(a: &str, b: &str) -> bool {
882 /// Walk through `iter` checking that it's a valid UTF-8 sequence,
883 /// returning `true` in that case, or, if it is invalid, `false` with
884 /// `iter` reset such that it is pointing at the first byte in the
885 /// invalid sequence.
887 fn run_utf8_validation_iterator(iter: &mut slice::Items<u8>) -> bool {
889 // save the current thing we're pointing at.
892 // restore the iterator we had at the start of this codepoint.
893 macro_rules! err ( () => { {*iter = old; return false} });
894 macro_rules! next ( () => {
897 // we needed data, but there was none: error!
902 let first = match iter.next() {
904 // we're at the end of the iterator and a codepoint
905 // boundary at the same time, so this string is valid.
909 // ASCII characters are always valid, so only large
910 // bytes need more examination.
912 let w = utf8_char_width(first);
913 let second = next!();
914 // 2-byte encoding is for codepoints \u0080 to \u07ff
915 // first C2 80 last DF BF
916 // 3-byte encoding is for codepoints \u0800 to \uffff
917 // first E0 A0 80 last EF BF BF
918 // excluding surrogates codepoints \ud800 to \udfff
919 // ED A0 80 to ED BF BF
920 // 4-byte encoding is for codepoints \u10000 to \u10ffff
921 // first F0 90 80 80 last F4 8F BF BF
923 // Use the UTF-8 syntax from the RFC
925 // https://tools.ietf.org/html/rfc3629
927 // UTF8-2 = %xC2-DF UTF8-tail
928 // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
929 // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
930 // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
931 // %xF4 %x80-8F 2( UTF8-tail )
933 2 => if second & !CONT_MASK != TAG_CONT_U8 {err!()},
935 match (first, second, next!() & !CONT_MASK) {
936 (0xE0 , 0xA0 ... 0xBF, TAG_CONT_U8) |
937 (0xE1 ... 0xEC, 0x80 ... 0xBF, TAG_CONT_U8) |
938 (0xED , 0x80 ... 0x9F, TAG_CONT_U8) |
939 (0xEE ... 0xEF, 0x80 ... 0xBF, TAG_CONT_U8) => {}
944 match (first, second, next!() & !CONT_MASK, next!() & !CONT_MASK) {
945 (0xF0 , 0x90 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
946 (0xF1 ... 0xF3, 0x80 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
947 (0xF4 , 0x80 ... 0x8F, TAG_CONT_U8, TAG_CONT_U8) => {}
957 /// Determines if a vector of bytes contains valid UTF-8.
958 pub fn is_utf8(v: &[u8]) -> bool {
959 run_utf8_validation_iterator(&mut v.iter())
962 /// Determines if a vector of `u16` contains valid UTF-16
963 pub fn is_utf16(v: &[u16]) -> bool {
964 let mut it = v.iter();
965 macro_rules! next ( ($ret:expr) => {
966 match it.next() { Some(u) => *u, None => return $ret }
972 match char::from_u32(u as u32) {
975 let u2 = next!(false);
976 if u < 0xD7FF || u > 0xDBFF ||
977 u2 < 0xDC00 || u2 > 0xDFFF { return false; }
983 /// An iterator that decodes UTF-16 encoded codepoints from a vector
986 pub struct Utf16Items<'a> {
987 iter: slice::Items<'a, u16>
989 /// The possibilities for values decoded from a `u16` stream.
990 #[deriving(PartialEq, Eq, Clone, Show)]
992 /// A valid codepoint.
994 /// An invalid surrogate without its pair.
999 /// Convert `self` to a `char`, taking `LoneSurrogate`s to the
1000 /// replacement character (U+FFFD).
1002 pub fn to_char_lossy(&self) -> char {
1004 ScalarValue(c) => c,
1005 LoneSurrogate(_) => '\uFFFD'
1010 impl<'a> Iterator<Utf16Item> for Utf16Items<'a> {
1011 fn next(&mut self) -> Option<Utf16Item> {
1012 let u = match self.iter.next() {
1017 if u < 0xD800 || 0xDFFF < u {
1019 Some(ScalarValue(unsafe {mem::transmute(u as u32)}))
1020 } else if u >= 0xDC00 {
1021 // a trailing surrogate
1022 Some(LoneSurrogate(u))
1024 // preserve state for rewinding.
1025 let old = self.iter;
1027 let u2 = match self.iter.next() {
1030 None => return Some(LoneSurrogate(u))
1032 if u2 < 0xDC00 || u2 > 0xDFFF {
1033 // not a trailing surrogate so we're not a valid
1034 // surrogate pair, so rewind to redecode u2 next time.
1036 return Some(LoneSurrogate(u))
1039 // all ok, so lets decode it.
1040 let c = ((u - 0xD800) as u32 << 10 | (u2 - 0xDC00) as u32) + 0x1_0000;
1041 Some(ScalarValue(unsafe {mem::transmute(c)}))
1046 fn size_hint(&self) -> (uint, Option<uint>) {
1047 let (low, high) = self.iter.size_hint();
1048 // we could be entirely valid surrogates (2 elements per
1049 // char), or entirely non-surrogates (1 element per char)
1054 /// Create an iterator over the UTF-16 encoded codepoints in `v`,
1055 /// returning invalid surrogates as `LoneSurrogate`s.
1061 /// use std::str::{ScalarValue, LoneSurrogate};
1063 /// // 𝄞mus<invalid>ic<invalid>
1064 /// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
1065 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
1068 /// assert_eq!(str::utf16_items(&v).collect::<Vec<_>>(),
1069 /// vec![ScalarValue('𝄞'),
1070 /// ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
1071 /// LoneSurrogate(0xDD1E),
1072 /// ScalarValue('i'), ScalarValue('c'),
1073 /// LoneSurrogate(0xD834)]);
1075 pub fn utf16_items<'a>(v: &'a [u16]) -> Utf16Items<'a> {
1076 Utf16Items { iter : v.iter() }
1079 /// Return a slice of `v` ending at (and not including) the first NUL
1088 /// let mut v = ['a' as u16, 'b' as u16, 'c' as u16, 'd' as u16];
1089 /// // no NULs so no change
1090 /// assert_eq!(str::truncate_utf16_at_nul(&v), v.as_slice());
1094 /// let b: &[_] = &['a' as u16, 'b' as u16];
1095 /// assert_eq!(str::truncate_utf16_at_nul(&v), b);
1097 pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] {
1098 match v.iter().position(|c| *c == 0) {
1099 // don't include the 0
1105 // https://tools.ietf.org/html/rfc3629
1106 static UTF8_CHAR_WIDTH: [u8, ..256] = [
1107 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1108 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1109 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1110 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1111 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1112 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1113 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1114 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
1115 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1116 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
1117 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1118 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
1119 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1120 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
1121 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
1122 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
1125 /// Given a first byte, determine how many bytes are in this UTF-8 character
1127 pub fn utf8_char_width(b: u8) -> uint {
1128 return UTF8_CHAR_WIDTH[b as uint] as uint;
1131 /// Struct that contains a `char` and the index of the first byte of
1132 /// the next `char` in a string. This can be used as a data structure
1133 /// for iterating over the UTF-8 bytes of a string.
1134 pub struct CharRange {
1137 /// Index of the first byte of the next `char`
1141 /// Mask of the value bits of a continuation byte
1142 const CONT_MASK: u8 = 0b0011_1111u8;
1143 /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte
1144 const TAG_CONT_U8: u8 = 0b1000_0000u8;
1146 /// Unsafe operations
1151 use slice::SlicePrelude;
1152 use str::{is_utf8, StrPrelude};
1154 /// Converts a slice of bytes to a string slice without checking
1155 /// that the string contains valid UTF-8.
1156 #[deprecated = "renamed to str::from_utf8_unchecked"]
1157 pub unsafe fn from_utf8<'a>(v: &'a [u8]) -> &'a str {
1158 super::from_utf8_unchecked(v)
1161 /// Form a slice from a C string. Unsafe because the caller must ensure the
1162 /// C string has the static lifetime, or else the return value may be
1163 /// invalidated later.
1164 #[deprecated = "renamed to str::from_c_str"]
1165 pub unsafe fn c_str_to_static_slice(s: *const i8) -> &'static str {
1166 let s = s as *const u8;
1169 while *curr != 0u8 {
1171 curr = s.offset(len as int);
1173 let v = Slice { data: s, len: len };
1174 assert!(is_utf8(::mem::transmute(v)));
1178 /// Takes a bytewise (not UTF-8) slice from a string.
1180 /// Returns the substring from [`begin`..`end`).
1184 /// If begin is greater than end.
1185 /// If end is greater than the length of the string.
1187 #[deprecated = "call the slice_unchecked method instead"]
1188 pub unsafe fn slice_bytes<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
1189 assert!(begin <= end);
1190 assert!(end <= s.len());
1191 s.slice_unchecked(begin, end)
1194 /// Takes a bytewise (not UTF-8) slice from a string.
1196 /// Returns the substring from [`begin`..`end`).
1198 /// Caller must check slice boundaries!
1200 #[deprecated = "this has moved to a method on `str` directly"]
1201 pub unsafe fn slice_unchecked<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
1202 s.slice_unchecked(begin, end)
1207 Section: Trait implementations
1210 #[allow(missing_docs)]
1212 use cmp::{Ord, Ordering, Less, Equal, Greater, PartialEq, PartialOrd, Equiv, Eq};
1213 use iter::IteratorExt;
1214 use option::{Option, Some};
1216 use str::{Str, StrPrelude, eq_slice};
1220 fn cmp(&self, other: &str) -> Ordering {
1221 for (s_b, o_b) in self.bytes().zip(other.bytes()) {
1222 match s_b.cmp(&o_b) {
1223 Greater => return Greater,
1224 Less => return Less,
1229 self.len().cmp(&other.len())
1233 impl PartialEq for str {
1235 fn eq(&self, other: &str) -> bool {
1236 eq_slice(self, other)
1239 fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
1244 impl PartialOrd for str {
1246 fn partial_cmp(&self, other: &str) -> Option<Ordering> {
1247 Some(self.cmp(other))
1251 #[allow(deprecated)]
1252 #[deprecated = "Use overloaded `core::cmp::PartialEq`"]
1253 impl<S: Str> Equiv<S> for str {
1255 fn equiv(&self, other: &S) -> bool { eq_slice(self, other.as_slice()) }
1258 impl ops::Slice<uint, str> for str {
1260 fn as_slice_<'a>(&'a self) -> &'a str {
1265 fn slice_from_or_fail<'a>(&'a self, from: &uint) -> &'a str {
1266 self.slice_from(*from)
1270 fn slice_to_or_fail<'a>(&'a self, to: &uint) -> &'a str {
1275 fn slice_or_fail<'a>(&'a self, from: &uint, to: &uint) -> &'a str {
1276 self.slice(*from, *to)
1281 /// Any string that can be represented as a slice
1282 pub trait Str for Sized? {
1283 /// Work with `self` as a slice.
1284 fn as_slice<'a>(&'a self) -> &'a str;
1289 fn as_slice<'a>(&'a self) -> &'a str { self }
1292 impl<'a, Sized? S> Str for &'a S where S: Str {
1294 fn as_slice(&self) -> &str { Str::as_slice(*self) }
1297 /// Methods for string slices
1298 pub trait StrPrelude for Sized? {
1299 /// Returns true if one string contains another
1303 /// - needle - The string to look for
1308 /// assert!("bananas".contains("nana"));
1310 fn contains(&self, needle: &str) -> bool;
1312 /// Returns true if a string contains a char.
1316 /// - needle - The char to look for
1321 /// assert!("hello".contains_char('e'));
1323 fn contains_char(&self, needle: char) -> bool;
1325 /// An iterator over the characters of `self`. Note, this iterates
1326 /// over Unicode code-points, not Unicode graphemes.
1331 /// let v: Vec<char> = "abc åäö".chars().collect();
1332 /// assert_eq!(v, vec!['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
1334 fn chars<'a>(&'a self) -> Chars<'a>;
1336 /// An iterator over the bytes of `self`
1341 /// let v: Vec<u8> = "bors".bytes().collect();
1342 /// assert_eq!(v, b"bors".to_vec());
1344 fn bytes<'a>(&'a self) -> Bytes<'a>;
1346 /// An iterator over the characters of `self` and their byte offsets.
1347 fn char_indices<'a>(&'a self) -> CharOffsets<'a>;
1349 /// An iterator over substrings of `self`, separated by characters
1350 /// matched by `sep`.
1355 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1356 /// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
1358 /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
1359 /// assert_eq!(v, vec!["abc", "def", "ghi"]);
1361 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1362 /// assert_eq!(v, vec!["lion", "", "tiger", "leopard"]);
1364 /// let v: Vec<&str> = "".split('X').collect();
1365 /// assert_eq!(v, vec![""]);
1367 fn split<'a, Sep: CharEq>(&'a self, sep: Sep) -> CharSplits<'a, Sep>;
1369 /// An iterator over substrings of `self`, separated by characters
1370 /// matched by `sep`, restricted to splitting at most `count`
1376 /// let v: Vec<&str> = "Mary had a little lambda".splitn(2, ' ').collect();
1377 /// assert_eq!(v, vec!["Mary", "had", "a little lambda"]);
1379 /// let v: Vec<&str> = "abc1def2ghi".splitn(1, |c: char| c.is_numeric()).collect();
1380 /// assert_eq!(v, vec!["abc", "def2ghi"]);
1382 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(2, 'X').collect();
1383 /// assert_eq!(v, vec!["lion", "", "tigerXleopard"]);
1385 /// let v: Vec<&str> = "abcXdef".splitn(0, 'X').collect();
1386 /// assert_eq!(v, vec!["abcXdef"]);
1388 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1389 /// assert_eq!(v, vec![""]);
1391 fn splitn<'a, Sep: CharEq>(&'a self, count: uint, sep: Sep) -> CharSplitsN<'a, Sep>;
1393 /// An iterator over substrings of `self`, separated by characters
1394 /// matched by `sep`.
1396 /// Equivalent to `split`, except that the trailing substring
1397 /// is skipped if empty (terminator semantics).
1402 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1403 /// assert_eq!(v, vec!["A", "B"]);
1405 /// let v: Vec<&str> = "A..B..".split_terminator('.').collect();
1406 /// assert_eq!(v, vec!["A", "", "B", ""]);
1408 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').rev().collect();
1409 /// assert_eq!(v, vec!["lamb", "little", "a", "had", "Mary"]);
1411 /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).rev().collect();
1412 /// assert_eq!(v, vec!["ghi", "def", "abc"]);
1414 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').rev().collect();
1415 /// assert_eq!(v, vec!["leopard", "tiger", "", "lion"]);
1417 fn split_terminator<'a, Sep: CharEq>(&'a self, sep: Sep) -> CharSplits<'a, Sep>;
1419 /// An iterator over substrings of `self`, separated by characters
1420 /// matched by `sep`, starting from the end of the string.
1421 /// Restricted to splitting at most `count` times.
1426 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(2, ' ').collect();
1427 /// assert_eq!(v, vec!["lamb", "little", "Mary had a"]);
1429 /// let v: Vec<&str> = "abc1def2ghi".rsplitn(1, |c: char| c.is_numeric()).collect();
1430 /// assert_eq!(v, vec!["ghi", "abc1def"]);
1432 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(2, 'X').collect();
1433 /// assert_eq!(v, vec!["leopard", "tiger", "lionX"]);
1435 fn rsplitn<'a, Sep: CharEq>(&'a self, count: uint, sep: Sep) -> CharSplitsN<'a, Sep>;
1437 /// An iterator over the start and end indices of the disjoint
1438 /// matches of `sep` within `self`.
1440 /// That is, each returned value `(start, end)` satisfies
1441 /// `self.slice(start, end) == sep`. For matches of `sep` within
1442 /// `self` that overlap, only the indices corresponding to the
1443 /// first match are returned.
1448 /// let v: Vec<(uint, uint)> = "abcXXXabcYYYabc".match_indices("abc").collect();
1449 /// assert_eq!(v, vec![(0,3), (6,9), (12,15)]);
1451 /// let v: Vec<(uint, uint)> = "1abcabc2".match_indices("abc").collect();
1452 /// assert_eq!(v, vec![(1,4), (4,7)]);
1454 /// let v: Vec<(uint, uint)> = "ababa".match_indices("aba").collect();
1455 /// assert_eq!(v, vec![(0, 3)]); // only the first `aba`
1457 fn match_indices<'a>(&'a self, sep: &'a str) -> MatchIndices<'a>;
1459 /// An iterator over the substrings of `self` separated by `sep`.
1464 /// let v: Vec<&str> = "abcXXXabcYYYabc".split_str("abc").collect();
1465 /// assert_eq!(v, vec!["", "XXX", "YYY", ""]);
1467 /// let v: Vec<&str> = "1abcabc2".split_str("abc").collect();
1468 /// assert_eq!(v, vec!["1", "", "2"]);
1470 fn split_str<'a>(&'a self, &'a str) -> StrSplits<'a>;
1472 /// An iterator over the lines of a string (subsequences separated
1473 /// by `\n`). This does not include the empty string after a
1479 /// let four_lines = "foo\nbar\n\nbaz\n";
1480 /// let v: Vec<&str> = four_lines.lines().collect();
1481 /// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
1483 fn lines<'a>(&'a self) -> CharSplits<'a, char>;
1485 /// An iterator over the lines of a string, separated by either
1486 /// `\n` or `\r\n`. As with `.lines()`, this does not include an
1487 /// empty trailing line.
1492 /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
1493 /// let v: Vec<&str> = four_lines.lines_any().collect();
1494 /// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
1496 fn lines_any<'a>(&'a self) -> AnyLines<'a>;
1498 /// Returns the number of Unicode code points (`char`) that a
1501 /// This does not perform any normalization, and is `O(n)`, since
1502 /// UTF-8 is a variable width encoding of code points.
1504 /// *Warning*: The number of code points in a string does not directly
1505 /// correspond to the number of visible characters or width of the
1506 /// visible text due to composing characters, and double- and
1507 /// zero-width ones.
1509 /// See also `.len()` for the byte length.
1514 /// // composed forms of `ö` and `é`
1515 /// let c = "Löwe 老虎 Léopard"; // German, Simplified Chinese, French
1516 /// // decomposed forms of `ö` and `é`
1517 /// let d = "Lo\u0308we 老虎 Le\u0301opard";
1519 /// assert_eq!(c.char_len(), 15);
1520 /// assert_eq!(d.char_len(), 17);
1522 /// assert_eq!(c.len(), 21);
1523 /// assert_eq!(d.len(), 23);
1525 /// // the two strings *look* the same
1526 /// println!("{}", c);
1527 /// println!("{}", d);
1529 fn char_len(&self) -> uint;
1531 /// Returns a slice of the given string from the byte range
1532 /// [`begin`..`end`).
1534 /// This operation is `O(1)`.
1536 /// Panics when `begin` and `end` do not point to valid characters
1537 /// or point beyond the last character of the string.
1539 /// See also `slice_to` and `slice_from` for slicing prefixes and
1540 /// suffixes of strings, and `slice_chars` for slicing based on
1541 /// code point counts.
1546 /// let s = "Löwe 老虎 Léopard";
1547 /// assert_eq!(s.slice(0, 1), "L");
1549 /// assert_eq!(s.slice(1, 9), "öwe 老");
1551 /// // these will panic:
1552 /// // byte 2 lies within `ö`:
1553 /// // s.slice(2, 3);
1555 /// // byte 8 lies within `老`
1556 /// // s.slice(1, 8);
1558 /// // byte 100 is outside the string
1559 /// // s.slice(3, 100);
1561 fn slice<'a>(&'a self, begin: uint, end: uint) -> &'a str;
1563 /// Returns a slice of the string from `begin` to its end.
1565 /// Equivalent to `self.slice(begin, self.len())`.
1567 /// Panics when `begin` does not point to a valid character, or is
1570 /// See also `slice`, `slice_to` and `slice_chars`.
1571 fn slice_from<'a>(&'a self, begin: uint) -> &'a str;
1573 /// Returns a slice of the string from the beginning to byte
1576 /// Equivalent to `self.slice(0, end)`.
1578 /// Panics when `end` does not point to a valid character, or is
1581 /// See also `slice`, `slice_from` and `slice_chars`.
1582 fn slice_to<'a>(&'a self, end: uint) -> &'a str;
1584 /// Returns a slice of the string from the character range
1585 /// [`begin`..`end`).
1587 /// That is, start at the `begin`-th code point of the string and
1588 /// continue to the `end`-th code point. This does not detect or
1589 /// handle edge cases such as leaving a combining character as the
1590 /// first code point of the string.
1592 /// Due to the design of UTF-8, this operation is `O(end)`.
1593 /// See `slice`, `slice_to` and `slice_from` for `O(1)`
1594 /// variants that use byte indices rather than code point
1597 /// Panics if `begin` > `end` or the either `begin` or `end` are
1598 /// beyond the last character of the string.
1603 /// let s = "Löwe 老虎 Léopard";
1604 /// assert_eq!(s.slice_chars(0, 4), "Löwe");
1605 /// assert_eq!(s.slice_chars(5, 7), "老虎");
1607 fn slice_chars<'a>(&'a self, begin: uint, end: uint) -> &'a str;
1609 /// Takes a bytewise (not UTF-8) slice from a string.
1611 /// Returns the substring from [`begin`..`end`).
1613 /// Caller must check both UTF-8 character boundaries and the boundaries of
1614 /// the entire slice as well.
1615 unsafe fn slice_unchecked<'a>(&'a self, begin: uint, end: uint) -> &'a str;
1617 /// Returns true if `needle` is a prefix of the string.
1622 /// assert!("banana".starts_with("ba"));
1624 fn starts_with(&self, needle: &str) -> bool;
1626 /// Returns true if `needle` is a suffix of the string.
1631 /// assert!("banana".ends_with("nana"));
1633 fn ends_with(&self, needle: &str) -> bool;
1635 /// Returns a string with characters that match `to_trim` removed from the left and the right.
1639 /// * to_trim - a character matcher
1644 /// assert_eq!("11foo1bar11".trim_chars('1'), "foo1bar")
1645 /// let x: &[_] = &['1', '2'];
1646 /// assert_eq!("12foo1bar12".trim_chars(x), "foo1bar")
1647 /// assert_eq!("123foo1bar123".trim_chars(|c: char| c.is_numeric()), "foo1bar")
1649 fn trim_chars<'a, C: CharEq>(&'a self, to_trim: C) -> &'a str;
1651 /// Returns a string with leading `chars_to_trim` removed.
1655 /// * to_trim - a character matcher
1660 /// assert_eq!("11foo1bar11".trim_left_chars('1'), "foo1bar11")
1661 /// let x: &[_] = &['1', '2'];
1662 /// assert_eq!("12foo1bar12".trim_left_chars(x), "foo1bar12")
1663 /// assert_eq!("123foo1bar123".trim_left_chars(|c: char| c.is_numeric()), "foo1bar123")
1665 fn trim_left_chars<'a, C: CharEq>(&'a self, to_trim: C) -> &'a str;
1667 /// Returns a string with trailing `chars_to_trim` removed.
1671 /// * to_trim - a character matcher
1676 /// assert_eq!("11foo1bar11".trim_right_chars('1'), "11foo1bar")
1677 /// let x: &[_] = &['1', '2'];
1678 /// assert_eq!("12foo1bar12".trim_right_chars(x), "12foo1bar")
1679 /// assert_eq!("123foo1bar123".trim_right_chars(|c: char| c.is_numeric()), "123foo1bar")
1681 fn trim_right_chars<'a, C: CharEq>(&'a self, to_trim: C) -> &'a str;
1683 /// Check that `index`-th byte lies at the start and/or end of a
1684 /// UTF-8 code point sequence.
1686 /// The start and end of the string (when `index == self.len()`)
1687 /// are considered to be boundaries.
1689 /// Panics if `index` is greater than `self.len()`.
1694 /// let s = "Löwe 老虎 Léopard";
1695 /// assert!(s.is_char_boundary(0));
1697 /// assert!(s.is_char_boundary(6));
1698 /// assert!(s.is_char_boundary(s.len()));
1700 /// // second byte of `ö`
1701 /// assert!(!s.is_char_boundary(2));
1703 /// // third byte of `老`
1704 /// assert!(!s.is_char_boundary(8));
1706 fn is_char_boundary(&self, index: uint) -> bool;
1708 /// Pluck a character out of a string and return the index of the next
1711 /// This function can be used to iterate over the Unicode characters of a
1716 /// This example manually iterates through the characters of a
1717 /// string; this should normally be done by `.chars()` or
1718 /// `.char_indices`.
1721 /// use std::str::CharRange;
1723 /// let s = "中华Việt Nam";
1725 /// while i < s.len() {
1726 /// let CharRange {ch, next} = s.char_range_at(i);
1727 /// println!("{}: {}", i, ch);
1749 /// * s - The string
1750 /// * i - The byte offset of the char to extract
1754 /// A record {ch: char, next: uint} containing the char value and the byte
1755 /// index of the next Unicode character.
1759 /// If `i` is greater than or equal to the length of the string.
1760 /// If `i` is not the index of the beginning of a valid UTF-8 character.
1761 fn char_range_at(&self, start: uint) -> CharRange;
1763 /// Given a byte position and a str, return the previous char and its position.
1765 /// This function can be used to iterate over a Unicode string in reverse.
1767 /// Returns 0 for next index if called on start index 0.
1771 /// If `i` is greater than the length of the string.
1772 /// If `i` is not an index following a valid UTF-8 character.
1773 fn char_range_at_reverse(&self, start: uint) -> CharRange;
1775 /// Plucks the character starting at the `i`th byte of a string.
1781 /// assert_eq!(s.char_at(1), 'b');
1782 /// assert_eq!(s.char_at(2), 'π');
1783 /// assert_eq!(s.char_at(4), 'c');
1788 /// If `i` is greater than or equal to the length of the string.
1789 /// If `i` is not the index of the beginning of a valid UTF-8 character.
1790 fn char_at(&self, i: uint) -> char;
1792 /// Plucks the character ending at the `i`th byte of a string.
1796 /// If `i` is greater than the length of the string.
1797 /// If `i` is not an index following a valid UTF-8 character.
1798 fn char_at_reverse(&self, i: uint) -> char;
1800 /// Work with the byte buffer of a string as a byte slice.
1805 /// assert_eq!("bors".as_bytes(), b"bors");
1807 fn as_bytes<'a>(&'a self) -> &'a [u8];
1809 /// Returns the byte index of the first character of `self` that
1810 /// matches `search`.
1814 /// `Some` containing the byte index of the last matching character
1815 /// or `None` if there is no match
1820 /// let s = "Löwe 老虎 Léopard";
1822 /// assert_eq!(s.find('L'), Some(0));
1823 /// assert_eq!(s.find('é'), Some(14));
1825 /// // the first space
1826 /// assert_eq!(s.find(|c: char| c.is_whitespace()), Some(5));
1828 /// // neither are found
1829 /// let x: &[_] = &['1', '2'];
1830 /// assert_eq!(s.find(x), None);
1832 fn find<C: CharEq>(&self, search: C) -> Option<uint>;
1834 /// Returns the byte index of the last character of `self` that
1835 /// matches `search`.
1839 /// `Some` containing the byte index of the last matching character
1840 /// or `None` if there is no match.
1845 /// let s = "Löwe 老虎 Léopard";
1847 /// assert_eq!(s.rfind('L'), Some(13));
1848 /// assert_eq!(s.rfind('é'), Some(14));
1850 /// // the second space
1851 /// assert_eq!(s.rfind(|c: char| c.is_whitespace()), Some(12));
1853 /// // searches for an occurrence of either `1` or `2`, but neither are found
1854 /// let x: &[_] = &['1', '2'];
1855 /// assert_eq!(s.rfind(x), None);
1857 fn rfind<C: CharEq>(&self, search: C) -> Option<uint>;
1859 /// Returns the byte index of the first matching substring
1863 /// * `needle` - The string to search for
1867 /// `Some` containing the byte index of the first matching substring
1868 /// or `None` if there is no match.
1873 /// let s = "Löwe 老虎 Léopard";
1875 /// assert_eq!(s.find_str("老虎 L"), Some(6));
1876 /// assert_eq!(s.find_str("muffin man"), None);
1878 fn find_str(&self, &str) -> Option<uint>;
1880 /// Retrieves the first character from a string slice and returns
1881 /// it. This does not allocate a new string; instead, it returns a
1882 /// slice that point one character beyond the character that was
1883 /// shifted. If the string does not contain any characters,
1884 /// None is returned instead.
1889 /// let s = "Löwe 老虎 Léopard";
1890 /// let (c, s1) = s.slice_shift_char().unwrap();
1891 /// assert_eq!(c, 'L');
1892 /// assert_eq!(s1, "öwe 老虎 Léopard");
1894 /// let (c, s2) = s1.slice_shift_char().unwrap();
1895 /// assert_eq!(c, 'ö');
1896 /// assert_eq!(s2, "we 老虎 Léopard");
1898 fn slice_shift_char<'a>(&'a self) -> Option<(char, &'a str)>;
1900 /// Returns the byte offset of an inner slice relative to an enclosing outer slice.
1902 /// Panics if `inner` is not a direct slice contained within self.
1907 /// let string = "a\nb\nc";
1908 /// let lines: Vec<&str> = string.lines().collect();
1910 /// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
1911 /// assert!(string.subslice_offset(lines[1]) == 2); // &"b"
1912 /// assert!(string.subslice_offset(lines[2]) == 4); // &"c"
1914 fn subslice_offset(&self, inner: &str) -> uint;
1916 /// Return an unsafe pointer to the strings buffer.
1918 /// The caller must ensure that the string outlives this pointer,
1919 /// and that it is not reallocated (e.g. by pushing to the
1921 fn as_ptr(&self) -> *const u8;
1923 /// Return an iterator of `u16` over the string encoded as UTF-16.
1924 fn utf16_units<'a>(&'a self) -> Utf16CodeUnits<'a>;
1926 /// Return the number of bytes in this string
1931 /// assert_eq!("foo".len(), 3);
1932 /// assert_eq!("ƒoo".len(), 4);
1934 #[experimental = "not triaged yet"]
1935 fn len(&self) -> uint;
1937 /// Returns true if this slice contains no bytes
1942 /// assert!("".is_empty());
1945 #[experimental = "not triaged yet"]
1946 fn is_empty(&self) -> bool { self.len() == 0 }
1950 fn slice_error_fail(s: &str, begin: uint, end: uint) -> ! {
1951 assert!(begin <= end);
1952 panic!("index {} and/or {} in `{}` do not lie on character boundary",
1956 impl StrPrelude for str {
1958 fn contains(&self, needle: &str) -> bool {
1959 self.find_str(needle).is_some()
1963 fn contains_char(&self, needle: char) -> bool {
1964 self.find(needle).is_some()
1968 fn chars(&self) -> Chars {
1969 Chars{iter: self.as_bytes().iter()}
1973 fn bytes(&self) -> Bytes {
1974 self.as_bytes().iter().map(|&b| b)
1978 fn char_indices(&self) -> CharOffsets {
1979 CharOffsets{front_offset: 0, iter: self.chars()}
1983 fn split<Sep: CharEq>(&self, sep: Sep) -> CharSplits<Sep> {
1986 only_ascii: sep.only_ascii(),
1988 allow_trailing_empty: true,
1994 fn splitn<Sep: CharEq>(&self, count: uint, sep: Sep)
1995 -> CharSplitsN<Sep> {
1997 iter: self.split(sep),
2004 fn split_terminator<Sep: CharEq>(&self, sep: Sep)
2005 -> CharSplits<Sep> {
2007 allow_trailing_empty: false,
2013 fn rsplitn<Sep: CharEq>(&self, count: uint, sep: Sep)
2014 -> CharSplitsN<Sep> {
2016 iter: self.split(sep),
2023 fn match_indices<'a>(&'a self, sep: &'a str) -> MatchIndices<'a> {
2024 assert!(!sep.is_empty())
2028 searcher: Searcher::new(self.as_bytes(), sep.as_bytes())
2033 fn split_str<'a>(&'a self, sep: &'a str) -> StrSplits<'a> {
2035 it: self.match_indices(sep),
2042 fn lines(&self) -> CharSplits<char> {
2043 self.split_terminator('\n')
2046 fn lines_any(&self) -> AnyLines {
2047 self.lines().map(|line| {
2049 if l > 0 && line.as_bytes()[l - 1] == b'\r' { line.slice(0, l - 1) }
2055 fn char_len(&self) -> uint { self.chars().count() }
2058 fn slice(&self, begin: uint, end: uint) -> &str {
2059 // is_char_boundary checks that the index is in [0, .len()]
2061 self.is_char_boundary(begin) &&
2062 self.is_char_boundary(end) {
2063 unsafe { self.slice_unchecked(begin, end) }
2065 slice_error_fail(self, begin, end)
2070 fn slice_from(&self, begin: uint) -> &str {
2071 // is_char_boundary checks that the index is in [0, .len()]
2072 if self.is_char_boundary(begin) {
2073 unsafe { self.slice_unchecked(begin, self.len()) }
2075 slice_error_fail(self, begin, self.len())
2080 fn slice_to(&self, end: uint) -> &str {
2081 // is_char_boundary checks that the index is in [0, .len()]
2082 if self.is_char_boundary(end) {
2083 unsafe { self.slice_unchecked(0, end) }
2085 slice_error_fail(self, 0, end)
2089 fn slice_chars(&self, begin: uint, end: uint) -> &str {
2090 assert!(begin <= end);
2092 let mut begin_byte = None;
2093 let mut end_byte = None;
2095 // This could be even more efficient by not decoding,
2096 // only finding the char boundaries
2097 for (idx, _) in self.char_indices() {
2098 if count == begin { begin_byte = Some(idx); }
2099 if count == end { end_byte = Some(idx); break; }
2102 if begin_byte.is_none() && count == begin { begin_byte = Some(self.len()) }
2103 if end_byte.is_none() && count == end { end_byte = Some(self.len()) }
2105 match (begin_byte, end_byte) {
2106 (None, _) => panic!("slice_chars: `begin` is beyond end of string"),
2107 (_, None) => panic!("slice_chars: `end` is beyond end of string"),
2108 (Some(a), Some(b)) => unsafe { self.slice_unchecked(a, b) }
2113 unsafe fn slice_unchecked(&self, begin: uint, end: uint) -> &str {
2114 mem::transmute(Slice {
2115 data: self.as_ptr().offset(begin as int),
2121 fn starts_with(&self, needle: &str) -> bool {
2122 let n = needle.len();
2123 self.len() >= n && needle.as_bytes() == self.as_bytes()[..n]
2127 fn ends_with(&self, needle: &str) -> bool {
2128 let (m, n) = (self.len(), needle.len());
2129 m >= n && needle.as_bytes() == self.as_bytes()[m-n..]
2133 fn trim_chars<C: CharEq>(&self, mut to_trim: C) -> &str {
2134 let cur = match self.find(|c: char| !to_trim.matches(c)) {
2136 Some(i) => unsafe { self.slice_unchecked(i, self.len()) }
2138 match cur.rfind(|c: char| !to_trim.matches(c)) {
2141 let right = cur.char_range_at(i).next;
2142 unsafe { cur.slice_unchecked(0, right) }
2148 fn trim_left_chars<C: CharEq>(&self, mut to_trim: C) -> &str {
2149 match self.find(|c: char| !to_trim.matches(c)) {
2151 Some(first) => unsafe { self.slice_unchecked(first, self.len()) }
2156 fn trim_right_chars<C: CharEq>(&self, mut to_trim: C) -> &str {
2157 match self.rfind(|c: char| !to_trim.matches(c)) {
2160 let next = self.char_range_at(last).next;
2161 unsafe { self.slice_unchecked(0u, next) }
2167 fn is_char_boundary(&self, index: uint) -> bool {
2168 if index == self.len() { return true; }
2169 match self.as_bytes().get(index) {
2171 Some(&b) => b < 128u8 || b >= 192u8,
2176 fn char_range_at(&self, i: uint) -> CharRange {
2177 if self.as_bytes()[i] < 128u8 {
2178 return CharRange {ch: self.as_bytes()[i] as char, next: i + 1 };
2181 // Multibyte case is a fn to allow char_range_at to inline cleanly
2182 fn multibyte_char_range_at(s: &str, i: uint) -> CharRange {
2183 let mut val = s.as_bytes()[i] as u32;
2184 let w = UTF8_CHAR_WIDTH[val as uint] as uint;
2187 val = utf8_first_byte!(val, w);
2188 val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 1]);
2189 if w > 2 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 2]); }
2190 if w > 3 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 3]); }
2192 return CharRange {ch: unsafe { mem::transmute(val) }, next: i + w};
2195 return multibyte_char_range_at(self, i);
2199 fn char_range_at_reverse(&self, start: uint) -> CharRange {
2200 let mut prev = start;
2202 prev = prev.saturating_sub(1);
2203 if self.as_bytes()[prev] < 128 {
2204 return CharRange{ch: self.as_bytes()[prev] as char, next: prev}
2207 // Multibyte case is a fn to allow char_range_at_reverse to inline cleanly
2208 fn multibyte_char_range_at_reverse(s: &str, mut i: uint) -> CharRange {
2209 // while there is a previous byte == 10......
2210 while i > 0 && s.as_bytes()[i] & !CONT_MASK == TAG_CONT_U8 {
2214 let mut val = s.as_bytes()[i] as u32;
2215 let w = UTF8_CHAR_WIDTH[val as uint] as uint;
2218 val = utf8_first_byte!(val, w);
2219 val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 1]);
2220 if w > 2 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 2]); }
2221 if w > 3 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 3]); }
2223 return CharRange {ch: unsafe { mem::transmute(val) }, next: i};
2226 return multibyte_char_range_at_reverse(self, prev);
2230 fn char_at(&self, i: uint) -> char {
2231 self.char_range_at(i).ch
2235 fn char_at_reverse(&self, i: uint) -> char {
2236 self.char_range_at_reverse(i).ch
2240 fn as_bytes(&self) -> &[u8] {
2241 unsafe { mem::transmute(self) }
2244 fn find<C: CharEq>(&self, mut search: C) -> Option<uint> {
2245 if search.only_ascii() {
2246 self.bytes().position(|b| search.matches(b as char))
2248 for (index, c) in self.char_indices() {
2249 if search.matches(c) { return Some(index); }
2255 fn rfind<C: CharEq>(&self, mut search: C) -> Option<uint> {
2256 if search.only_ascii() {
2257 self.bytes().rposition(|b| search.matches(b as char))
2259 for (index, c) in self.char_indices().rev() {
2260 if search.matches(c) { return Some(index); }
2266 fn find_str(&self, needle: &str) -> Option<uint> {
2267 if needle.is_empty() {
2270 self.match_indices(needle)
2272 .map(|(start, _end)| start)
2277 fn slice_shift_char(&self) -> Option<(char, &str)> {
2278 if self.is_empty() {
2281 let CharRange {ch, next} = self.char_range_at(0u);
2282 let next_s = unsafe { self.slice_unchecked(next, self.len()) };
2287 fn subslice_offset(&self, inner: &str) -> uint {
2288 let a_start = self.as_ptr() as uint;
2289 let a_end = a_start + self.len();
2290 let b_start = inner.as_ptr() as uint;
2291 let b_end = b_start + inner.len();
2293 assert!(a_start <= b_start);
2294 assert!(b_end <= a_end);
2299 fn as_ptr(&self) -> *const u8 {
2304 fn utf16_units(&self) -> Utf16CodeUnits {
2305 Utf16CodeUnits { encoder: Utf16Encoder::new(self.chars()) }
2309 fn len(&self) -> uint { self.repr().len }
2312 impl<'a> Default for &'a str {
2313 fn default() -> &'a str { "" }