mod.rs 59.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! String manipulation
//!
//! For more details, see std::str

15 16
#![doc(primitive = "str")]

17
use self::OldSearcher::{TwoWay, TwoWayLong};
18 19
use self::pattern::Pattern;
use self::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
S
Steven Fackler 已提交
20

21
use char::CharExt;
22
use clone::Clone;
23
use cmp::{self, Eq};
S
Sean McArthur 已提交
24
use convert::AsRef;
25
use default::Default;
26
use fmt;
27
use iter::ExactSizeIterator;
S
Steven Fackler 已提交
28
use iter::{Map, Iterator, DoubleEndedIterator};
29
use mem;
30
use ops::{Fn, FnMut, FnOnce};
31
use option::Option::{self, None, Some};
32
use raw::{Repr, Slice};
33 34
use result::Result::{self, Ok, Err};
use slice::{self, SliceExt};
35
use usize;
36

37
pub mod pattern;
38

B
Brendan Zabarauskas 已提交
39 40
/// A trait to abstract the idea of creating a new instance of a type from a
/// string.
A
Alex Crichton 已提交
41
#[stable(feature = "rust1", since = "1.0.0")]
B
Brendan Zabarauskas 已提交
42
pub trait FromStr {
A
Alex Crichton 已提交
43 44 45 46
    /// The associated error which can be returned from parsing.
    #[stable(feature = "rust1", since = "1.0.0")]
    type Err;

B
Brendan Zabarauskas 已提交
47 48
    /// Parses a string `s` to return an optional value of this type. If the
    /// string is ill-formatted, the None is returned.
A
Alex Crichton 已提交
49 50
    #[stable(feature = "rust1", since = "1.0.0")]
    fn from_str(s: &str) -> Result<Self, Self::Err>;
B
Brendan Zabarauskas 已提交
51 52
}

A
Alex Crichton 已提交
53
#[stable(feature = "rust1", since = "1.0.0")]
B
Brendan Zabarauskas 已提交
54
impl FromStr for bool {
A
Alex Crichton 已提交
55 56
    type Err = ParseBoolError;

B
Brendan Zabarauskas 已提交
57 58
    /// Parse a `bool` from a string.
    ///
59 60
    /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
    /// actually be parseable.
B
Brendan Zabarauskas 已提交
61 62 63
    ///
    /// # Examples
    ///
64
    /// ```
65 66 67 68 69 70 71
    /// use std::str::FromStr;
    ///
    /// assert_eq!(FromStr::from_str("true"), Ok(true));
    /// assert_eq!(FromStr::from_str("false"), Ok(false));
    /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
    /// ```
    ///
72
    /// Note, in many cases, the `.parse()` method on `str` is more proper.
73
    ///
74
    /// ```
A
Alex Crichton 已提交
75 76 77
    /// assert_eq!("true".parse(), Ok(true));
    /// assert_eq!("false".parse(), Ok(false));
    /// assert!("not even a boolean".parse::<bool>().is_err());
B
Brendan Zabarauskas 已提交
78 79
    /// ```
    #[inline]
A
Alex Crichton 已提交
80
    fn from_str(s: &str) -> Result<bool, ParseBoolError> {
B
Brendan Zabarauskas 已提交
81
        match s {
A
Alex Crichton 已提交
82 83 84
            "true"  => Ok(true),
            "false" => Ok(false),
            _       => Err(ParseBoolError { _priv: () }),
B
Brendan Zabarauskas 已提交
85 86 87 88
        }
    }
}

A
Alex Crichton 已提交
89
/// An error returned when parsing a `bool` from a string fails.
A
Alex Crichton 已提交
90
#[derive(Debug, Clone, PartialEq)]
A
Alex Crichton 已提交
91 92 93 94 95 96 97 98 99 100
#[stable(feature = "rust1", since = "1.0.0")]
pub struct ParseBoolError { _priv: () }

#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for ParseBoolError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        "provided string was not `true` or `false`".fmt(f)
    }
}

101 102 103 104
/*
Section: Creating a string
*/

A
Alex Crichton 已提交
105
/// Errors which can occur when attempting to interpret a byte slice as a `str`.
J
Jorge Aparicio 已提交
106
#[derive(Copy, Eq, PartialEq, Clone, Debug)]
107 108 109 110 111 112 113 114
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Utf8Error {
    valid_up_to: usize,
}

impl Utf8Error {
    /// Returns the index in the given string up to which valid UTF-8 was
    /// verified.
A
Alex Crichton 已提交
115
    ///
116 117 118 119
    /// Starting at the index provided, but not necessarily at it precisely, an
    /// invalid UTF-8 encoding sequence was found.
    #[unstable(feature = "utf8_error", reason = "method just added")]
    pub fn valid_up_to(&self) -> usize { self.valid_up_to }
A
Alex Crichton 已提交
120 121 122 123
}

/// Converts a slice of bytes to a string slice without performing any
/// allocations.
124 125 126 127
///
/// Once the slice has been validated as utf-8, it is transmuted in-place and
/// returned as a '&str' instead of a '&[u8]'
///
A
Alex Crichton 已提交
128 129 130 131
/// # Failure
///
/// Returns `Err` if the slice is not utf-8 with a description as to why the
/// provided slice is not utf-8.
B
Brian Anderson 已提交
132
#[stable(feature = "rust1", since = "1.0.0")]
A
Alex Crichton 已提交
133 134 135
pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
    try!(run_utf8_validation_iterator(&mut v.iter()));
    Ok(unsafe { from_utf8_unchecked(v) })
136 137 138 139
}

/// Converts a slice of bytes to a string slice without checking
/// that the string contains valid UTF-8.
140
#[inline(always)]
B
Brian Anderson 已提交
141
#[stable(feature = "rust1", since = "1.0.0")]
142 143 144 145
pub unsafe fn from_utf8_unchecked<'a>(v: &'a [u8]) -> &'a str {
    mem::transmute(v)
}

146
#[stable(feature = "rust1", since = "1.0.0")]
147 148
impl fmt::Display for Utf8Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
149
        write!(f, "invalid utf-8: invalid byte near index {}", self.valid_up_to)
150 151 152
    }
}

153 154 155 156
/*
Section: Iterators
*/

157 158 159
/// Iterator for the char (representing *Unicode Scalar Values*) of a string
///
/// Created with the method `.chars()`.
160
#[derive(Clone)]
B
Brian Anderson 已提交
161
#[stable(feature = "rust1", since = "1.0.0")]
162
pub struct Chars<'a> {
163
    iter: slice::Iter<'a, u8>
164 165
}

T
Tobias Bucher 已提交
166 167 168 169 170
/// Return the initial codepoint accumulator for the first byte.
/// The first byte is special, only want bottom 5 bits for width 2, 4 bits
/// for width 3, and 3 bits for width 4.
#[inline]
fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 }
171

T
Tobias Bucher 已提交
172 173 174
/// Return the value of `ch` updated with continuation byte `byte`.
#[inline]
fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
175

T
Tobias Bucher 已提交
176 177 178 179
/// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the
/// bits `10`).
#[inline]
fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
180 181 182 183 184 185 186

#[inline]
fn unwrap_or_0(opt: Option<&u8>) -> u8 {
    match opt {
        Some(&byte) => byte,
        None => 0,
    }
187 188
}

