string.rs 34.9 KB
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright 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.
10 11
//
// ignore-lexer-test FIXME #15679
12 13 14

//! An owned, growable string that enforces that its contents are valid UTF-8.

15 16 17 18 19 20 21 22
use core::prelude::*;

use core::default::Default;
use core::fmt;
use core::mem;
use core::ptr;
use core::raw::Slice;

23
use {Collection, Mutable, MutableSeq};
24
use hash;
25
use str;
26
use str::{CharRange, StrAllocating, MaybeOwned, Owned, Slice};
27 28
use vec::Vec;

29
/// A growable string stored as a UTF-8 encoded buffer.
30
#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord)]
31
pub struct String {
32 33 34
    vec: Vec<u8>,
}

35
impl String {
J
Joseph Crail 已提交
36
    /// Creates a new string buffer initialized with the empty string.
J
Jonas Hietala 已提交
37 38 39 40 41 42
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::new();
    /// ```
43
    #[inline]
44 45
    pub fn new() -> String {
        String {
46 47 48 49 50
            vec: Vec::new(),
        }
    }

    /// Creates a new string buffer with the given capacity.
J
Jonas Hietala 已提交
51 52 53 54 55 56 57 58
    /// The string will be able to hold exactly `capacity` bytes without
    /// reallocating. If `capacity` is 0, the string will not allocate.
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::with_capacity(10);
    /// ```
59
    #[inline]
60 61
    pub fn with_capacity(capacity: uint) -> String {
        String {
62 63 64 65 66
            vec: Vec::with_capacity(capacity),
        }
    }

    /// Creates a new string buffer from the given string.
J
Jonas Hietala 已提交
67 68 69 70 71 72 73
    ///
    /// # Example
    ///
    /// ```
    /// let s = String::from_str("hello");
    /// assert_eq!(s.as_slice(), "hello");
    /// ```
74
    #[inline]
75 76
    pub fn from_str(string: &str) -> String {
        String {
77 78 79 80
            vec: Vec::from_slice(string.as_bytes())
        }
    }

81 82 83 84
    /// Deprecated. Replaced by `string::raw::from_parts`
    #[inline]
    #[deprecated = "Replaced by string::raw::from_parts"]
    pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut u8) -> String {
A
Adolfo Ochagavía 已提交
85
        raw::from_parts(ptr, length, capacity)
86 87
    }

J
Jonas Hietala 已提交
88
    /// Deprecated.
89
    #[deprecated = "obsoleted by the removal of ~str"]
90
    #[inline]
91
    pub fn from_owned_str(string: String) -> String {
92
        string
93 94
    }

95 96 97 98 99
    /// Returns the vector as a string buffer, if possible, taking care not to
    /// copy it.
    ///
    /// Returns `Err` with the original vector if the vector contains invalid
    /// UTF-8.
100 101 102 103 104
    ///
    /// # Example
    ///
    /// ```rust
    /// let hello_vec = vec![104, 101, 108, 108, 111];
J
Jonas Hietala 已提交
105 106 107 108 109 110
    /// let s = String::from_utf8(hello_vec);
    /// assert_eq!(s, Ok("hello".to_string()));
    ///
    /// let invalid_vec = vec![240, 144, 128];
    /// let s = String::from_utf8(invalid_vec);
    /// assert_eq!(s, Err(vec![240, 144, 128]));
111
    /// ```
112
    #[inline]
113
    pub fn from_utf8(vec: Vec<u8>) -> Result<String, Vec<u8>> {
114
        if str::is_utf8(vec.as_slice()) {
115
            Ok(String { vec: vec })
116
        } else {
117
            Err(vec)
118 119
        }
    }
120 121 122 123 124 125 126 127

    /// Converts a vector of bytes to a new utf-8 string.
    /// Any invalid utf-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
    ///
    /// # Example
    ///
    /// ```rust
    /// let input = b"Hello \xF0\x90\x80World";