A
Aaron Turon 已提交
189 190
/// Reads the next code point out of a byte iterator (assuming a
/// UTF-8-like encoding).
191
#[unstable(feature = "core")]
192
#[inline]
A
Aaron Turon 已提交
193 194 195 196 197 198 199 200 201 202 203
pub fn next_code_point(bytes: &mut slice::Iter<u8>) -> Option<u32> {
    // Decode UTF-8
    let x = match bytes.next() {
        None => return None,
        Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
        Some(&next_byte) => next_byte,
    };

    // Multibyte case follows
    // Decode from a byte combination out of: [[[x y] z] w]
    // NOTE: Performance is sensitive to the exact formulation here
T
Tobias Bucher 已提交
204
    let init = utf8_first_byte(x, 2);
A
Aaron Turon 已提交
205
    let y = unwrap_or_0(bytes.next());
T
Tobias Bucher 已提交
206
    let mut ch = utf8_acc_cont_byte(init, y);
A
Aaron Turon 已提交
207 208 209 210
    if x >= 0xE0 {
        // [[x y z] w] case
        // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
        let z = unwrap_or_0(bytes.next());
T
Tobias Bucher 已提交
211
        let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
A
Aaron Turon 已提交
212 213 214 215 216
        ch = init << 12 | y_z;
        if x >= 0xF0 {
            // [x y z w] case
            // use only the lower 3 bits of `init`
            let w = unwrap_or_0(bytes.next());
T
Tobias Bucher 已提交
217
            ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
A
Aaron Turon 已提交
218 219 220 221 222 223
        }
    }

    Some(ch)
}

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
/// Reads the last code point out of a byte iterator (assuming a
/// UTF-8-like encoding).
#[unstable(feature = "core")]
#[inline]
pub fn next_code_point_reverse(bytes: &mut slice::Iter<u8>) -> Option<u32> {
    // Decode UTF-8
    let w = match bytes.next_back() {
        None => return None,
        Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
        Some(&back_byte) => back_byte,
    };

    // Multibyte case follows
    // Decode from a byte combination out of: [x [y [z w]]]
    let mut ch;
    let z = unwrap_or_0(bytes.next_back());
T
Tobias Bucher 已提交
240 241
    ch = utf8_first_byte(z, 2);
    if utf8_is_cont_byte(z) {
242
        let y = unwrap_or_0(bytes.next_back());
T
Tobias Bucher 已提交
243 244
        ch = utf8_first_byte(y, 3);
        if utf8_is_cont_byte(y) {
245
            let x = unwrap_or_0(bytes.next_back());
T
Tobias Bucher 已提交
246 247
            ch = utf8_first_byte(x, 4);
            ch = utf8_acc_cont_byte(ch, y);
248
        }
T
Tobias Bucher 已提交
249
        ch = utf8_acc_cont_byte(ch, z);
250
    }
T
Tobias Bucher 已提交
251
    ch = utf8_acc_cont_byte(ch, w);
252 253 254 255

    Some(ch)
}

B
Brian Anderson 已提交
256
#[stable(feature = "rust1", since = "1.0.0")]
257 258 259
impl<'a> Iterator for Chars<'a> {
    type Item = char;

260 261
    #[inline]
    fn next(&mut self) -> Option<char> {
A
Aaron Turon 已提交
262 263 264 265
        next_code_point(&mut self.iter).map(|ch| {
            // str invariant says `ch` is a valid Unicode Scalar Value
            unsafe {
                mem::transmute(ch)
266
            }
A
Aaron Turon 已提交
267
        })
268 269 270
    }

    #[inline]
271
    fn size_hint(&self) -> (usize, Option<usize>) {
272
        let (len, _) = self.iter.size_hint();
T
Tobias Bucher 已提交
273 274 275 276
        // `(len + 3)` can't overflow, because we know that the `slice::Iter`
        // belongs to a slice in memory which has a maximum length of
        // `isize::MAX` (that's well below `usize::MAX`).
        ((len + 3) / 4, Some(len))
277 278 279
    }
}

B
Brian Anderson 已提交
280
#[stable(feature = "rust1", since = "1.0.0")]
281
impl<'a> DoubleEndedIterator for Chars<'a> {
282 283
    #[inline]
    fn next_back(&mut self) -> Option<char> {
284 285 286 287
        next_code_point_reverse(&mut self.iter).map(|ch| {
            // str invariant says `ch` is a valid Unicode Scalar Value
            unsafe {
                mem::transmute(ch)
288
            }
289
        })
290 291 292
    }
}

293
/// Iterator for a string's characters and their byte offsets.
294
#[derive(Clone)]
B
Brian Anderson 已提交
295
#[stable(feature = "rust1", since = "1.0.0")]
A
Alex Crichton 已提交
296
pub struct CharIndices<'a> {
297
    front_offset: usize,
298 299 300
    iter: Chars<'a>,
}

B
Brian Anderson 已提交
301
#[stable(feature = "rust1", since = "1.0.0")]
302
impl<'a> Iterator for CharIndices<'a> {
303
    type Item = (usize, char);
304

305
    #[inline]
306
    fn next(&mut self) -> Option<(usize, char)> {
R
root 已提交
307
        let (pre_len, _) = self.iter.iter.size_hint();
308 309 310
        match self.iter.next() {
            None => None,
            Some(ch) => {
R
root 已提交
311
                let index = self.front_offset;
312
                let (len, _) = self.iter.iter.size_hint();
R
root 已提交
313
                self.front_offset += pre_len - len;
314 315 316
                Some((index, ch))
            }
        }
317 318 319
    }

    #[inline]
320
    fn size_hint(&self) -> (usize, Option<usize>) {
321 322 323 324
        self.iter.size_hint()
    }
}

B
Brian Anderson 已提交
325
#[stable(feature = "rust1", since = "1.0.0")]
326
impl<'a> DoubleEndedIterator for CharIndices<'a> {
327
    #[inline]
328
    fn next_back(&mut self) -> Option<(usize, char)> {
329 330 331 332
        match self.iter.next_back() {
            None => None,
            Some(ch) => {
                let (len, _) = self.iter.iter.size_hint();
R
root 已提交
333 334
                let index = self.front_offset + len;
                Some((index, ch))
335 336
            }
        }
337 338 339 340 341
    }
}

/// External iterator for a string's bytes.
/// Use with the `std::iter` module.
342
///
343
/// Created with the method `.bytes()`.
B
Brian Anderson 已提交
344
#[stable(feature = "rust1", since = "1.0.0")]
345
#[derive(Clone)]
346
pub struct Bytes<'a>(Map<slice::Iter<'a, u8>, BytesDeref>);
347

348 349
/// A nameable, clonable fn type
#[derive(Clone)]
350
struct BytesDeref;
351

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
impl<'a> Fn<(&'a u8,)> for BytesDeref {
    #[inline]
    extern "rust-call" fn call(&self, (ptr,): (&'a u8,)) -> u8 {
        *ptr
    }
}

impl<'a> FnMut<(&'a u8,)> for BytesDeref {
    #[inline]
    extern "rust-call" fn call_mut(&mut self, (ptr,): (&'a u8,)) -> u8 {
        Fn::call(&*self, (ptr,))
    }
}

impl<'a> FnOnce<(&'a u8,)> for BytesDeref {
    type Output = u8;

    #[inline]
    extern "rust-call" fn call_once(self, (ptr,): (&'a u8,)) -> u8 {
        Fn::call(&self, (ptr,))
    }
}

375 376 377
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Iterator for Bytes<'a> {
    type Item = u8;
378

379 380 381 382
    #[inline]
    fn next(&mut self) -> Option<u8> {
        self.0.next()
    }
383

384 385 386 387
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
388 389
}

390 391 392 393 394 395
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> DoubleEndedIterator for Bytes<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<u8> {
        self.0.next_back()
    }
396 397
}

B
Brian Anderson 已提交
398
#[stable(feature = "rust1", since = "1.0.0")]
399 400 401 402 403
impl<'a> ExactSizeIterator for Bytes<'a> {
    #[inline]
    fn len(&self) -> usize {
        self.0.len()
    }
J
Jake Goulding 已提交
404 405
}

406 407 408 409 410 411 412 413 414 415 416 417 418
/// This macro generates a Clone impl for string pattern API
/// wrapper types of the form X<'a, P>
macro_rules! derive_pattern_clone {
    (clone $t:ident with |$s:ident| $e:expr) => {
        impl<'a, P: Pattern<'a>> Clone for $t<'a, P>
            where P::Searcher: Clone
        {
            fn clone(&self) -> Self {
                let $s = self;
                $e
            }
        }
    }
419
}
J
Jake Goulding 已提交
420

421 422 423 424
/// This macro generates two public iterator structs
/// wrapping an private internal one that makes use of the `Pattern` API.
///
/// For all patterns `P: Pattern<'a>` the following items will be
425
/// generated (generics omitted):
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
///
/// struct $forward_iterator($internal_iterator);
/// struct $reverse_iterator($internal_iterator);
///
/// impl Iterator for $forward_iterator
/// { /* internal ends up calling Searcher::next_match() */ }
///
/// impl DoubleEndedIterator for $forward_iterator
///       where P::Searcher: DoubleEndedSearcher
/// { /* internal ends up calling Searcher::next_match_back() */ }
///
/// impl Iterator for $reverse_iterator
///       where P::Searcher: ReverseSearcher
/// { /* internal ends up calling Searcher::next_match_back() */ }
///
/// impl DoubleEndedIterator for $reverse_iterator
///       where P::Searcher: DoubleEndedSearcher
/// { /* internal ends up calling Searcher::next_match() */ }
///
/// The internal one is defined outside the macro, and has almost the same
/// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and
/// `pattern::ReverseSearcher` for both forward and reverse iteration.
///
/// "Almost", because a `Searcher` and a `ReverseSearcher` for a given
/// `Pattern` might not return the same elements, so actually implementing
/// `DoubleEndedIterator` for it would be incorrect.
/// (See the docs in `str::pattern` for more details)
///
/// However, the internal struct still represents a single ended iterator from
/// either end, and depending on pattern is also a valid double ended iterator,
/// so the two wrapper structs implement `Iterator`
/// and `DoubleEndedIterator` depending on the concrete pattern type, leading
/// to the complex impls seen above.
macro_rules! generate_pattern_iterators {
    {
        // Forward iterator
        forward:
            $(#[$forward_iterator_attribute:meta])*
            struct $forward_iterator:ident;

        // Reverse iterator
        reverse:
            $(#[$reverse_iterator_attribute:meta])*
            struct $reverse_iterator:ident;

        // Stability of all generated items
        stability:
            $(#[$common_stability_attribute:meta])*

        // Internal almost-iterator that is being delegated to
        internal:
            $internal_iterator:ident yielding ($iterty:ty);

        // Kind of delgation - either single ended or double ended
        delegate $($t:tt)*
    } => {
        $(#[$forward_iterator_attribute])*
        $(#[$common_stability_attribute])*
        pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);

        $(#[$common_stability_attribute])*
        impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> {
            type Item = $iterty;

            #[inline]
            fn next(&mut self) -> Option<$iterty> {
                self.0.next()
            }
        }

496 497 498 499 500 501 502 503 504
        $(#[$common_stability_attribute])*
        impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P>
            where P::Searcher: Clone
        {
            fn clone(&self) -> Self {
                $forward_iterator(self.0.clone())
            }
        }

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
        $(#[$reverse_iterator_attribute])*
        $(#[$common_stability_attribute])*
        pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>);

        $(#[$common_stability_attribute])*
        impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P>
            where P::Searcher: ReverseSearcher<'a>
        {
            type Item = $iterty;

            #[inline]
            fn next(&mut self) -> Option<$iterty> {
                self.0.next_back()
            }
        }

521 522 523 524 525 526 527 528 529
        $(#[$common_stability_attribute])*
        impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P>
            where P::Searcher: Clone
        {
            fn clone(&self) -> Self {
                $reverse_iterator(self.0.clone())
            }
        }

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
        generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*,
                                                $forward_iterator,
                                                $reverse_iterator, $iterty);
    };
    {
        double ended; with $(#[$common_stability_attribute:meta])*,
                           $forward_iterator:ident,
                           $reverse_iterator:ident, $iterty:ty
    } => {
        $(#[$common_stability_attribute])*
        impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P>
            where P::Searcher: DoubleEndedSearcher<'a>
        {
            #[inline]
            fn next_back(&mut self) -> Option<$iterty> {
                self.0.next_back()
            }
        }

        $(#[$common_stability_attribute])*
        impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P>
            where P::Searcher: DoubleEndedSearcher<'a>
        {
            #[inline]
            fn next_back(&mut self) -> Option<$iterty> {
                self.0.next()
            }
        }
    };
    {
        single ended; with $(#[$common_stability_attribute:meta])*,
                           $forward_iterator:ident,
                           $reverse_iterator:ident, $iterty:ty
    } => {}
A
Alex Crichton 已提交
564 565
}

566 567 568 569
derive_pattern_clone!{
    clone SplitInternal
    with |s| SplitInternal { matcher: s.matcher.clone(), ..*s }
}
570 571 572 573 574 575
struct SplitInternal<'a, P: Pattern<'a>> {
    start: usize,
    end: usize,
    matcher: P::Searcher,
    allow_trailing_empty: bool,
    finished: bool,
A
Alex Crichton 已提交
576
}
577

578
impl<'a, P: Pattern<'a>> SplitInternal<'a, P> {
579 580
    #[inline]
    fn get_end(&mut self) -> Option<&'a str> {
581
        if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) {
582
            self.finished = true;
583 584 585 586
            unsafe {
                let string = self.matcher.haystack().slice_unchecked(self.start, self.end);
                Some(string)
            }
587 588 589 590
        } else {
            None
        }
    }
591

592 593 594 595
    #[inline]
    fn next(&mut self) -> Option<&'a str> {
        if self.finished { return None }

596 597
        let haystack = self.matcher.haystack();
        match self.matcher.next_match() {
598
            Some((a, b)) => unsafe {
599 600
                let elt = haystack.slice_unchecked(self.start, a);
                self.start = b;
601 602 603 604 605 606 607
                Some(elt)
            },
            None => self.get_end(),
        }
    }

    #[inline]
608 609 610
    fn next_back(&mut self) -> Option<&'a str>
        where P::Searcher: ReverseSearcher<'a>
    {
611 612 613 614 615 616 617 618 619
        if self.finished { return None }

        if !self.allow_trailing_empty {
            self.allow_trailing_empty = true;
            match self.next_back() {
                Some(elt) if !elt.is_empty() => return Some(elt),
                _ => if self.finished { return None }
            }
        }
620 621 622

        let haystack = self.matcher.haystack();
        match self.matcher.next_match_back() {
623
            Some((a, b)) => unsafe {
624 625
                let elt = haystack.slice_unchecked(b, self.end);
                self.end = a;
626 627
                Some(elt)
            },
628 629 630 631
            None => unsafe {
                self.finished = true;
                Some(haystack.slice_unchecked(self.start, self.end))
            },
632 633 634 635
        }
    }
}

636 637
generate_pattern_iterators! {
    forward:
638
        /// Created with the method `.split()`.
639 640
        struct Split;
    reverse:
641
        /// Created with the method `.rsplit()`.
642 643 644 645 646 647 648 649 650 651
        struct RSplit;
    stability:
        #[stable(feature = "rust1", since = "1.0.0")]
    internal:
        SplitInternal yielding (&'a str);
    delegate double ended;
}

generate_pattern_iterators! {
    forward:
652
        /// Created with the method `.split_terminator()`.
653 654
        struct SplitTerminator;
    reverse:
655
        /// Created with the method `.rsplit_terminator()`.
656 657 658 659 660 661 662
        struct RSplitTerminator;
    stability:
        #[stable(feature = "rust1", since = "1.0.0")]
    internal:
        SplitInternal yielding (&'a str);
    delegate double ended;
}
663

664 665 666 667
derive_pattern_clone!{
    clone SplitNInternal
    with |s| SplitNInternal { iter: s.iter.clone(), ..*s }
}
668 669 670 671 672
struct SplitNInternal<'a, P: Pattern<'a>> {
    iter: SplitInternal<'a, P>,
    /// The number of splits remaining
    count: usize,
}
673

674
impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> {
675 676
    #[inline]
    fn next(&mut self) -> Option<&'a str> {
677 678 679 680
        match self.count {
            0 => None,
            1 => { self.count = 0; self.iter.get_end() }
            _ => { self.count -= 1; self.iter.next() }
681 682 683
        }
    }

J
Jake Goulding 已提交
684
    #[inline]
685 686 687 688 689 690 691
    fn next_back(&mut self) -> Option<&'a str>
        where P::Searcher: ReverseSearcher<'a>
    {
        match self.count {
            0 => None,
            1 => { self.count = 0; self.iter.get_end() }
            _ => { self.count -= 1; self.iter.next_back() }
J
Jake Goulding 已提交
692 693 694 695
        }
    }
}

696 697
generate_pattern_iterators! {
    forward:
698
        /// Created with the method `.splitn()`.
699 700
        struct SplitN;
    reverse:
701
        /// Created with the method `.rsplitn()`.
702 703 704 705 706 707 708 709
        struct RSplitN;
    stability:
        #[stable(feature = "rust1", since = "1.0.0")]
    internal:
        SplitNInternal yielding (&'a str);
    delegate single ended;
}

710 711 712 713
derive_pattern_clone!{
    clone MatchIndicesInternal
    with |s| MatchIndicesInternal(s.0.clone())
}
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher);

impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> {
    #[inline]
    fn next(&mut self) -> Option<(usize, usize)> {
        self.0.next_match()
    }

    #[inline]
    fn next_back(&mut self) -> Option<(usize, usize)>
        where P::Searcher: ReverseSearcher<'a>
    {
        self.0.next_match_back()
    }
}

generate_pattern_iterators! {
    forward:
732
        /// Created with the method `.match_indices()`.
733 734
        struct MatchIndices;
    reverse:
735
        /// Created with the method `.rmatch_indices()`.
736 737 738 739 740 741 742 743 744
        struct RMatchIndices;
    stability:
        #[unstable(feature = "core",
                   reason = "type may be removed or have its iterator impl changed")]
    internal:
        MatchIndicesInternal yielding ((usize, usize));
    delegate double ended;
}

745 746 747 748
derive_pattern_clone!{
    clone MatchesInternal
    with |s| MatchesInternal(s.0.clone())
}
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);

impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> {
    #[inline]
    fn next(&mut self) -> Option<&'a str> {
        self.0.next_match().map(|(a, b)| unsafe {
            // Indices are known to be on utf8 boundaries
            self.0.haystack().slice_unchecked(a, b)
        })
    }

    #[inline]
    fn next_back(&mut self) -> Option<&'a str>
        where P::Searcher: ReverseSearcher<'a>
    {
        self.0.next_match_back().map(|(a, b)| unsafe {
            // Indices are known to be on utf8 boundaries
            self.0.haystack().slice_unchecked(a, b)
        })
    }
}

generate_pattern_iterators! {
    forward:
773
        /// Created with the method `.matches()`.
774 775
        struct Matches;
    reverse:
776
        /// Created with the method `.rmatches()`.
777 778 779 780 781 782 783 784
        struct RMatches;
    stability:
        #[unstable(feature = "core", reason = "type got recently added")]
    internal:
        MatchesInternal yielding (&'a str);
    delegate double ended;
}

785
/// Created with the method `.lines()`.
786
#[stable(feature = "rust1", since = "1.0.0")]
787
#[derive(Clone)]
788 789
pub struct Lines<'a>(SplitTerminator<'a, char>);

J
Jake Goulding 已提交
790
#[stable(feature = "rust1", since = "1.0.0")]
791
impl<'a> Iterator for Lines<'a> {
J
Jake Goulding 已提交
792 793 794 795
    type Item = &'a str;

    #[inline]
    fn next(&mut self) -> Option<&'a str> {
796 797
        self.0.next()
    }
J
Jake Goulding 已提交
798

799 800 801 802 803 804 805 806 807 808 809
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> DoubleEndedIterator for Lines<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a str> {
        self.0.next_back()
J
Jake Goulding 已提交
810 811 812
    }
}

813
/// Created with the method `.lines_any()`.
814
#[stable(feature = "rust1", since = "1.0.0")]
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
#[derive(Clone)]
pub struct LinesAny<'a>(Map<Lines<'a>, LinesAnyMap>);

/// A nameable, clonable fn type
#[derive(Clone)]
struct LinesAnyMap;

impl<'a> Fn<(&'a str,)> for LinesAnyMap {
    #[inline]
    extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str {
        let l = line.len();
        if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
        else { line }
    }
}

impl<'a> FnMut<(&'a str,)> for LinesAnyMap {
    #[inline]
    extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str {
        Fn::call(&*self, (line,))
    }
}

impl<'a> FnOnce<(&'a str,)> for LinesAnyMap {
    type Output = &'a str;