A
Adolfo Ochagavía 已提交
128
    /// let output = String::from_utf8_lossy(input);
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
    /// assert_eq!(output.as_slice(), "Hello \uFFFDWorld");
    /// ```
    pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> MaybeOwned<'a> {
        if str::is_utf8(v) {
            return Slice(unsafe { mem::transmute(v) })
        }

        static TAG_CONT_U8: u8 = 128u8;
        static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
        let mut i = 0;
        let total = v.len();
        fn unsafe_get(xs: &[u8], i: uint) -> u8 {
            unsafe { *xs.unsafe_ref(i) }
        }
        fn safe_get(xs: &[u8], i: uint, total: uint) -> u8 {
            if i >= total {
                0
            } else {
                unsafe_get(xs, i)
            }
        }

        let mut res = String::with_capacity(total);

        if i > 0 {
            unsafe {
                res.push_bytes(v.slice_to(i))
            };
        }

        // subseqidx is the index of the first byte of the subsequence we're looking at.
        // It's used to copy a bunch of contiguous good codepoints at once instead of copying
        // them one by one.
        let mut subseqidx = 0;

        while i < total {
            let i_ = i;
            let byte = unsafe_get(v, i);
            i += 1;

            macro_rules! error(() => ({
                unsafe {
                    if subseqidx != i_ {
                        res.push_bytes(v.slice(subseqidx, i_));
                    }
                    subseqidx = i;
                    res.push_bytes(REPLACEMENT);
                }
            }))

            if byte < 128u8 {
                // subseqidx handles this
            } else {
                let w = str::utf8_char_width(byte);

                match w {
                    2 => {
                        if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
                            error!();
                            continue;
                        }
                        i += 1;
                    }
                    3 => {
                        match (byte, safe_get(v, i, total)) {
                            (0xE0        , 0xA0 .. 0xBF) => (),
                            (0xE1 .. 0xEC, 0x80 .. 0xBF) => (),
                            (0xED        , 0x80 .. 0x9F) => (),
                            (0xEE .. 0xEF, 0x80 .. 0xBF) => (),
                            _ => {
                                error!();
                                continue;
                            }
                        }
                        i += 1;
                        if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
                            error!();
                            continue;
                        }
                        i += 1;
                    }
                    4 => {
                        match (byte, safe_get(v, i, total)) {
                            (0xF0        , 0x90 .. 0xBF) => (),
                            (0xF1 .. 0xF3, 0x80 .. 0xBF) => (),
                            (0xF4        , 0x80 .. 0x8F) => (),
                            _ => {
                                error!();
                                continue;
                            }
                        }
                        i += 1;
                        if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
                            error!();
                            continue;
                        }
                        i += 1;
                        if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
                            error!();
                            continue;
                        }
                        i += 1;
                    }
                    _ => {
                        error!();
                        continue;
                    }
                }
            }
        }
        if subseqidx < total {
            unsafe {
                res.push_bytes(v.slice(subseqidx, total))
            };
        }
        Owned(res.into_string())
    }

A
Adolfo Ochagavía 已提交
247
    /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
A
Adolfo Ochagavía 已提交
248 249 250 251 252
    /// if `v` contains any invalid data.
    ///
    /// # Example
    ///
    /// ```rust
A
Adolfo Ochagavía 已提交
253
    /// // 𝄞music
A
Adolfo Ochagavía 已提交
254 255
    /// let mut v = [0xD834, 0xDD1E, 0x006d, 0x0075,
    ///              0x0073, 0x0069, 0x0063];
A
Adolfo Ochagavía 已提交
256
    /// assert_eq!(String::from_utf16(v), Some("𝄞music".to_string()));
A
Adolfo Ochagavía 已提交
257
    ///
A
Adolfo Ochagavía 已提交
258
    /// // 𝄞mu<invalid>ic
A
Adolfo Ochagavía 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271
    /// v[4] = 0xD800;
    /// assert_eq!(String::from_utf16(v), None);
    /// ```
    pub fn from_utf16(v: &[u16]) -> Option<String> {
        let mut s = String::with_capacity(v.len() / 2);
        for c in str::utf16_items(v) {
            match c {
                str::ScalarValue(c) => s.push_char(c),
                str::LoneSurrogate(_) => return None
            }
        }
        Some(s)
    }
272

273 274 275 276 277
    /// Decode a UTF-16 encoded vector `v` into a string, replacing
    /// invalid data with the replacement character (U+FFFD).
    ///
    /// # Example
    /// ```rust
A
Adolfo Ochagavía 已提交
278
    /// // 𝄞mus<invalid>ic<invalid>
279 280 281 282 283
    /// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
    ///          0x0073, 0xDD1E, 0x0069, 0x0063,
    ///          0xD834];
    ///
    /// assert_eq!(String::from_utf16_lossy(v),
A
Adolfo Ochagavía 已提交
284
    ///            "𝄞mus\uFFFDic\uFFFD".to_string());
285 286 287 288
    /// ```
    pub fn from_utf16_lossy(v: &[u16]) -> String {
        str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
    }
A
Adolfo Ochagavía 已提交
289

J
Jonas Hietala 已提交
290
    /// Convert a vector of chars to a string.
A
Adolfo Ochagavía 已提交
291 292 293 294 295
    ///
    /// # Example
    ///
    /// ```rust
    /// let chars = ['h', 'e', 'l', 'l', 'o'];
J
Jonas Hietala 已提交
296 297
    /// let s = String::from_chars(chars);
    /// assert_eq!(s.as_slice(), "hello");
A
Adolfo Ochagavía 已提交
298 299 300 301 302
    /// ```
    #[inline]
    pub fn from_chars(chs: &[char]) -> String {
        chs.iter().map(|c| *c).collect()
    }
303 304

    /// Return the underlying byte buffer, encoded as UTF-8.
J
Jonas Hietala 已提交
305 306 307 308 309 310 311 312
    ///
    /// # Example
    ///
    /// ```
    /// let s = String::from_str("hello");
    /// let bytes = s.into_bytes();
    /// assert_eq!(bytes, vec![104, 101, 108, 108, 111]);
    /// ```