    #[inline]
    extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str {
        Fn::call(&self, (line,))
J
Jake Goulding 已提交
844 845 846
    }
}

847
#[stable(feature = "rust1", since = "1.0.0")]
848
impl<'a> Iterator for LinesAny<'a> {
849 850 851 852
    type Item = &'a str;

    #[inline]
    fn next(&mut self) -> Option<&'a str> {
853 854 855 856 857 858 859 860 861 862 863 864 865 866
        self.0.next()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> DoubleEndedIterator for LinesAny<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a str> {
        self.0.next_back()
867 868 869
    }
}

870 871
/// The internal state of an iterator that searches for matches of a substring
/// within a larger string using two-way search
872
#[derive(Clone)]
873 874
struct TwoWaySearcher {
    // constants
875 876
    crit_pos: usize,
    period: usize,
877 878 879
    byteset: u64,

    // variables
880 881
    position: usize,
    memory: usize
882 883
}

N
nham 已提交
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
/*
    This is the Two-Way search algorithm, which was introduced in the paper:
    Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675.

    Here's some background information.

    A *word* is a string of symbols. The *length* of a word should be a familiar
    notion, and here we denote it for any word x by |x|.
    (We also allow for the possibility of the *empty word*, a word of length zero).

    If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a
    *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p].
    For example, both 1 and 2 are periods for the string "aa". As another example,
    the only period of the string "abcd" is 4.

    We denote by period(x) the *smallest* period of x (provided that x is non-empty).
    This is always well-defined since every non-empty word x has at least one period,
    |x|. We sometimes call this *the period* of x.

    If u, v and x are words such that x = uv, where uv is the concatenation of u and
    v, then we say that (u, v) is a *factorization* of x.

    Let (u, v) be a factorization for a word x. Then if w is a non-empty word such
    that both of the following hold

      - either w is a suffix of u or u is a suffix of w
      - either w is a prefix of v or v is a prefix of w

    then w is said to be a *repetition* for the factorization (u, v).

    Just to unpack this, there are four possibilities here. Let w = "abc". Then we
    might have:

      - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde")
      - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab")
      - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi")
      - u is a suffix of w and v is a prefix of w. ex: ("bc", "a")

    Note that the word vu is a repetition for any factorization (u,v) of x = uv,
    so every factorization has at least one repetition.

    If x is a string and (u, v) is a factorization for x, then a *local period* for
    (u, v) is an integer r such that there is some word w such that |w| = r and w is
    a repetition for (u, v).

    We denote by local_period(u, v) the smallest local period of (u, v). We sometimes
    call this *the local period* of (u, v). Provided that x = uv is non-empty, this
    is well-defined (because each non-empty word has at least one factorization, as
    noted above).

    It can be proven that the following is an equivalent definition of a local period
    for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
    all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
    defined. (i.e. i > 0 and i + r < |x|).

    Using the above reformulation, it is easy to prove that

        1 <= local_period(u, v) <= period(uv)

    A factorization (u, v) of x such that local_period(u,v) = period(x) is called a
    *critical factorization*.

    The algorithm hinges on the following theorem, which is stated without proof:

    **Critical Factorization Theorem** Any word x has at least one critical
    factorization (u, v) such that |u| < period(x).

    The purpose of maximal_suffix is to find such a critical factorization.

*/
954
impl TwoWaySearcher {
955
    #[allow(dead_code)]
956
    fn new(needle: &[u8]) -> TwoWaySearcher {
T
Tristan Storch 已提交
957 958 959 960 961 962 963 964 965
        let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false);
        let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true);

        let (crit_pos, period) =
            if crit_pos_false > crit_pos_true {
                (crit_pos_false, period_false)
            } else {
                (crit_pos_true, period_true)
            };
966

N
nham 已提交
967
        // This isn't in the original algorithm, as far as I'm aware.
968
        let byteset = needle.iter()
969
                            .fold(0, |a, &b| (1 << ((b & 0x3f) as usize)) | a);
970

N
nham 已提交
971 972 973
        // A particularly readable explanation of what's going on here can be found
        // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically
        // see the code for "Algorithm CP" on p. 323.
N
nham 已提交
974
        //
N
nham 已提交
975 976
        // What's going on is we have some critical factorization (u, v) of the
        // needle, and we want to determine whether u is a suffix of
977
        // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use
N
nham 已提交
978 979
        // "Algorithm CP2", which is optimized for when the period of the needle
        // is large.
980
        if &needle[..crit_pos] == &needle[period.. period + crit_pos] {
981
            TwoWaySearcher {
982
                crit_pos: crit_pos,
983 984 985 986 987 988 989 990
                period: period,
                byteset: byteset,

                position: 0,
                memory: 0
            }
        } else {
            TwoWaySearcher {
991 992
                crit_pos: crit_pos,
                period: cmp::max(crit_pos, needle.len() - crit_pos) + 1,
993 994 995
                byteset: byteset,

                position: 0,
996
                memory: usize::MAX // Dummy value to signify that the period is long
997 998 999 1000
            }
        }
    }

N
nham 已提交
1001 1002 1003 1004 1005
    // One of the main ideas of Two-Way is that we factorize the needle into
    // two halves, (u, v), and begin trying to find v in the haystack by scanning
    // left to right. If v matches, we try to match u by scanning right to left.
    // How far we can jump when we encounter a mismatch is all based on the fact
    // that (u, v) is a critical factorization for the needle.
1006
    #[inline]
M
Marvin Löbel 已提交
1007
    fn next(&mut self, haystack: &[u8], needle: &[u8], long_period: bool)
M
Marvin Löbel 已提交
1008
            -> Option<(usize, usize)> {
1009 1010 1011 1012 1013 1014 1015
        'search: loop {
            // Check that we have room to search in
            if self.position + needle.len() > haystack.len() {
                return None;
            }

            // Quickly skip by large portions unrelated to our substring
1016 1017
            if (self.byteset >>
                    ((haystack[self.position + needle.len() - 1] & 0x3f)
1018
                     as usize)) & 1 == 0 {
1019
                self.position += needle.len();
1020 1021 1022
                if !long_period {
                    self.memory = 0;
                }
1023 1024 1025 1026
                continue 'search;
            }

            // See if the right part of the needle matches
1027 1028
            let start = if long_period { self.crit_pos }
                        else { cmp::max(self.crit_pos, self.memory) };
1029
            for i in start..needle.len() {
1030
                if needle[i] != haystack[self.position + i] {
1031 1032
                    self.position += i - self.crit_pos + 1;
                    if !long_period {
1033 1034 1035 1036 1037 1038 1039
                        self.memory = 0;
                    }
                    continue 'search;
                }
            }

            // See if the left part of the needle matches
1040
            let start = if long_period { 0 } else { self.memory };
1041
            for i in (start..self.crit_pos).rev() {
1042 1043
                if needle[i] != haystack[self.position + i] {
                    self.position += self.period;
1044
                    if !long_period {
1045 1046 1047 1048 1049 1050 1051
                        self.memory = needle.len() - self.period;
                    }
                    continue 'search;
                }
            }

            // We have found a match!
1052
            let match_pos = self.position;
1053
            self.position += needle.len(); // add self.period for all matches
1054
            if !long_period {
1055 1056
                self.memory = 0; // set to needle.len() - self.period for all matches
            }
1057
            return Some((match_pos, match_pos + needle.len()));
1058 1059 1060
        }
    }

N
nham 已提交
1061 1062 1063
    // Computes a critical factorization (u, v) of `arr`.
    // Specifically, returns (i, p), where i is the starting index of v in some
    // critical factorization (u, v) and p = period(v)
1064
    #[inline]
1065
    #[allow(dead_code)]
A
Aaron Turon 已提交
1066
    #[allow(deprecated)]
1067
    fn maximal_suffix(arr: &[u8], reversed: bool) -> (usize, usize) {
1068
        let mut left: usize = !0; // Corresponds to i in the paper
1069 1070 1071 1072 1073 1074 1075 1076
        let mut right = 0; // Corresponds to j in the paper
        let mut offset = 1; // Corresponds to k in the paper
        let mut period = 1; // Corresponds to p in the paper

        while right + offset < arr.len() {
            let a;
            let b;
            if reversed {
1077
                a = arr[left.wrapping_add(offset)];
1078 1079 1080
                b = arr[right + offset];
            } else {
                a = arr[right + offset];
1081
                b = arr[left.wrapping_add(offset)];
1082 1083 1084 1085 1086
            }
            if a < b {
                // Suffix is smaller, period is entire prefix so far.
                right += offset;
                offset = 1;
1087
                period = right.wrapping_sub(left);
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
            } else if a == b {
                // Advance through repetition of the current period.
                if offset == period {
                    right += offset;
                    offset = 1;
                } else {
                    offset += 1;
                }
            } else {
                // Suffix is larger, start over from current location.
                left = right;
                right += 1;
                offset = 1;
                period = 1;
            }
        }
1104
        (left.wrapping_add(1), period)
1105 1106 1107 1108
    }
}

/// The internal state of an iterator that searches for matches of a substring
J
Joseph Crail 已提交
1109
/// within a larger string using a dynamically chosen search algorithm
1110
#[derive(Clone)]
M
Marvin Löbel 已提交
1111 1112
// NB: This is kept around for convenience because
// it is planned to be used again in the future
1113
enum OldSearcher {
1114
    TwoWay(TwoWaySearcher),
1115
    TwoWayLong(TwoWaySearcher),
1116 1117
}

1118 1119 1120
impl OldSearcher {
    #[allow(dead_code)]
    fn new(haystack: &[u8], needle: &[u8]) -> OldSearcher {
1121
        if needle.is_empty() {
1122 1123
            // Handle specially
            unimplemented!()
1124
        // FIXME: Tune this.
1125 1126 1127
        // FIXME(#16715): This unsigned integer addition will probably not
        // overflow because that would mean that the memory almost solely
        // consists of the needle. Needs #16715 to be formally fixed.
1128
        } else if needle.len() + 20 > haystack.len() {
1129 1130
            // Use naive searcher
            unimplemented!()
1131 1132
        } else {
            let searcher = TwoWaySearcher::new(needle);
1133
            if searcher.memory == usize::MAX { // If the period is long
1134 1135 1136 1137 1138 1139 1140 1141
                TwoWayLong(searcher)
            } else {
                TwoWay(searcher)
            }
        }
    }
}

1142
#[derive(Clone)]
M
Marvin Löbel 已提交
1143 1144
// NB: This is kept around for convenience because
// it is planned to be used again in the future
1145
struct OldMatchIndices<'a, 'b> {
1146
    // constants
1147
    haystack: &'a str,
1148
    needle: &'b str,
1149
    searcher: OldSearcher
1150 1151
}

1152
impl<'a, 'b>  OldMatchIndices<'a, 'b> {
1153
    #[inline]
1154 1155
    #[allow(dead_code)]
    fn next(&mut self) -> Option<(usize, usize)> {
1156 1157 1158 1159
        match self.searcher {
            TwoWay(ref mut searcher)
                => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), false),
            TwoWayLong(ref mut searcher)
1160
                => searcher.next(self.haystack.as_bytes(), self.needle.as_bytes(), true),
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
        }
    }
}

/*
Section: Comparing strings
*/

// share the implementation of the lang-item vs. non-lang-item
// eq_slice.
1171 1172
/// NOTE: This function is (ab)used in rustc::middle::trans::_match
/// to compare &[u8] byte slices that are not necessarily valid UTF-8.
1173 1174
#[inline]
fn eq_slice_(a: &str, b: &str) -> bool {
M
Marvin Löbel 已提交
1175
    // NOTE: In theory n should be libc::size_t and not usize, but libc is not available here
A
Aaron Turon 已提交
1176
    #[allow(improper_ctypes)]
1177
    extern { fn memcmp(s1: *const i8, s2: *const i8, n: usize) -> i32; }
1178
    a.len() == b.len() && unsafe {
1179 1180
        memcmp(a.as_ptr() as *const i8,
               b.as_ptr() as *const i8,
1181 1182 1183 1184 1185
               a.len()) == 0
    }
}

/// Bytewise slice equality
1186 1187
/// NOTE: This function is (ab)used in rustc::middle::trans::_match
/// to compare &[u8] byte slices that are not necessarily valid UTF-8.
1188 1189
#[lang="str_eq"]
#[inline]
A
Alex Crichton 已提交
1190
fn eq_slice(a: &str, b: &str) -> bool {
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
    eq_slice_(a, b)
}

/*
Section: Misc
*/