313 314 315 316 317
    #[inline]
    pub fn into_bytes(self) -> Vec<u8> {
        self.vec
    }

318 319
    /// Pushes the given string onto this buffer; then, returns `self` so that it can be used
    /// again.
J
Jonas Hietala 已提交
320 321 322 323 324 325 326 327 328 329
    ///
    /// # Example
    ///
    /// ```
    /// let s = String::from_str("hello");
    /// let big = s.append(" ").append("world").append("!");
    /// // s has now been moved and cannot be used
    ///
    /// assert_eq!(big.as_slice(), "hello world!");
    /// ```
330
    #[inline]
331
    pub fn append(mut self, second: &str) -> String {
332 333 334 335 336
        self.push_str(second);
        self
    }

    /// Creates a string buffer by repeating a character `length` times.
J
Jonas Hietala 已提交
337 338 339 340 341 342 343
    ///
    /// # Example
    ///
    /// ```
    /// let s = String::from_char(5, 'a');
    /// assert_eq!(s.as_slice(), "aaaaa");
    /// ```
344
    #[inline]
345
    pub fn from_char(length: uint, ch: char) -> String {
346
        if length == 0 {
347
            return String::new()
348 349
        }

350
        let mut buf = String::new();
351 352 353 354 355 356 357 358 359
        buf.push_char(ch);
        let size = buf.len() * length;
        buf.reserve(size);
        for _ in range(1, length) {
            buf.push_char(ch)
        }
        buf
    }

J
Jonas Hietala 已提交
360
    /// Convert a byte to a UTF-8 string.
A
Adolfo Ochagavía 已提交
361 362 363 364 365 366 367 368
    ///
    /// # Failure
    ///
    /// Fails if invalid UTF-8
    ///
    /// # Example
    ///
    /// ```rust
J
Jonas Hietala 已提交
369 370
    /// let s = String::from_byte(104);
    /// assert_eq!(s.as_slice(), "h");
A
Adolfo Ochagavía 已提交
371 372 373 374 375 376
    /// ```
    pub fn from_byte(b: u8) -> String {
        assert!(b < 128u8);
        String::from_char(1, b as char)
    }

377
    /// Pushes the given string onto this string buffer.
J
Jonas Hietala 已提交
378 379 380 381 382 383 384 385
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::from_str("foo");
    /// s.push_str("bar");
    /// assert_eq!(s.as_slice(), "foobar");
    /// ```
386 387 388 389 390
    #[inline]
    pub fn push_str(&mut self, string: &str) {
        self.vec.push_all(string.as_bytes())
    }

391
    /// Push `ch` onto the given string `count` times.
J
Jonas Hietala 已提交
392 393 394 395 396 397 398 399
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::from_str("foo");
    /// s.grow(5, 'Z');
    /// assert_eq!(s.as_slice(), "fooZZZZZ");
    /// ```
400 401 402 403 404 405 406 407
    #[inline]
    pub fn grow(&mut self, count: uint, ch: char) {
        for _ in range(0, count) {
            self.push_char(ch)
        }
    }

    /// Returns the number of bytes that this string buffer can hold without reallocating.
J
Jonas Hietala 已提交
408 409 410 411 412 413 414
    ///
    /// # Example
    ///
    /// ```
    /// let s = String::with_capacity(10);
    /// assert!(s.byte_capacity() >= 10);
    /// ```
415 416 417 418 419 420
    #[inline]
    pub fn byte_capacity(&self) -> uint {
        self.vec.capacity()
    }

    /// Reserves capacity for at least `extra` additional bytes in this string buffer.
J
Jonas Hietala 已提交
421 422 423 424 425 426 427 428 429
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::with_capacity(10);
    /// let before = s.byte_capacity();
    /// s.reserve_additional(100);
    /// assert!(s.byte_capacity() - before >= 100);
    /// ```
430 431 432 433 434 435
    #[inline]
    pub fn reserve_additional(&mut self, extra: uint) {
        self.vec.reserve_additional(extra)
    }

    /// Reserves capacity for at least `capacity` bytes in this string buffer.
J
Jonas Hietala 已提交
436 437 438 439 440 441 442 443
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::new();
    /// s.reserve(10);
    /// assert!(s.byte_capacity() >= 10);
    /// ```
444 445 446 447 448 449
    #[inline]
    pub fn reserve(&mut self, capacity: uint) {
        self.vec.reserve(capacity)
    }

    /// Reserves capacity for exactly `capacity` bytes in this string buffer.
J
Jonas Hietala 已提交
450 451 452 453 454 455 456 457
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::new();
    /// s.reserve_exact(10);
    /// assert_eq!(s.byte_capacity(), 10);
    /// ```
458 459 460 461 462 463
    #[inline]
    pub fn reserve_exact(&mut self, capacity: uint) {
        self.vec.reserve_exact(capacity)
    }

    /// Shrinks the capacity of this string buffer to match its length.
J
Jonas Hietala 已提交
464 465 466 467 468 469 470 471 472 473
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::from_str("foo");
    /// s.reserve(100);
    /// assert!(s.byte_capacity() >= 100);
    /// s.shrink_to_fit();
    /// assert_eq!(s.byte_capacity(), 3);
    /// ```