/// Walk through `iter` checking that it's a valid UTF-8 sequence,
/// returning `true` in that case, or, if it is invalid, `false` with
/// `iter` reset such that it is pointing at the first byte in the
/// invalid sequence.
#[inline(always)]
1203
fn run_utf8_validation_iterator(iter: &mut slice::Iter<u8>)
A
Alex Crichton 已提交
1204 1205
                                -> Result<(), Utf8Error> {
    let whole = iter.as_slice();
1206 1207
    loop {
        // save the current thing we're pointing at.
1208
        let old = iter.clone();
1209 1210

        // restore the iterator we had at the start of this codepoint.
1211
        macro_rules! err { () => {{
1212
            *iter = old.clone();
1213 1214 1215
            return Err(Utf8Error {
                valid_up_to: whole.len() - iter.as_slice().len()
            })
1216 1217 1218
        }}}

        macro_rules! next { () => {
A
Alex Crichton 已提交
1219 1220 1221
            match iter.next() {
                Some(a) => *a,
                // we needed data, but there was none: error!
1222
                None => err!(),
A
Alex Crichton 已提交
1223
            }
1224
        }}
1225 1226 1227 1228 1229

        let first = match iter.next() {
            Some(&b) => b,
            // we're at the end of the iterator and a codepoint
            // boundary at the same time, so this string is valid.
A
Alex Crichton 已提交
1230
            None => return Ok(())
1231 1232 1233 1234 1235
        };

        // ASCII characters are always valid, so only large
        // bytes need more examination.
        if first >= 128 {
T
Tobias Bucher 已提交
1236
            let w = UTF8_CHAR_WIDTH[first as usize];
1237
            let second = next!();
A
Alex Crichton 已提交
1238
            // 2-byte encoding is for codepoints  \u{0080} to  \u{07ff}
1239
            //        first  C2 80        last DF BF
A
Alex Crichton 已提交
1240
            // 3-byte encoding is for codepoints  \u{0800} to  \u{ffff}
1241
            //        first  E0 A0 80     last EF BF BF
A
Alex Crichton 已提交
1242
            //   excluding surrogates codepoints  \u{d800} to  \u{dfff}
1243
            //               ED A0 80 to       ED BF BF
A
Alex Crichton 已提交
1244
            // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
            //        first  F0 90 80 80  last F4 8F BF BF
            //
            // Use the UTF-8 syntax from the RFC
            //
            // https://tools.ietf.org/html/rfc3629
            // UTF8-1      = %x00-7F
            // UTF8-2      = %xC2-DF UTF8-tail
            // UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
            //               %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
            // UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
            //               %xF4 %x80-8F 2( UTF8-tail )
            match w {
R
root 已提交
1257
                2 => if second & !CONT_MASK != TAG_CONT_U8 {err!()},
1258
                3 => {
R
root 已提交
1259
                    match (first, second, next!() & !CONT_MASK) {
1260 1261 1262 1263
                        (0xE0         , 0xA0 ... 0xBF, TAG_CONT_U8) |
                        (0xE1 ... 0xEC, 0x80 ... 0xBF, TAG_CONT_U8) |
                        (0xED         , 0x80 ... 0x9F, TAG_CONT_U8) |
                        (0xEE ... 0xEF, 0x80 ... 0xBF, TAG_CONT_U8) => {}
1264 1265 1266 1267
                        _ => err!()
                    }
                }
                4 => {
R
root 已提交
1268
                    match (first, second, next!() & !CONT_MASK, next!() & !CONT_MASK) {
1269 1270 1271
                        (0xF0         , 0x90 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
                        (0xF1 ... 0xF3, 0x80 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) |
                        (0xF4         , 0x80 ... 0x8F, TAG_CONT_U8, TAG_CONT_U8) => {}
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
                        _ => err!()
                    }
                }
                _ => err!()
            }
        }
    }
}

// https://tools.ietf.org/html/rfc3629
1282
static UTF8_CHAR_WIDTH: [u8; 256] = [
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
];

/// Struct that contains a `char` and the index of the first byte of
/// the next `char` in a string.  This can be used as a data structure
/// for iterating over the UTF-8 bytes of a string.
1304
#[derive(Copy, Clone)]
1305 1306 1307 1308
#[unstable(feature = "str_char",
           reason = "existence of this struct is uncertain as it is frequently \
                     able to be replaced with char.len_utf8() and/or \
                     char/char_indices iterators")]
1309 1310 1311 1312
pub struct CharRange {
    /// Current `char`
    pub ch: char,
    /// Index of the first byte of the next `char`
1313
    pub next: usize,
1314 1315
}

R
root 已提交
1316
/// Mask of the value bits of a continuation byte
1317
const CONT_MASK: u8 = 0b0011_1111;
R
root 已提交
1318
/// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte
1319
const TAG_CONT_U8: u8 = 0b1000_0000;
1320 1321 1322 1323 1324

/*
Section: Trait implementations
*/

1325
mod traits {
A
Alex Crichton 已提交
1326
    use cmp::{Ordering, Ord, PartialEq, PartialOrd, Eq};
C
Corey Farwell 已提交
1327
    use cmp::Ordering::{Less, Equal, Greater};
S
Steven Fackler 已提交
1328
    use iter::Iterator;
C
Corey Farwell 已提交
1329 1330
    use option::Option;
    use option::Option::Some;
1331
    use ops;
A
Alex Crichton 已提交
1332
    use str::{StrExt, eq_slice};
1333

B
Brian Anderson 已提交
1334
    #[stable(feature = "rust1", since = "1.0.0")]
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
    impl Ord for str {
        #[inline]
        fn cmp(&self, other: &str) -> Ordering {
            for (s_b, o_b) in self.bytes().zip(other.bytes()) {
                match s_b.cmp(&o_b) {
                    Greater => return Greater,
                    Less => return Less,
                    Equal => ()
                }
            }

            self.len().cmp(&other.len())
        }
    }

B
Brian Anderson 已提交
1350
    #[stable(feature = "rust1", since = "1.0.0")]
1351 1352 1353 1354 1355 1356 1357 1358 1359
    impl PartialEq for str {
        #[inline]
        fn eq(&self, other: &str) -> bool {
            eq_slice(self, other)
        }
        #[inline]
        fn ne(&self, other: &str) -> bool { !(*self).eq(other) }
    }

B
Brian Anderson 已提交
1360
    #[stable(feature = "rust1", since = "1.0.0")]
1361 1362
    impl Eq for str {}

B
Brian Anderson 已提交
1363
    #[stable(feature = "rust1", since = "1.0.0")]
1364 1365 1366 1367 1368 1369 1370
    impl PartialOrd for str {
        #[inline]
        fn partial_cmp(&self, other: &str) -> Option<Ordering> {
            Some(self.cmp(other))
        }
    }

1371 1372 1373 1374 1375 1376 1377 1378
    /// Returns a slice of the given string from the byte range
    /// [`begin`..`end`).
    ///
    /// This operation is `O(1)`.
    ///
    /// Panics when `begin` and `end` do not point to valid characters
    /// or point beyond the last character of the string.
    ///
S
Steve Klabnik 已提交
1379
    /// # Examples
1380
    ///
1381
    /// ```
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
    /// let s = "Löwe 老虎 Léopard";
    /// assert_eq!(&s[0 .. 1], "L");
    ///
    /// assert_eq!(&s[1 .. 9], "öwe 老");
    ///
    /// // these will panic:
    /// // byte 2 lies within `ö`:
    /// // &s[2 ..3];
    ///
    /// // byte 8 lies within `老`
    /// // &s[1 .. 8];
    ///
    /// // byte 100 is outside the string
    /// // &s[3 .. 100];
    /// ```
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
    #[stable(feature = "rust1", since = "1.0.0")]
    impl ops::Index<ops::Range<usize>> for str {
        type Output = str;
        #[inline]
        fn index(&self, index: ops::Range<usize>) -> &str {
            // is_char_boundary checks that the index is in [0, .len()]
            if index.start <= index.end &&
               self.is_char_boundary(index.start) &&
               self.is_char_boundary(index.end) {
                unsafe { self.slice_unchecked(index.start, index.end) }
            } else {
                super::slice_error_fail(self, index.start, index.end)
            }
        }
    }

1413 1414 1415 1416 1417 1418 1419
    /// Returns a slice of the string from the beginning to byte
    /// `end`.
    ///
    /// Equivalent to `self[0 .. end]`.
    ///
    /// Panics when `end` does not point to a valid character, or is
    /// out of bounds.
1420
    #[stable(feature = "rust1", since = "1.0.0")]
1421
    impl ops::Index<ops::RangeTo<usize>> for str {
N
fallout  
Nick Cameron 已提交
1422
        type Output = str;
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432

        #[inline]
        fn index(&self, index: ops::RangeTo<usize>) -> &str {
            // is_char_boundary checks that the index is in [0, .len()]
            if self.is_char_boundary(index.end) {
                unsafe { self.slice_unchecked(0, index.end) }
            } else {
                super::slice_error_fail(self, 0, index.end)
            }
        }
1433
    }
1434 1435 1436 1437 1438 1439 1440

    /// Returns a slice of the string from `begin` to its end.
    ///
    /// Equivalent to `self[begin .. self.len()]`.
    ///
    /// Panics when `begin` does not point to a valid character, or is
    /// out of bounds.
1441
    #[stable(feature = "rust1", since = "1.0.0")]
1442
    impl ops::Index<ops::RangeFrom<usize>> for str {
N
fallout  
Nick Cameron 已提交
1443
        type Output = str;
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453

        #[inline]
        fn index(&self, index: ops::RangeFrom<usize>) -> &str {
            // is_char_boundary checks that the index is in [0, .len()]
            if self.is_char_boundary(index.start) {
                unsafe { self.slice_unchecked(index.start, self.len()) }
            } else {
                super::slice_error_fail(self, index.start, self.len())
            }
        }
1454
    }
1455

N
Nick Cameron 已提交
1456 1457 1458
    #[stable(feature = "rust1", since = "1.0.0")]
    impl ops::Index<ops::RangeFull> for str {
        type Output = str;
1459 1460 1461 1462 1463

        #[inline]
        fn index(&self, _index: ops::RangeFull) -> &str {
            self
        }
N
Nick Cameron 已提交
1464
    }
1465 1466 1467
}

/// Methods for string slices
A
Alex Crichton 已提交
1468
#[allow(missing_docs)]
1469
#[doc(hidden)]
1470
pub trait StrExt {
A
Alex Crichton 已提交
1471 1472
    // NB there are no docs here are they're all located on the StrExt trait in
    // libcollections, not here.
1473

1474 1475
    fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
    fn contains_char<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
J
Jorge Aparicio 已提交
1476 1477
    fn chars<'a>(&'a self) -> Chars<'a>;
    fn bytes<'a>(&'a self) -> Bytes<'a>;
A
Alex Crichton 已提交
1478
    fn char_indices<'a>(&'a self) -> CharIndices<'a>;
1479
    fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>;
J
Jake Goulding 已提交
1480 1481
    fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
        where P::Searcher: ReverseSearcher<'a>;
1482
    fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P>;
1483 1484
    fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
        where P::Searcher: ReverseSearcher<'a>;
1485 1486 1487 1488 1489 1490
    fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P>;
    fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
        where P::Searcher: ReverseSearcher<'a>;
    fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P>;
    fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
        where P::Searcher: ReverseSearcher<'a>;
1491
    fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>;
1492 1493
    fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
        where P::Searcher: ReverseSearcher<'a>;
A
Alex Crichton 已提交
1494 1495
    fn lines<'a>(&'a self) -> Lines<'a>;
    fn lines_any<'a>(&'a self) -> LinesAny<'a>;
1496 1497 1498 1499 1500 1501
    fn char_len(&self) -> usize;
    fn slice_chars<'a>(&'a self, begin: usize, end: usize) -> &'a str;
    unsafe fn slice_unchecked<'a>(&'a self, begin: usize, end: usize) -> &'a str;
    fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool;
    fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
        where P::Searcher: ReverseSearcher<'a>;
1502
    fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1503
        where P::Searcher: DoubleEndedSearcher<'a>;
1504 1505
    fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str;
    fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1506 1507 1508 1509 1510 1511
        where P::Searcher: ReverseSearcher<'a>;
    fn is_char_boundary(&self, index: usize) -> bool;
    fn char_range_at(&self, start: usize) -> CharRange;
    fn char_range_at_reverse(&self, start: usize) -> CharRange;
    fn char_at(&self, i: usize) -> char;
    fn char_at_reverse(&self, i: usize) -> char;
J
Jorge Aparicio 已提交
1512
    fn as_bytes<'a>(&'a self) -> &'a [u8];
1513 1514 1515 1516
    fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
    fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
        where P::Searcher: ReverseSearcher<'a>;
    fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
1517
    fn slice_shift_char<'a>(&'a self) -> Option<(char, &'a str)>;
1518
    fn subslice_offset(&self, inner: &str) -> usize;
1519
    fn as_ptr(&self) -> *const u8;
1520
    fn len(&self) -> usize;
A
Alex Crichton 已提交
1521
    fn is_empty(&self) -> bool;
A
Alex Crichton 已提交
1522
    fn parse<T: FromStr>(&self) -> Result<T, T::Err>;
1523 1524
}

1525
#[inline(never)]
1526
fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
1527
    assert!(begin <= end);
S
Steve Klabnik 已提交
1528
    panic!("index {} and/or {} in `{}` do not lie on character boundary",
1529 1530 1531
          begin, end, s);
}

A
Alex Crichton 已提交
1532
impl StrExt for str {
1533
    #[inline]
1534 1535
    fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
        pat.is_contained_in(self)
1536 1537 1538
    }

    #[inline]
1539 1540
    fn contains_char<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
        pat.is_contained_in(self)
1541 1542 1543
    }

    #[inline]
J
Jorge Aparicio 已提交
1544
    fn chars(&self) -> Chars {
1545
        Chars{iter: self.as_bytes().iter()}
1546 1547 1548
    }

    #[inline]
J
Jorge Aparicio 已提交
1549
    fn bytes(&self) -> Bytes {
1550
        Bytes(self.as_bytes().iter().map(BytesDeref))
1551 1552 1553
    }

    #[inline]
A
Alex Crichton 已提交
1554 1555
    fn char_indices(&self) -> CharIndices {
        CharIndices { front_offset: 0, iter: self.chars() }
1556 1557 1558
    }

    #[inline]
1559
    fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1560
        Split(SplitInternal {
1561 1562
            start: 0,
            end: self.len(),
1563
            matcher: pat.into_searcher(self),
1564 1565
            allow_trailing_empty: true,
            finished: false,
1566
        })
1567 1568
    }

1569 1570 1571 1572 1573 1574 1575
    #[inline]
    fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
        where P::Searcher: ReverseSearcher<'a>
    {
        RSplit(self.split(pat).0)
    }

1576
    #[inline]
1577
    fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
1578
        SplitN(SplitNInternal {
1579
            iter: self.split(pat).0,
1580
            count: count,
1581
        })
1582 1583
    }

1584 1585 1586 1587 1588 1589 1590
    #[inline]
    fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
        where P::Searcher: ReverseSearcher<'a>
    {
        RSplitN(self.splitn(count, pat).0)
    }

1591
    #[inline]
1592
    fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1593
        SplitTerminator(SplitInternal {
1594
            allow_trailing_empty: false,
1595 1596
            ..self.split(pat).0
        })
1597 1598
    }

J
Jake Goulding 已提交
1599
    #[inline]
1600
    fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
J
Jake Goulding 已提交
1601 1602
        where P::Searcher: ReverseSearcher<'a>
    {
1603
        RSplitTerminator(self.split_terminator(pat).0)
J
Jake Goulding 已提交
1604 1605
    }

1606
    #[inline]
1607 1608 1609 1610 1611 1612
    fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
        Matches(MatchesInternal(pat.into_searcher(self)))
    }

    #[inline]
    fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1613 1614
        where P::Searcher: ReverseSearcher<'a>
    {
1615
        RMatches(self.matches(pat).0)
1616 1617 1618
    }

    #[inline]
1619
    fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1620
        MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1621 1622
    }

1623 1624 1625 1626 1627 1628
    #[inline]
    fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
        where P::Searcher: ReverseSearcher<'a>
    {
        RMatchIndices(self.match_indices(pat).0)
    }
1629
    #[inline]
A
Alex Crichton 已提交
1630
    fn lines(&self) -> Lines {
1631
        Lines(self.split_terminator('\n'))
1632 1633
    }

1634
    #[inline]
A
Alex Crichton 已提交
1635
    fn lines_any(&self) -> LinesAny {
1636
        LinesAny(self.lines().map(LinesAnyMap))
1637 1638 1639
    }

    #[inline]
1640
    fn char_len(&self) -> usize { self.chars().count() }
1641

1642
    fn slice_chars(&self, begin: usize, end: usize) -> &str {
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
        assert!(begin <= end);
        let mut count = 0;
        let mut begin_byte = None;
        let mut end_byte = None;

        // This could be even more efficient by not decoding,
        // only finding the char boundaries
        for (idx, _) in self.char_indices() {
            if count == begin { begin_byte = Some(idx); }
            if count == end { end_byte = Some(idx); break; }
            count += 1;
        }
        if begin_byte.is_none() && count == begin { begin_byte = Some(self.len()) }
        if end_byte.is_none() && count == end { end_byte = Some(self.len()) }

        match (begin_byte, end_byte) {
S
Steve Klabnik 已提交
1659 1660
            (None, _) => panic!("slice_chars: `begin` is beyond end of string"),
            (_, None) => panic!("slice_chars: `end` is beyond end of string"),
1661
            (Some(a), Some(b)) => unsafe { self.slice_unchecked(a, b) }
1662 1663 1664
        }
    }

1665
    #[inline]
1666
    unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
1667
        mem::transmute(Slice {
1668
            data: self.as_ptr().offset(begin as isize),
1669 1670 1671 1672
            len: end - begin,
        })
    }

1673
    #[inline]
1674
    fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
M
Marvin Löbel 已提交
1675
        pat.is_prefix_of(self)