474 475 476 477 478 479
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.vec.shrink_to_fit()
    }

    /// Adds the given character to the end of the string.
J
Jonas Hietala 已提交
480 481 482 483 484 485 486 487 488 489
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::from_str("abc");
    /// s.push_char('1');
    /// s.push_char('2');
    /// s.push_char('3');
    /// assert_eq!(s.as_slice(), "abc123");
    /// ```
490 491 492
    #[inline]
    pub fn push_char(&mut self, ch: char) {
        let cur_len = self.len();
493 494
        // This may use up to 4 bytes.
        self.vec.reserve_additional(4);
495

496
        unsafe {
497 498
            // Attempt to not use an intermediate buffer by just pushing bytes
            // directly onto this string.
499 500 501 502 503
            let slice = Slice {
                data: self.vec.as_ptr().offset(cur_len as int),
                len: 4,
            };
            let used = ch.encode_utf8(mem::transmute(slice));
504 505 506 507
            self.vec.set_len(cur_len + used);
        }
    }

J
Jonas Hietala 已提交
508 509
    /// Pushes the given bytes onto this string buffer.
    /// This is unsafe because it does not check
510
    /// to ensure that the resulting string will be valid UTF-8.
J
Jonas Hietala 已提交
511 512 513 514 515 516 517 518 519 520
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::new();
    /// unsafe {
    ///     s.push_bytes([104, 101, 108, 108, 111]);
    /// }
    /// assert_eq!(s.as_slice(), "hello");
    /// ```
521 522 523 524 525 526
    #[inline]
    pub unsafe fn push_bytes(&mut self, bytes: &[u8]) {
        self.vec.push_all(bytes)
    }

    /// Works with the underlying buffer as a byte slice.
J
Jonas Hietala 已提交
527 528 529 530 531 532 533
    ///
    /// # Example
    ///
    /// ```
    /// let s = String::from_str("hello");
    /// assert_eq!(s.as_bytes(), &[104, 101, 108, 108, 111]);
    /// ```
534 535 536 537 538
    #[inline]
    pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
        self.vec.as_slice()
    }

J
Jonas Hietala 已提交
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    /// Works with the underlying buffer as a mutable byte slice.
    ///
    /// This is unsafe because it does not check
    /// to ensure that the resulting string will be valid UTF-8.
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::from_str("hello");
    /// unsafe {
    ///     let bytes = s.as_mut_bytes();
    ///     bytes[1] = 51;
    ///     bytes[4] = 48;
    /// }
    /// assert_eq!(s.as_bytes(), &[104, 51, 108, 108, 48]);
    /// assert_eq!(s.as_slice(), "h3ll0")
    /// ```
556 557 558 559 560
    #[inline]
    pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] {
        self.vec.as_mut_slice()
    }

J
Jonas Hietala 已提交
561 562 563 564 565 566 567 568 569 570 571 572 573
    /// Shorten a string to the specified length.
    ///
    /// # Failure
    ///
    /// Fails if `len` > current length.
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::from_str("hello");
    /// s.truncate(2);
    /// assert_eq!(s.as_slice(), "he");
    /// ```
574 575 576 577 578 579
    #[inline]
    pub fn truncate(&mut self, len: uint) {
        assert!(self.as_slice().is_char_boundary(len));
        self.vec.truncate(len)
    }

J
Jonas Hietala 已提交
580 581 582 583 584 585 586 587 588 589 590 591 592 593
    /// Appends a byte to this string buffer.
    ///
    /// This is unsafe because it does not check
    /// to ensure that the resulting string will be valid UTF-8.
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::from_str("hell");
    /// unsafe {
    ///     s.push_byte(111);
    /// }
    /// assert_eq!(s.as_slice(), "hello");
    /// ```
594 595
    #[inline]
    pub unsafe fn push_byte(&mut self, byte: u8) {
S
Simon Sapin 已提交
596
        self.vec.push(byte)
597 598
    }

J
Jonas Hietala 已提交
599 600 601 602 603 604 605
    /// Removes the last byte from the string buffer and returns it.
    /// Returns `None` if this string buffer is empty.
    ///
    /// This is unsafe because it does not check
    /// to ensure that the resulting string will be valid UTF-8.
    ///
    /// # Example
606
    ///
J
Jonas Hietala 已提交
607 608 609 610 611 612 613 614 615
    /// ```
    /// let mut s = String::from_str("foo");
    /// unsafe {
    ///     assert_eq!(s.pop_byte(), Some(111));
    ///     assert_eq!(s.pop_byte(), Some(111));
    ///     assert_eq!(s.pop_byte(), Some(102));
    ///     assert_eq!(s.pop_byte(), None);
    /// }
    /// ```
616 617 618 619 620 621 622
    #[inline]
    pub unsafe fn pop_byte(&mut self) -> Option<u8> {
        let len = self.len();
        if len == 0 {
            return None
        }

623
        let byte = self.as_bytes()[len - 1];
624 625 626 627
        self.vec.set_len(len - 1);
        Some(byte)
    }

J
Jonas Hietala 已提交
628 629 630 631 632 633 634 635 636 637 638 639
    /// Removes the last character from the string buffer and returns it.
    /// Returns `None` if this string buffer is empty.
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::from_str("foo");
    /// assert_eq!(s.pop_char(), Some('o'));
    /// assert_eq!(s.pop_char(), Some('o'));
    /// assert_eq!(s.pop_char(), Some('f'));
    /// assert_eq!(s.pop_char(), None);
    /// ```
640 641 642 643 644 645 646 647 648 649 650 651 652 653
    #[inline]
    pub fn pop_char(&mut self) -> Option<char> {
        let len = self.len();
        if len == 0 {
            return None
        }

        let CharRange {ch, next} = self.as_slice().char_range_at_reverse(len);
        unsafe {
            self.vec.set_len(next);
        }
        Some(ch)
    }

J
Jonas Hietala 已提交
654 655
    /// Removes the first byte from the string buffer and returns it.
    /// Returns `None` if this string buffer is empty.
656
    ///
J
Jonas Hietala 已提交
657 658 659 660 661 662 663 664 665 666 667 668 669 670
    /// This is unsafe because it does not check
    /// to ensure that the resulting string will be valid UTF-8.
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::from_str("foo");
    /// unsafe {
    ///     assert_eq!(s.shift_byte(), Some(102));
    ///     assert_eq!(s.shift_byte(), Some(111));
    ///     assert_eq!(s.shift_byte(), Some(111));
    ///     assert_eq!(s.shift_byte(), None);
    /// }
    /// ```
671
    pub unsafe fn shift_byte(&mut self) -> Option<u8> {
672 673 674
        self.vec.shift()
    }

J
Jonas Hietala 已提交
675 676
    /// Removes the first character from the string buffer and returns it.
    /// Returns `None` if this string buffer is empty.
677 678 679 680
    ///
    /// # Warning
    ///
    /// This is a O(n) operation as it requires copying every element in the buffer.
J
Jonas Hietala 已提交
681 682 683 684 685 686 687 688 689 690
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::from_str("foo");
    /// assert_eq!(s.shift_char(), Some('f'));
    /// assert_eq!(s.shift_char(), Some('o'));
    /// assert_eq!(s.shift_char(), Some('o'));
    /// assert_eq!(s.shift_char(), None);
    /// ```
E
Erick Tryzelaar 已提交
691
    pub fn shift_char(&mut self) -> Option<char> {
692 693 694 695 696
        let len = self.len();
        if len == 0 {
            return None
        }

697 698 699 700 701 702 703
        let CharRange {ch, next} = self.as_slice().char_range_at(0);
        let new_len = len - next;
        unsafe {
            ptr::copy_memory(self.vec.as_mut_ptr(), self.vec.as_ptr().offset(next as int), new_len);
            self.vec.set_len(new_len);
        }
        Some(ch)
704
    }
705 706 707

    /// Views the string buffer as a mutable sequence of bytes.
    ///
J
Jonas Hietala 已提交
708 709 710 711 712 713 714 715 716 717 718 719 720 721
    /// This is unsafe because it does not check
    /// to ensure that the resulting string will be valid UTF-8.
    ///
    /// # Example
    ///
    /// ```
    /// let mut s = String::from_str("hello");
    /// unsafe {
    ///     let vec = s.as_mut_vec();
    ///     assert!(vec == &mut vec![104, 101, 108, 108, 111]);
    ///     vec.reverse();
    /// }
    /// assert_eq!(s.as_slice(), "olleh");
    /// ```
722 723 724
    pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
        &mut self.vec
    }
725 726
}

727
impl Collection for String {
728 729 730 731 732 733
    #[inline]
    fn len(&self) -> uint {
        self.vec.len()
    }
}

734
impl Mutable for String {
735 736 737 738 739 740
    #[inline]
    fn clear(&mut self) {
        self.vec.clear()
    }
}

741 742 743
impl FromIterator<char> for String {
    fn from_iter<I:Iterator<char>>(iterator: I) -> String {
        let mut buf = String::new();
744 745 746 747 748
        buf.extend(iterator);
        buf
    }
}

749
impl Extendable<char> for String {
750 751 752 753 754 755 756
    fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
        for ch in iterator {
            self.push_char(ch)
        }
    }
}

757
impl Str for String {
758 759 760
    #[inline]
    fn as_slice<'a>(&'a self) -> &'a str {
        unsafe {
A
Alex Crichton 已提交
761
            mem::transmute(self.vec.as_slice())
762 763
        }
    }
764
}
765

766
impl StrAllocating for String {
767
    #[inline]
768
    fn into_string(self) -> String {
769 770
        self
    }
771 772
}

773 774 775
impl Default for String {
    fn default() -> String {
        String::new()
776 777 778
    }
}

779
impl fmt::Show for String {
780 781 782 783 784
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.as_slice().fmt(f)
    }
}