1676 1677 1678
    }

    #[inline]
1679
    fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
M
Marvin Löbel 已提交
1680 1681 1682
        where P::Searcher: ReverseSearcher<'a>
    {
        pat.is_suffix_of(self)
1683 1684 1685
    }

    #[inline]
1686
    fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
M
Marvin Löbel 已提交
1687 1688
        where P::Searcher: DoubleEndedSearcher<'a>
    {
1689
        let mut i = 0;
M
Marvin Löbel 已提交
1690
        let mut j = 0;
1691
        let mut matcher = pat.into_searcher(self);
1692 1693 1694 1695
        if let Some((a, b)) = matcher.next_reject() {
            i = a;
            j = b; // Rember earliest known match, correct it below if
                   // last match is different
1696
        }
1697 1698
        if let Some((_, b)) = matcher.next_reject_back() {
            j = b;
1699
        }
1700
        unsafe {
1701
            // Searcher is known to return valid indices
1702 1703
            self.slice_unchecked(i, j)
        }
1704 1705 1706
    }

    #[inline]
1707
    fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
M
Marvin Löbel 已提交
1708
        let mut i = self.len();
1709
        let mut matcher = pat.into_searcher(self);
1710 1711
        if let Some((a, _)) = matcher.next_reject() {
            i = a;
1712 1713
        }
        unsafe {
1714
            // Searcher is known to return valid indices
1715
            self.slice_unchecked(i, self.len())
1716 1717 1718 1719
        }
    }

    #[inline]
1720
    fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
M
Marvin Löbel 已提交
1721 1722
        where P::Searcher: ReverseSearcher<'a>
    {
M
Marvin Löbel 已提交
1723
        let mut j = 0;
1724
        let mut matcher = pat.into_searcher(self);
1725 1726
        if let Some((_, b)) = matcher.next_reject_back() {
            j = b;
1727
        }
1728
        unsafe {
1729 1730
            // Searcher is known to return valid indices
            self.slice_unchecked(0, j)
1731
        }
1732 1733 1734
    }

    #[inline]
1735
    fn is_char_boundary(&self, index: usize) -> bool {
1736
        if index == self.len() { return true; }
1737 1738
        match self.as_bytes().get(index) {
            None => false,
1739
            Some(&b) => b < 128 || b >= 192,
1740
        }
1741 1742 1743
    }

    #[inline]
1744
    fn char_range_at(&self, i: usize) -> CharRange {
A
Aaron Turon 已提交
1745 1746
        let (c, n) = char_range_at_raw(self.as_bytes(), i);
        CharRange { ch: unsafe { mem::transmute(c) }, next: n }
1747 1748 1749
    }

    #[inline]
1750
    fn char_range_at_reverse(&self, start: usize) -> CharRange {
1751 1752 1753
        let mut prev = start;

        prev = prev.saturating_sub(1);
1754 1755 1756
        if self.as_bytes()[prev] < 128 {
            return CharRange{ch: self.as_bytes()[prev] as char, next: prev}
        }
1757 1758

        // Multibyte case is a fn to allow char_range_at_reverse to inline cleanly
1759
        fn multibyte_char_range_at_reverse(s: &str, mut i: usize) -> CharRange {
1760
            // while there is a previous byte == 10......
R
root 已提交
1761
            while i > 0 && s.as_bytes()[i] & !CONT_MASK == TAG_CONT_U8 {
1762
                i -= 1;
1763 1764
            }

T
Tobias Bucher 已提交
1765 1766 1767
            let first= s.as_bytes()[i];
            let w = UTF8_CHAR_WIDTH[first as usize];
            assert!(w != 0);
1768

T
Tobias Bucher 已提交
1769 1770 1771 1772
            let mut val = utf8_first_byte(first, w as u32);
            val = utf8_acc_cont_byte(val, s.as_bytes()[i + 1]);
            if w > 2 { val = utf8_acc_cont_byte(val, s.as_bytes()[i + 2]); }
            if w > 3 { val = utf8_acc_cont_byte(val, s.as_bytes()[i + 3]); }
1773

A
Alex Crichton 已提交
1774
            return CharRange {ch: unsafe { mem::transmute(val) }, next: i};
1775 1776
        }

J
Jorge Aparicio 已提交
1777
        return multibyte_char_range_at_reverse(self, prev);
1778 1779 1780
    }

    #[inline]
1781
    fn char_at(&self, i: usize) -> char {
1782 1783 1784 1785
        self.char_range_at(i).ch
    }

    #[inline]
1786
    fn char_at_reverse(&self, i: usize) -> char {
1787 1788 1789 1790
        self.char_range_at_reverse(i).ch
    }

    #[inline]
J
Jorge Aparicio 已提交
1791 1792
    fn as_bytes(&self) -> &[u8] {
        unsafe { mem::transmute(self) }
1793 1794
    }

1795
    fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1796
        pat.into_searcher(self).next_match().map(|(i, _)| i)
1797 1798
    }

1799
    fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
M
Marvin Löbel 已提交
1800 1801
        where P::Searcher: ReverseSearcher<'a>
    {
1802
        pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1803 1804
    }

1805 1806
    fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
        self.find(pat)
1807 1808 1809
    }

    #[inline]
1810
    fn slice_shift_char(&self) -> Option<(char, &str)> {
1811
        if self.is_empty() {
1812
            None
1813
        } else {
1814 1815
            let ch = self.char_at(0);
            let next_s = unsafe { self.slice_unchecked(ch.len_utf8(), self.len()) };
1816
            Some((ch, next_s))
1817 1818 1819
        }
    }

1820 1821
    fn subslice_offset(&self, inner: &str) -> usize {
        let a_start = self.as_ptr() as usize;
1822
        let a_end = a_start + self.len();
1823
        let b_start = inner.as_ptr() as usize;
1824 1825 1826 1827 1828 1829 1830 1831
        let b_end = b_start + inner.len();

        assert!(a_start <= b_start);
        assert!(b_end <= a_end);
        b_start - a_start
    }

    #[inline]
1832
    fn as_ptr(&self) -> *const u8 {
1833 1834
        self.repr().data
    }
J
John Schmidt 已提交
1835 1836

    #[inline]
1837
    fn len(&self) -> usize { self.repr().len }
1838 1839

    #[inline]
A
Alex Crichton 已提交
1840
    fn is_empty(&self) -> bool { self.len() == 0 }
A
Alex Crichton 已提交
1841 1842

    #[inline]
A
Alex Crichton 已提交
1843
    fn parse<T: FromStr>(&self) -> Result<T, T::Err> { FromStr::from_str(self) }
1844 1845
}

S
Sean McArthur 已提交
1846 1847 1848 1849 1850 1851 1852 1853
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<[u8]> for str {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

A
Aaron Turon 已提交
1854 1855 1856
/// Pluck a code point out of a UTF-8-like byte slice and return the
/// index of the next code point.
#[inline]
1857
#[unstable(feature = "core")]
1858
pub fn char_range_at_raw(bytes: &[u8], i: usize) -> (u32, usize) {
1859
    if bytes[i] < 128 {
A
Aaron Turon 已提交
1860 1861 1862 1863
        return (bytes[i] as u32, i + 1);
    }

    // Multibyte case is a fn to allow char_range_at to inline cleanly
1864
    fn multibyte_char_range_at(bytes: &[u8], i: usize) -> (u32, usize) {
T
Tobias Bucher 已提交
1865 1866 1867
        let first = bytes[i];
        let w = UTF8_CHAR_WIDTH[first as usize];
        assert!(w != 0);
A
Aaron Turon 已提交
1868

T
Tobias Bucher 已提交
1869 1870 1871 1872
        let mut val = utf8_first_byte(first, w as u32);
        val = utf8_acc_cont_byte(val, bytes[i + 1]);
        if w > 2 { val = utf8_acc_cont_byte(val, bytes[i + 2]); }
        if w > 3 { val = utf8_acc_cont_byte(val, bytes[i + 3]); }
A
Aaron Turon 已提交
1873

T
Tobias Bucher 已提交
1874
        return (val, i + w as usize);
A
Aaron Turon 已提交
1875 1876 1877 1878 1879
    }

    multibyte_char_range_at(bytes, i)
}

B
Brian Anderson 已提交
1880
#[stable(feature = "rust1", since = "1.0.0")]
1881
impl<'a> Default for &'a str {
B
Brian Anderson 已提交
1882
    #[stable(feature = "rust1", since = "1.0.0")]
1883 1884
    fn default() -> &'a str { "" }
}