785
impl<H: hash::Writer> hash::Hash<H> for String {
786 787 788 789 790 791
    #[inline]
    fn hash(&self, hasher: &mut H) {
        self.as_slice().hash(hasher)
    }
}

792
impl<'a, S: Str> Equiv<S> for String {
793 794 795 796 797 798
    #[inline]
    fn equiv(&self, other: &S) -> bool {
        self.as_slice() == other.as_slice()
    }
}

799 800
impl<S: Str> Add<S, String> for String {
    fn add(&self, other: &S) -> String {
801
        let mut s = String::from_str(self.as_slice());
802 803 804 805 806
        s.push_str(other.as_slice());
        return s;
    }
}

J
Jonas Hietala 已提交
807
/// Unsafe operations
808
pub mod raw {
809
    use core::mem;
A
Adolfo Ochagavía 已提交
810
    use core::ptr::RawPtr;
811 812
    use core::raw::Slice;

813 814 815
    use super::String;
    use vec::Vec;

816 817 818 819 820 821
    /// Creates a new `String` from length, capacity, and a pointer.
    ///
    /// This is unsafe because:
    /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`
    /// * We assume that the `Vec` contains valid UTF-8
    #[inline]
A
Adolfo Ochagavía 已提交
822
    pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
823
        String {
A
Adolfo Ochagavía 已提交
824
            vec: Vec::from_raw_parts(length, capacity, buf),
825 826 827
        }
    }

A
Adolfo Ochagavía 已提交
828
    /// Create `String` from a *u8 buffer of the given length
829 830 831 832 833 834 835 836 837 838 839 840
    ///
    /// This function is unsafe because of two reasons:
    /// * A raw pointer is dereferenced and transmuted to `&[u8]`
    /// * The slice is not checked to see whether it contains valid UTF-8
    pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
        use slice::CloneableVector;
        let slice: &[u8] = mem::transmute(Slice {
            data: buf,
            len: len,
        });
        self::from_utf8(slice.to_vec())
    }
A
Adolfo Ochagavía 已提交
841 842 843 844

    /// Create a `String` from a null-terminated *u8 buffer
    ///
    /// This function is unsafe because we dereference memory until we find the NUL character,
J
Joseph Crail 已提交
845
    /// which is not guaranteed to be present. Additionally, the slice is not checked to see
A
Adolfo Ochagavía 已提交
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    /// whether it contains valid UTF-8
    pub unsafe fn from_buf(buf: *const u8) -> String {
        let mut len = 0;
        while *buf.offset(len) != 0 {
            len += 1;
        }
        self::from_buf_len(buf, len as uint)
    }

    /// Converts a vector of bytes to a new `String` without checking if
    /// it contains valid UTF-8. This is unsafe because it assumes that
    /// the utf-8-ness of the vector has already been validated.
    #[inline]
    pub unsafe fn from_utf8(bytes: Vec<u8>) -> String {
        String { vec: bytes }
    }
862 863
}

864 865
#[cfg(test)]
mod tests {
866 867 868
    use std::prelude::*;
    use test::Bencher;

B
Brian Anderson 已提交
869
    use {Mutable, MutableSeq};
870
    use str;
A
Adolfo Ochagavía 已提交
871
    use str::{Str, StrSlice, Owned, Slice};
872
    use super::String;
A
Adolfo Ochagavía 已提交
873
    use vec::Vec;
874

875 876 877 878 879
    #[test]
    fn test_from_str() {
      let owned: Option<::std::string::String> = from_str("string");
      assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
    }
880 881 882 883

    #[test]
    fn test_from_utf8() {
        let xs = Vec::from_slice(b"hello");
A
Adolfo Ochagavía 已提交
884
        assert_eq!(String::from_utf8(xs), Ok(String::from_str("hello")));
885

A
Adolfo Ochagavía 已提交
886 887
        let xs = Vec::from_slice("ศไทย中华Việt Nam".as_bytes());
        assert_eq!(String::from_utf8(xs), Ok(String::from_str("ศไทย中华Việt Nam")));
888 889 890 891 892 893 894 895 896 897 898

        let xs = Vec::from_slice(b"hello\xFF");
        assert_eq!(String::from_utf8(xs),
                   Err(Vec::from_slice(b"hello\xFF")));
    }

    #[test]
    fn test_from_utf8_lossy() {
        let xs = b"hello";
        assert_eq!(String::from_utf8_lossy(xs), Slice("hello"));

A
Adolfo Ochagavía 已提交
899 900
        let xs = "ศไทย中华Việt Nam".as_bytes();
        assert_eq!(String::from_utf8_lossy(xs), Slice("ศไทย中华Việt Nam"));
901 902

        let xs = b"Hello\xC2 There\xFF Goodbye";
A
Adolfo Ochagavía 已提交
903 904
        assert_eq!(String::from_utf8_lossy(xs),
                   Owned(String::from_str("Hello\uFFFD There\uFFFD Goodbye")));
905 906 907 908 909 910

        let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
        assert_eq!(String::from_utf8_lossy(xs),
                   Owned(String::from_str("Hello\uFFFD\uFFFD There\uFFFD Goodbye")));

        let xs = b"\xF5foo\xF5\x80bar";
A
Adolfo Ochagavía 已提交
911 912
        assert_eq!(String::from_utf8_lossy(xs),
                   Owned(String::from_str("\uFFFDfoo\uFFFD\uFFFDbar")));
913 914

        let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
A
Adolfo Ochagavía 已提交
915 916
        assert_eq!(String::from_utf8_lossy(xs),
                   Owned(String::from_str("\uFFFDfoo\uFFFDbar\uFFFDbaz")));
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931

        let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
        assert_eq!(String::from_utf8_lossy(xs),
                   Owned(String::from_str("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz")));

        let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
        assert_eq!(String::from_utf8_lossy(xs), Owned(String::from_str("\uFFFD\uFFFD\uFFFD\uFFFD\
                                               foo\U00010000bar")));

        // surrogates
        let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
        assert_eq!(String::from_utf8_lossy(xs), Owned(String::from_str("\uFFFD\uFFFD\uFFFDfoo\
                                               \uFFFD\uFFFD\uFFFDbar")));
    }

932 933 934
    #[test]
    fn test_from_utf16() {
        let pairs =
A
Adolfo Ochagavía 已提交
935
            [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"),
936 937 938 939 940
              vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
                0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
                0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
                0xd800_u16, 0xdf30_u16, 0x000a_u16]),

A
Adolfo Ochagavía 已提交
941
             (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"),
942 943 944 945 946 947 948
              vec![0xd801_u16, 0xdc12_u16, 0xd801_u16,
                0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
                0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
                0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16,
                0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16,
                0x000a_u16]),

A
Adolfo Ochagavía 已提交
949
             (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"),
950 951 952 953 954 955 956 957
              vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
                0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
                0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
                0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16,
                0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16,
                0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16,
                0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),

A
Adolfo Ochagavía 已提交
958
             (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"),
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
              vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
                0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
                0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
                0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16,
                0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16,
                0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16,
                0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16,
                0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16,
                0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16,
                0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16,
                0x000a_u16 ]),
             // Issue #12318, even-numbered non-BMP planes
             (String::from_str("\U00020000"),
              vec![0xD840, 0xDC00])];

        for p in pairs.iter() {
            let (s, u) = (*p).clone();
            let s_as_utf16 = s.as_slice().utf16_units().collect::<Vec<u16>>();
            let u_as_string = String::from_utf16(u.as_slice()).unwrap();

            assert!(str::is_utf16(u.as_slice()));
            assert_eq!(s_as_utf16, u);

            assert_eq!(u_as_string, s);
            assert_eq!(String::from_utf16_lossy(u.as_slice()), s);

            assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
            assert_eq!(u_as_string.as_slice().utf16_units().collect::<Vec<u16>>(), u);
        }
    }

    #[test]
    fn test_utf16_invalid() {
        // completely positive cases tested above.
        // lead + eof
        assert_eq!(String::from_utf16([0xD800]), None);
        // lead + lead
        assert_eq!(String::from_utf16([0xD800, 0xD800]), None);

        // isolated trail
        assert_eq!(String::from_utf16([0x0061, 0xDC00]), None);

        // general
        assert_eq!(String::from_utf16([0xD800, 0xd801, 0xdc8b, 0xD800]), None);
    }

    #[test]
    fn test_from_utf16_lossy() {
        // completely positive cases tested above.
        // lead + eof
        assert_eq!(String::from_utf16_lossy([0xD800]), String::from_str("\uFFFD"));
        // lead + lead
        assert_eq!(String::from_utf16_lossy([0xD800, 0xD800]), String::from_str("\uFFFD\uFFFD"));

        // isolated trail
        assert_eq!(String::from_utf16_lossy([0x0061, 0xDC00]), String::from_str("a\uFFFD"));

        // general
        assert_eq!(String::from_utf16_lossy([0xD800, 0xd801, 0xdc8b, 0xD800]),
A
Adolfo Ochagavía 已提交
1018
                   String::from_str("\uFFFD𐒋\uFFFD"));
1019
    }
1020

1021 1022 1023 1024 1025 1026 1027 1028
    #[test]
    fn test_from_buf_len() {
        unsafe {
            let a = vec![65u8, 65, 65, 65, 65, 65, 65, 0];
            assert_eq!(super::raw::from_buf_len(a.as_ptr(), 3), String::from_str("AAA"));
        }
    }

A
Adolfo Ochagavía 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    #[test]
    fn test_from_buf() {
        unsafe {
            let a = vec![65, 65, 65, 65, 65, 65, 65, 0];
            let b = a.as_ptr();
            let c = super::raw::from_buf(b);
            assert_eq!(c, String::from_str("AAAAAAA"));
        }
    }

1039 1040
    #[test]
    fn test_push_bytes() {
1041
        let mut s = String::from_str("ABC");
1042 1043 1044 1045 1046 1047 1048 1049
        unsafe {
            s.push_bytes([ 'D' as u8 ]);
        }
        assert_eq!(s.as_slice(), "ABCD");
    }

    #[test]
    fn test_push_str() {
1050
        let mut s = String::new();
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
        s.push_str("");
        assert_eq!(s.as_slice().slice_from(0), "");
        s.push_str("abc");
        assert_eq!(s.as_slice().slice_from(0), "abc");
        s.push_str("ประเทศไทย中华Việt Nam");
        assert_eq!(s.as_slice().slice_from(0), "abcประเทศไทย中华Việt Nam");
    }

    #[test]
    fn test_push_char() {
1061
        let mut data = String::from_str("ประเทศไทย中");
1062 1063 1064 1065 1066 1067 1068 1069
        data.push_char('华');
        data.push_char('b'); // 1 byte
        data.push_char('¢'); // 2 byte
        data.push_char('€'); // 3 byte
        data.push_char('𤭢'); // 4 byte
        assert_eq!(data.as_slice(), "ประเทศไทย中华b¢€𤭢");
    }

1070 1071
    #[test]
    fn test_pop_char() {
1072
        let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
        assert_eq!(data.pop_char().unwrap(), '𤭢'); // 4 bytes
        assert_eq!(data.pop_char().unwrap(), '€'); // 3 bytes
        assert_eq!(data.pop_char().unwrap(), '¢'); // 2 bytes
        assert_eq!(data.pop_char().unwrap(), 'b'); // 1 bytes
        assert_eq!(data.pop_char().unwrap(), '华');
        assert_eq!(data.as_slice(), "ประเทศไทย中");
    }

    #[test]
    fn test_shift_char() {
1083
        let mut data = String::from_str("𤭢€¢b华ประเทศไทย中");
1084 1085 1086 1087 1088 1089 1090 1091
        assert_eq!(data.shift_char().unwrap(), '𤭢'); // 4 bytes
        assert_eq!(data.shift_char().unwrap(), '€'); // 3 bytes
        assert_eq!(data.shift_char().unwrap(), '¢'); // 2 bytes
        assert_eq!(data.shift_char().unwrap(), 'b'); // 1 bytes
        assert_eq!(data.shift_char().unwrap(), '华');
        assert_eq!(data.as_slice(), "ประเทศไทย中");
    }

1092 1093
    #[test]
    fn test_str_truncate() {
1094
        let mut s = String::from_str("12345");
1095 1096 1097 1098 1099 1100 1101
        s.truncate(5);
        assert_eq!(s.as_slice(), "12345");
        s.truncate(3);
        assert_eq!(s.as_slice(), "123");
        s.truncate(0);
        assert_eq!(s.as_slice(), "");

1102
        let mut s = String::from_str("12345");
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
        let p = s.as_slice().as_ptr();
        s.truncate(3);
        s.push_str("6");
        let p_ = s.as_slice().as_ptr();
        assert_eq!(p_, p);
    }

    #[test]
    #[should_fail]
    fn test_str_truncate_invalid_len() {
1113
        let mut s = String::from_str("12345");
1114 1115 1116 1117 1118 1119
        s.truncate(6);
    }

    #[test]
    #[should_fail]
    fn test_str_truncate_split_codepoint() {
1120
        let mut s = String::from_str("\u00FC"); // ü
1121 1122
        s.truncate(1);
    }
1123 1124 1125

    #[test]
    fn test_str_clear() {
1126
        let mut s = String::from_str("12345");
1127 1128 1129 1130
        s.clear();
        assert_eq!(s.len(), 0);
        assert_eq!(s.as_slice(), "");
    }
1131 1132 1133 1134 1135 1136 1137 1138 1139

    #[test]
    fn test_str_add() {
        let a = String::from_str("12345");
        let b = a + "2";
        let b = b + String::from_str("2");
        assert_eq!(b.len(), 7);
        assert_eq!(b.as_slice(), "1234522");
    }
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169

    #[bench]
    fn bench_with_capacity(b: &mut Bencher) {
        b.iter(|| {
            String::with_capacity(100)
        });
    }

    #[bench]
    fn bench_push_str(b: &mut Bencher) {
        let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
        b.iter(|| {
            let mut r = String::new();
            r.push_str(s);
        });
    }

    #[bench]
    fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
        let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
                  Lorem ipsum dolor sit amet, consectetur. ";

        assert_eq!(100, s.len());
        b.iter(|| {
            let _ = String::from_utf8_lossy(s);
        });
    }

    #[bench]
    fn from_utf8_lossy_100_multibyte(b: &mut Bencher) {
1170
        let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
        assert_eq!(100, s.len());
        b.iter(|| {
            let _ = String::from_utf8_lossy(s);
        });
    }

    #[bench]
    fn from_utf8_lossy_invalid(b: &mut Bencher) {
        let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
        b.iter(|| {
            let _ = String::from_utf8_lossy(s);
        });
    }

    #[bench]
    fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
        let s = Vec::from_elem(100, 0xF5u8);
        b.iter(|| {
            let _ = String::from_utf8_lossy(s.as_slice());
        });
    }
1192
}