string.rs 43.3 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
use core::prelude::*;

17
use core::borrow::{Cow, IntoCow};
18 19 20 21
use core::default::Default;
use core::fmt;
use core::mem;
use core::ptr;
22
use core::ops;
23
// FIXME: ICE's abound if you import the `Slice` type while importing `Slice` trait
24
use core::raw::Slice as RawSlice;
25 26

use hash;
27
use slice::CloneSliceAllocPrelude;
28
use str;
29
use str::{CharRange, CowString, FromStr, StrAllocating, Owned};
30
use vec::{DerefVec, Vec, as_vec};
31

32
/// A growable string stored as a UTF-8 encoded buffer.
J
Jorge Aparicio 已提交
33
#[deriving(Clone, PartialOrd, Eq, Ord)]
A
Alex Crichton 已提交
34
#[stable]
35
pub struct String {
36 37 38
    vec: Vec<u8>,
}

39
impl String {
J
Joseph Crail 已提交
40
    /// Creates a new string buffer initialized with the empty string.
J
Jonas Hietala 已提交
41
    ///
42
    /// # Examples
J
Jonas Hietala 已提交
43 44 45 46
    ///
    /// ```
    /// let mut s = String::new();
    /// ```
47
    #[inline]
A
Alex Crichton 已提交
48
    #[stable]
49 50
    pub fn new() -> String {
        String {
51 52 53 54 55
            vec: Vec::new(),
        }
    }

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

    /// Creates a new string buffer from the given string.
J
Jonas Hietala 已提交
73
    ///
74
    /// # Examples
J
Jonas Hietala 已提交
75 76 77 78 79
    ///
    /// ```
    /// let s = String::from_str("hello");
    /// assert_eq!(s.as_slice(), "hello");
    /// ```
80
    #[inline]
A
Alex Crichton 已提交
81
    #[experimental = "needs investigation to see if to_string() can match perf"]
82
    pub fn from_str(string: &str) -> String {
83
        String { vec: string.as_bytes().to_vec() }
84 85
    }

86 87 88 89 90
    /// 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.
91
    ///
92
    /// # Examples
93 94 95
    ///
    /// ```rust
    /// let hello_vec = vec![104, 101, 108, 108, 111];
J
Jonas Hietala 已提交
96 97 98 99 100 101
    /// 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]));
102
    /// ```
103
    #[inline]
A
Alex Crichton 已提交
104
    #[unstable = "error type may change"]
105
    pub fn from_utf8(vec: Vec<u8>) -> Result<String, Vec<u8>> {
106
        if str::is_utf8(vec.as_slice()) {
107
            Ok(String { vec: vec })
108
        } else {
109
            Err(vec)
110 111
        }
    }
112

P
P1start 已提交
113 114
    /// Converts a vector of bytes to a new UTF-8 string.
    /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
115
    ///
116
    /// # Examples
117 118 119
    ///
    /// ```rust
    /// let input = b"Hello \xF0\x90\x80World";
A
Adolfo Ochagavía 已提交
120
    /// let output = String::from_utf8_lossy(input);
A
Alex Crichton 已提交
121
    /// assert_eq!(output.as_slice(), "Hello \u{FFFD}World");
122
    /// ```
A
Alex Crichton 已提交
123
    #[unstable = "return type may change"]
124
    pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> CowString<'a> {
125
        if str::is_utf8(v) {
126
            return Cow::Borrowed(unsafe { mem::transmute(v) })
127 128 129 130 131 132 133
        }

        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 {
134
            unsafe { *xs.unsafe_get(i) }
135 136 137 138 139 140 141 142 143 144 145 146 147
        }
        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 {
148
                res.as_mut_vec().push_all(v[..i])
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
            };
        }

        // 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_ {
165
                        res.as_mut_vec().push_all(v[subseqidx..i_]);
166 167
                    }
                    subseqidx = i;
168
                    res.as_mut_vec().push_all(REPLACEMENT);
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
                }
            }))

            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)) {
187 188 189 190
                            (0xE0         , 0xA0 ... 0xBF) => (),
                            (0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
                            (0xED         , 0x80 ... 0x9F) => (),
                            (0xEE ... 0xEF, 0x80 ... 0xBF) => (),
191 192 193 194 195 196 197 198 199 200 201 202 203 204
                            _ => {
                                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)) {
205 206 207
                            (0xF0         , 0x90 ... 0xBF) => (),
                            (0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
                            (0xF4         , 0x80 ... 0x8F) => (),
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
                            _ => {
                                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 {
234
                res.as_mut_vec().push_all(v[subseqidx..total])
235 236
            };
        }
237
        Cow::Owned(res.into_string())
238 239
    }

A
Adolfo Ochagavía 已提交
240
    /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
A
Adolfo Ochagavía 已提交
241 242
    /// if `v` contains any invalid data.
    ///
243
    /// # Examples
A
Adolfo Ochagavía 已提交
244 245
    ///
    /// ```rust
A
Adolfo Ochagavía 已提交
246
    /// // 𝄞music
N
Nick Cameron 已提交
247 248
    /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
    ///                   0x0073, 0x0069, 0x0063];
A
Adolfo Ochagavía 已提交
249
    /// assert_eq!(String::from_utf16(v), Some("𝄞music".to_string()));
A
Adolfo Ochagavía 已提交
250
    ///
A
Adolfo Ochagavía 已提交
251
    /// // 𝄞mu<invalid>ic
A
Adolfo Ochagavía 已提交
252 253 254
    /// v[4] = 0xD800;
    /// assert_eq!(String::from_utf16(v), None);
    /// ```
A
Alex Crichton 已提交
255
    #[unstable = "error value in return may change"]
A
Adolfo Ochagavía 已提交
256
    pub fn from_utf16(v: &[u16]) -> Option<String> {
257
        let mut s = String::with_capacity(v.len());
A
Adolfo Ochagavía 已提交
258 259
        for c in str::utf16_items(v) {
            match c {
260
                str::ScalarValue(c) => s.push(c),
A
Adolfo Ochagavía 已提交
261 262 263 264 265
                str::LoneSurrogate(_) => return None
            }
        }
        Some(s)
    }
266

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

P
P1start 已提交
286
    /// Convert a vector of `char`s to a `String`.
A
Adolfo Ochagavía 已提交
287
    ///
288
    /// # Examples
A
Adolfo Ochagavía 已提交
289 290
    ///
    /// ```rust
N
Nick Cameron 已提交
291
    /// let chars = &['h', 'e', 'l', 'l', 'o'];
J
Jonas Hietala 已提交
292 293
    /// let s = String::from_chars(chars);
    /// assert_eq!(s.as_slice(), "hello");
A
Adolfo Ochagavía 已提交
294 295
    /// ```
    #[inline]
A
Alex Crichton 已提交
296
    #[unstable = "may be removed in favor of .collect()"]
A
Adolfo Ochagavía 已提交
297 298 299
    pub fn from_chars(chs: &[char]) -> String {
        chs.iter().map(|c| *c).collect()
    }
300

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    /// Creates a new `String` from a length, capacity, and 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]
    #[unstable = "function just moved from string::raw"]
    pub unsafe fn from_raw_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
        String {
            vec: Vec::from_raw_parts(buf, length, capacity),
        }
    }

    /// Creates a `String` from a null-terminated `*const u8` buffer.
    ///
    /// This function is unsafe because we dereference memory until we find the
    /// NUL character, which is not guaranteed to be present. Additionally, the
    /// slice is not checked to see whether it contains valid UTF-8
    #[unstable = "just renamed from `mod raw`"]
    pub unsafe fn from_raw_buf(buf: *const u8) -> String {
        String::from_str(str::from_c_str(buf as *const i8))
    }

    /// Creates a `String` from a `*const u8` buffer of the given length.
    ///
    /// This function is unsafe because it blindly assumes the validity of the
    /// pointer `buf` for `len` bytes of memory. This function will copy the
    /// memory from `buf` into a new allocation (owned by the returned
    /// `String`).
    ///
    /// This function is also unsafe because it does not validate that the
    /// buffer is valid UTF-8 encoded data.
    #[unstable = "just renamed from `mod raw`"]
    pub unsafe fn from_raw_buf_len(buf: *const u8, len: uint) -> String {
        String::from_utf8_unchecked(Vec::from_raw_buf(buf, len))
    }

    /// 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]
    #[unstable = "awaiting stabilization"]
    pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
        String { vec: bytes }
    }

347
    /// Return the underlying byte buffer, encoded as UTF-8.
J
Jonas Hietala 已提交
348
    ///
349
    /// # Examples
J
Jonas Hietala 已提交
350 351 352 353 354 355
    ///
    /// ```
    /// let s = String::from_str("hello");
    /// let bytes = s.into_bytes();
    /// assert_eq!(bytes, vec![104, 101, 108, 108, 111]);
    /// ```
356
    #[inline]
A
Alex Crichton 已提交
357
    #[stable]
358 359 360 361
    pub fn into_bytes(self) -> Vec<u8> {
        self.vec
    }

362
    /// Creates a string buffer by repeating a character `length` times.
J
Jonas Hietala 已提交
363
    ///
364
    /// # Examples
J
Jonas Hietala 已提交
365 366 367 368 369
    ///
    /// ```
    /// let s = String::from_char(5, 'a');
    /// assert_eq!(s.as_slice(), "aaaaa");
    /// ```
370
    #[inline]
A
Alex Crichton 已提交
371 372
    #[unstable = "may be replaced with iterators, questionable usability, and \
                  the name may change"]
373
    pub fn from_char(length: uint, ch: char) -> String {
374
        if length == 0 {
375
            return String::new()
376 377
        }

378
        let mut buf = String::new();
379
        buf.push(ch);
380 381
        let size = buf.len() * (length - 1);
        buf.reserve_exact(size);
382
        for _ in range(1, length) {
383
            buf.push(ch)
384 385 386 387 388
        }
        buf
    }

    /// Pushes the given string onto this string buffer.
J
Jonas Hietala 已提交
389
    ///
390
    /// # Examples
J
Jonas Hietala 已提交
391 392 393 394 395 396
    ///
    /// ```
    /// let mut s = String::from_str("foo");
    /// s.push_str("bar");
    /// assert_eq!(s.as_slice(), "foobar");
    /// ```
397
    #[inline]
A
Alex Crichton 已提交
398
    #[unstable = "extra variants of `push`, could possibly be based on iterators"]
399 400 401 402
    pub fn push_str(&mut self, string: &str) {
        self.vec.push_all(string.as_bytes())
    }

P
P1start 已提交
403
    /// Pushes `ch` onto the given string `count` times.
J
Jonas Hietala 已提交
404
    ///
405
    /// # Examples
J
Jonas Hietala 已提交
406 407 408 409 410 411
    ///
    /// ```
    /// let mut s = String::from_str("foo");
    /// s.grow(5, 'Z');
    /// assert_eq!(s.as_slice(), "fooZZZZZ");
    /// ```
412
    #[inline]
A
Alex Crichton 已提交
413
    #[unstable = "duplicate of iterator-based functionality"]
414 415
    pub fn grow(&mut self, count: uint, ch: char) {
        for _ in range(0, count) {
416
            self.push(ch)
417 418 419
        }
    }

A
Alex Crichton 已提交
420 421
    /// Returns the number of bytes that this string buffer can hold without reallocating.
    ///
422
    /// # Examples
A
Alex Crichton 已提交
423 424 425
    ///
    /// ```
    /// let s = String::with_capacity(10);
426
    /// assert!(s.capacity() >= 10);
A
Alex Crichton 已提交
427 428
    /// ```
    #[inline]
429
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
A
Alex Crichton 已提交
430 431 432 433
    pub fn capacity(&self) -> uint {
        self.vec.capacity()
    }

434 435
    /// Deprecated: Renamed to `reserve`.
    #[deprecated = "Renamed to `reserve`"]
436
    pub fn reserve_additional(&mut self, extra: uint) {
437
        self.vec.reserve(extra)
438 439
    }

440 441 442 443 444 445
    /// Reserves capacity for at least `additional` more bytes to be inserted in the given
    /// `String`. The collection may reserve more space to avoid frequent reallocations.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `uint`.
J
Jonas Hietala 已提交
446
    ///
447
    /// # Examples
J
Jonas Hietala 已提交
448 449 450 451
    ///
    /// ```
    /// let mut s = String::new();
    /// s.reserve(10);
452
    /// assert!(s.capacity() >= 10);
J
Jonas Hietala 已提交
453
    /// ```
454
    #[inline]
455 456 457
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn reserve(&mut self, additional: uint) {
        self.vec.reserve(additional)
458 459
    }

460 461 462 463 464 465 466 467 468 469
    /// Reserves the minimum capacity for exactly `additional` more bytes to be inserted in the
    /// given `String`. Does nothing if the capacity is already sufficient.
    ///
    /// Note that the allocator may give the collection more space than it requests. Therefore
    /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
    /// insertions are expected.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `uint`.
J
Jonas Hietala 已提交
470
    ///
471
    /// # Examples
J
Jonas Hietala 已提交
472 473 474
    ///
    /// ```
    /// let mut s = String::new();
475 476
    /// s.reserve(10);
    /// assert!(s.capacity() >= 10);
J
Jonas Hietala 已提交
477
    /// ```
478
    #[inline]
479 480 481
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn reserve_exact(&mut self, additional: uint) {
        self.vec.reserve_exact(additional)
482 483 484
    }

    /// Shrinks the capacity of this string buffer to match its length.
J
Jonas Hietala 已提交
485
    ///
486
    /// # Examples
J
Jonas Hietala 已提交
487 488 489 490
    ///
    /// ```
    /// let mut s = String::from_str("foo");
    /// s.reserve(100);
491
    /// assert!(s.capacity() >= 100);
J
Jonas Hietala 已提交
492
    /// s.shrink_to_fit();
493
    /// assert_eq!(s.capacity(), 3);
J
Jonas Hietala 已提交
494
    /// ```
495
    #[inline]
496
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
497 498 499 500 501
    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 已提交
502
    ///
503
    /// # Examples
J
Jonas Hietala 已提交
504 505 506
    ///
    /// ```
    /// let mut s = String::from_str("abc");
A
Alex Crichton 已提交
507 508 509
    /// s.push('1');
    /// s.push('2');
    /// s.push('3');
J
Jonas Hietala 已提交
510 511
    /// assert_eq!(s.as_slice(), "abc123");
    /// ```
512
    #[inline]
S
Squeaky 已提交
513
    #[stable = "function just renamed from push_char"]
A
Alex Crichton 已提交
514
    pub fn push(&mut self, ch: char) {
515
        let cur_len = self.len();
516
        // This may use up to 4 bytes.
517
        self.vec.reserve(4);
518

519
        unsafe {
520 521
            // Attempt to not use an intermediate buffer by just pushing bytes
            // directly onto this string.
522
            let slice = RawSlice {
523 524 525
                data: self.vec.as_ptr().offset(cur_len as int),
                len: 4,
            };
526
            let used = ch.encode_utf8(mem::transmute(slice)).unwrap_or(0);
527 528 529 530 531
            self.vec.set_len(cur_len + used);
        }
    }

    /// Works with the underlying buffer as a byte slice.
J
Jonas Hietala 已提交
532
    ///
533
    /// # Examples
J
Jonas Hietala 已提交
534 535 536
    ///
    /// ```
    /// let s = String::from_str("hello");
N
Nick Cameron 已提交
537 538
    /// let b: &[_] = &[104, 101, 108, 108, 111];
    /// assert_eq!(s.as_bytes(), b);
J
Jonas Hietala 已提交
539
    /// ```
540
    #[inline]
A
Alex Crichton 已提交
541
    #[stable]
542 543 544 545
    pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
        self.vec.as_slice()
    }

P
P1start 已提交
546
    /// Shortens a string to the specified length.
J
Jonas Hietala 已提交
547
    ///
548
    /// # Panics
J
Jonas Hietala 已提交
549
    ///
550
    /// Panics if `new_len` > current length,
551
    /// or if `new_len` is not a character boundary.
J
Jonas Hietala 已提交
552
    ///
553
    /// # Examples
J
Jonas Hietala 已提交
554 555 556 557 558 559
    ///
    /// ```
    /// let mut s = String::from_str("hello");
    /// s.truncate(2);
    /// assert_eq!(s.as_slice(), "he");
    /// ```
560
    #[inline]
S
Steve Klabnik 已提交
561
    #[unstable = "the panic conventions for strings are under development"]
562
    pub fn truncate(&mut self, new_len: uint) {
563
        assert!(self.is_char_boundary(new_len));
564
        self.vec.truncate(new_len)
565 566
    }

J
Jonas Hietala 已提交
567 568 569
    /// Removes the last character from the string buffer and returns it.
    /// Returns `None` if this string buffer is empty.
    ///
570
    /// # Examples
J
Jonas Hietala 已提交
571 572 573
    ///
    /// ```
    /// let mut s = String::from_str("foo");
A
Alex Crichton 已提交
574 575 576 577
    /// assert_eq!(s.pop(), Some('o'));
    /// assert_eq!(s.pop(), Some('o'));
    /// assert_eq!(s.pop(), Some('f'));
    /// assert_eq!(s.pop(), None);
J
Jonas Hietala 已提交
578
    /// ```
579
    #[inline]
A
Alex Crichton 已提交
580 581
    #[unstable = "this function was just renamed from pop_char"]
    pub fn pop(&mut self) -> Option<char> {
582 583 584 585 586
        let len = self.len();
        if len == 0 {
            return None
        }

587
        let CharRange {ch, next} = self.char_range_at_reverse(len);
588 589 590 591 592 593
        unsafe {
            self.vec.set_len(next);
        }
        Some(ch)
    }

594 595
    /// Removes the character from the string buffer at byte position `idx` and
    /// returns it. Returns `None` if `idx` is out of bounds.
596 597 598
    ///
    /// # Warning
    ///
599
    /// This is an O(n) operation as it requires copying every element in the
600 601
    /// buffer.
    ///
S
Steve Klabnik 已提交
602
    /// # Panics
603 604
    ///
    /// If `idx` does not lie on a character boundary, then this function will
S
Steve Klabnik 已提交
605
    /// panic.
J
Jonas Hietala 已提交
606
    ///
607
    /// # Examples
J
Jonas Hietala 已提交
608 609 610
    ///
    /// ```
    /// let mut s = String::from_str("foo");
611 612 613 614
    /// assert_eq!(s.remove(0), Some('f'));
    /// assert_eq!(s.remove(1), Some('o'));
    /// assert_eq!(s.remove(0), Some('o'));
    /// assert_eq!(s.remove(0), None);
J
Jonas Hietala 已提交
615
    /// ```
S
Steve Klabnik 已提交
616
    #[unstable = "the panic semantics of this function and return type \
617 618
                  may change"]
    pub fn remove(&mut self, idx: uint) -> Option<char> {
619
        let len = self.len();
620
        if idx >= len { return None }
621

622
        let CharRange { ch, next } = self.char_range_at(idx);
623
        unsafe {
624 625 626 627
            ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
                             self.vec.as_ptr().offset(next as int),
                             len - next);
            self.vec.set_len(len - (next - idx));
628 629
        }
        Some(ch)
630
    }
631

632 633 634 635
    /// Insert a character into the string buffer at byte position `idx`.
    ///
    /// # Warning
    ///
636
    /// This is an O(n) operation as it requires copying every element in the
637 638
    /// buffer.
    ///
S
Steve Klabnik 已提交
639
    /// # Panics
640 641
    ///
    /// If `idx` does not lie on a character boundary or is out of bounds, then
S
Steve Klabnik 已提交
642 643
    /// this function will panic.
    #[unstable = "the panic semantics of this function are uncertain"]
644 645 646
    pub fn insert(&mut self, idx: uint, ch: char) {
        let len = self.len();
        assert!(idx <= len);
647
        assert!(self.is_char_boundary(idx));
648
        self.vec.reserve(4);
649
        let mut bits = [0, ..4];
N
Nick Cameron 已提交
650
        let amt = ch.encode_utf8(&mut bits).unwrap();
651 652 653 654 655 656 657 658 659 660 661 662

        unsafe {
            ptr::copy_memory(self.vec.as_mut_ptr().offset((idx + amt) as int),
                             self.vec.as_ptr().offset(idx as int),
                             len - idx);
            ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
                             bits.as_ptr(),
                             amt);
            self.vec.set_len(len + amt);
        }
    }

663 664
    /// Views the string buffer as a mutable sequence of bytes.
    ///
J
Jonas Hietala 已提交
665 666 667
    /// This is unsafe because it does not check
    /// to ensure that the resulting string will be valid UTF-8.
    ///
668
    /// # Examples
J
Jonas Hietala 已提交
669 670 671 672 673 674 675 676 677 678
    ///
    /// ```
    /// 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");
    /// ```
A
Alex Crichton 已提交
679
    #[unstable = "the name of this method may be changed"]
680 681 682
    pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
        &mut self.vec
    }
683

684 685
    /// Return the number of bytes in this string.
    ///
686
    /// # Examples
687 688 689 690 691
    ///
    /// ```
    /// let a = "foo".to_string();
    /// assert_eq!(a.len(), 3);
    /// ```
692
    #[inline]
A
Alex Crichton 已提交
693
    #[stable]
694
    pub fn len(&self) -> uint { self.vec.len() }
695

696 697
    /// Returns true if the string contains no bytes
    ///
698
    /// # Examples
699 700 701 702 703 704 705 706 707 708 709
    ///
    /// ```
    /// let mut v = String::new();
    /// assert!(v.is_empty());
    /// v.push('a');
    /// assert!(!v.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool { self.len() == 0 }

    /// Truncates the string, returning it to 0 length.
    ///
710
    /// # Examples
711 712 713 714 715 716
    ///
    /// ```
    /// let mut s = "foo".to_string();
    /// s.clear();
    /// assert!(s.is_empty());
    /// ```
717
    #[inline]
A
Alex Crichton 已提交
718
    #[stable]
719
    pub fn clear(&mut self) {
720 721 722 723
        self.vec.clear()
    }
}

A
Alex Crichton 已提交
724
#[experimental = "waiting on FromIterator stabilization"]
725 726 727
impl FromIterator<char> for String {
    fn from_iter<I:Iterator<char>>(iterator: I) -> String {
        let mut buf = String::new();
728 729 730 731 732
        buf.extend(iterator);
        buf
    }
}

733 734 735 736 737 738 739 740 741
#[experimental = "waiting on FromIterator stabilization"]
impl<'a> FromIterator<&'a str> for String {
    fn from_iter<I:Iterator<&'a str>>(iterator: I) -> String {
        let mut buf = String::new();
        buf.extend(iterator);
        buf
    }
}

G
gamazeps 已提交
742 743
#[experimental = "waiting on Extend stabilization"]
impl Extend<char> for String {
744
    fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
745 746
        let (lower_bound, _) = iterator.size_hint();
        self.reserve(lower_bound);
747
        for ch in iterator {
748
            self.push(ch)
749 750 751 752
        }
    }
}

753 754 755 756 757 758 759 760 761 762 763 764
#[experimental = "waiting on Extend stabilization"]
impl<'a> Extend<&'a str> for String {
    fn extend<I: Iterator<&'a str>>(&mut self, mut iterator: I) {
        // A guess that at least one byte per iterator element will be needed.
        let (lower_bound, _) = iterator.size_hint();
        self.reserve(lower_bound);
        for s in iterator {
            self.push_str(s)
        }
    }
}

J
Jorge Aparicio 已提交
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
impl PartialEq for String {
    #[inline]
    fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
    #[inline]
    fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) }
}

macro_rules! impl_eq {
    ($lhs:ty, $rhs: ty) => {
        impl<'a> PartialEq<$rhs> for $lhs {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
            #[inline]
            fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
        }

        impl<'a> PartialEq<$lhs> for $rhs {
            #[inline]
            fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
            #[inline]
            fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
        }

    }
}

impl_eq!(String, &'a str)
impl_eq!(CowString<'a>, String)

impl<'a, 'b> PartialEq<&'b str> for CowString<'a> {
    #[inline]
    fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) }
    #[inline]
    fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) }
}

impl<'a, 'b> PartialEq<CowString<'a>> for &'b str {
    #[inline]
    fn eq(&self, other: &CowString<'a>) -> bool { PartialEq::eq(&**self, &**other) }
    #[inline]
    fn ne(&self, other: &CowString<'a>) -> bool { PartialEq::ne(&**self, &**other) }
}

A
Alex Crichton 已提交
808
#[experimental = "waiting on Str stabilization"]
809
impl Str for String {
810
    #[inline]
A
Alex Crichton 已提交
811
    #[stable]
812 813
    fn as_slice<'a>(&'a self) -> &'a str {
        unsafe {
A
Alex Crichton 已提交
814
            mem::transmute(self.vec.as_slice())
815 816
        }
    }
817
}
818

A
Alex Crichton 已提交
819
#[experimental = "waiting on StrAllocating stabilization"]
820
impl StrAllocating for String {
821
    #[inline]
822
    fn into_string(self) -> String {
823 824
        self
    }
825 826
}

A
Alex Crichton 已提交
827
#[stable]
828 829 830
impl Default for String {
    fn default() -> String {
        String::new()
831 832 833
    }
}

A
Alex Crichton 已提交
834
#[experimental = "waiting on Show stabilization"]
835
impl fmt::Show for String {
836 837 838 839 840
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.as_slice().fmt(f)
    }
}

A
Alex Crichton 已提交
841
#[experimental = "waiting on Hash stabilization"]
842
impl<H: hash::Writer> hash::Hash<H> for String {
843 844 845 846 847 848
    #[inline]
    fn hash(&self, hasher: &mut H) {
        self.as_slice().hash(hasher)
    }
}

J
Jorge Aparicio 已提交
849 850
#[allow(deprecated)]
#[deprecated = "Use overloaded `core::cmp::PartialEq`"]
851
impl<'a, S: Str> Equiv<S> for String {
852 853 854 855 856 857
    #[inline]
    fn equiv(&self, other: &S) -> bool {
        self.as_slice() == other.as_slice()
    }
}

J
Jorge Aparicio 已提交
858 859
// NOTE(stage0): Remove impl after a snapshot
#[cfg(stage0)]
A
Alex Crichton 已提交
860
#[experimental = "waiting on Add stabilization"]
861 862
impl<S: Str> Add<S, String> for String {
    fn add(&self, other: &S) -> String {
863
        let mut s = String::from_str(self.as_slice());
864 865 866 867 868
        s.push_str(other.as_slice());
        return s;
    }
}

J
Jorge Aparicio 已提交
869 870 871 872 873 874 875 876
#[cfg(not(stage0))]  // NOTE(stage0): Remove cfg after a snapshot
impl<'a> Add<&'a str, String> for String {
    fn add(mut self, other: &str) -> String {
        self.push_str(other);
        self
    }
}

877 878 879 880 881 882 883 884
#[cfg(not(stage0))]  // NOTE(stage0): Remove cfg after a snapshot
impl<'a> Add<String, String> for &'a str {
    fn add(self, mut other: String) -> String {
        other.push_str(self);
        other
    }
}

N
Nick Cameron 已提交
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
impl ops::Slice<uint, str> for String {
    #[inline]
    fn as_slice_<'a>(&'a self) -> &'a str {
        self.as_slice()
    }

    #[inline]
    fn slice_from_or_fail<'a>(&'a self, from: &uint) -> &'a str {
        self[][*from..]
    }

    #[inline]
    fn slice_to_or_fail<'a>(&'a self, to: &uint) -> &'a str {
        self[][..*to]
    }

    #[inline]
    fn slice_or_fail<'a>(&'a self, from: &uint, to: &uint) -> &'a str {
        self[][*from..*to]
    }
}
906

907 908 909 910 911
#[experimental = "waiting on Deref stabilization"]
impl ops::Deref<str> for String {
    fn deref<'a>(&'a self) -> &'a str { self.as_slice() }
}

912 913 914 915 916 917 918 919 920 921 922 923 924
/// Wrapper type providing a `&String` reference via `Deref`.
#[experimental]
pub struct DerefString<'a> {
    x: DerefVec<'a, u8>
}

impl<'a> Deref<String> for DerefString<'a> {
    fn deref<'b>(&'b self) -> &'b String {
        unsafe { mem::transmute(&*self.x) }
    }
}

/// Convert a string slice to a wrapper type providing a `&String` reference.
925 926 927 928 929 930 931 932 933 934 935 936 937
///
/// # Examples
///
/// ```
/// use std::string::as_string;
///
/// fn string_consumer(s: String) {
///     assert_eq!(s, "foo".to_string());
/// }
///
/// let string = as_string("foo").clone();
/// string_consumer(string);
/// ```
938 939 940 941 942
#[experimental]
pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
    DerefString { x: as_vec(x.as_bytes()) }
}

B
Brendan Zabarauskas 已提交
943 944 945 946 947 948 949
impl FromStr for String {
    #[inline]
    fn from_str(s: &str) -> Option<String> {
        Some(String::from_str(s))
    }
}

950 951 952 953 954 955
/// Trait for converting a type to a string, consuming it in the process.
pub trait IntoString {
    /// Consume and convert to a string.
    fn into_string(self) -> String;
}

956 957 958 959 960 961 962 963 964 965 966 967 968 969
/// A generic trait for converting a value to a string
pub trait ToString {
    /// Converts the value of `self` to an owned string
    fn to_string(&self) -> String;
}

impl<T: fmt::Show> ToString for T {
    fn to_string(&self) -> String {
        let mut buf = Vec::<u8>::new();
        let _ = format_args!(|args| fmt::write(&mut buf, args), "{}", self);
        String::from_utf8(buf).unwrap()
    }
}

970 971 972 973 974 975 976 977 978 979 980 981
impl IntoCow<'static, String, str> for String {
    fn into_cow(self) -> CowString<'static> {
        Cow::Owned(self)
    }
}

impl<'a> IntoCow<'a, String, str> for &'a str {
    fn into_cow(self) -> CowString<'a> {
        Cow::Borrowed(self)
    }
}

J
Jonas Hietala 已提交
982
/// Unsafe operations
983
#[deprecated]
984 985 986 987
pub mod raw {
    use super::String;
    use vec::Vec;

P
P1start 已提交
988
    /// Creates a new `String` from a length, capacity, and pointer.
989 990
    ///
    /// This is unsafe because:
P
P1start 已提交
991 992
    /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
    /// * We assume that the `Vec` contains valid UTF-8.
993
    #[inline]
994
    #[deprecated = "renamed to String::from_raw_parts"]
A
Adolfo Ochagavía 已提交
995
    pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
996
        String::from_raw_parts(buf, length, capacity)
997 998
    }

P
P1start 已提交
999
    /// Creates a `String` from a `*const u8` buffer of the given length.
1000 1001
    ///
    /// This function is unsafe because of two reasons:
1002
    ///
P
P1start 已提交
1003 1004
    /// * A raw pointer is dereferenced and transmuted to `&[u8]`;
    /// * The slice is not checked to see whether it contains valid UTF-8.
1005
    #[deprecated = "renamed to String::from_raw_buf_len"]
1006
    pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
1007
        String::from_raw_buf_len(buf, len)
1008
    }
A
Adolfo Ochagavía 已提交
1009

P
P1start 已提交
1010
    /// Creates a `String` from a null-terminated `*const u8` buffer.
A
Adolfo Ochagavía 已提交
1011 1012
    ///
    /// This function is unsafe because we dereference memory until we find the NUL character,
J
Joseph Crail 已提交
1013
    /// which is not guaranteed to be present. Additionally, the slice is not checked to see
A
Adolfo Ochagavía 已提交
1014
    /// whether it contains valid UTF-8
1015
    #[deprecated = "renamed to String::from_raw_buf"]
A
Adolfo Ochagavía 已提交
1016
    pub unsafe fn from_buf(buf: *const u8) -> String {
1017
        String::from_raw_buf(buf)
A
Adolfo Ochagavía 已提交
1018 1019 1020 1021
    }

    /// Converts a vector of bytes to a new `String` without checking if
    /// it contains valid UTF-8. This is unsafe because it assumes that
P
P1start 已提交
1022
    /// the UTF-8-ness of the vector has already been validated.
A
Adolfo Ochagavía 已提交
1023
    #[inline]
1024
    #[deprecated = "renamed to String::from_utf8_unchecked"]
A
Adolfo Ochagavía 已提交
1025
    pub unsafe fn from_utf8(bytes: Vec<u8>) -> String {
1026
        String::from_utf8_unchecked(bytes)
A
Adolfo Ochagavía 已提交
1027
    }
1028 1029
}

1030 1031
#[cfg(test)]
mod tests {
1032 1033 1034
    use std::prelude::*;
    use test::Bencher;

1035 1036
    use slice::CloneSliceAllocPrelude;
    use str::{Str, StrPrelude};
1037
    use str;
1038
    use super::{as_string, String, ToString};
A
Adolfo Ochagavía 已提交
1039
    use vec::Vec;
1040

1041 1042 1043 1044 1045 1046
    #[test]
    fn test_as_string() {
        let x = "foo";
        assert_eq!(x, as_string(x).as_slice());
    }

1047 1048 1049 1050 1051
    #[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"));
    }
1052 1053 1054

    #[test]
    fn test_from_utf8() {
N
NODA, Kai 已提交
1055
        let xs = b"hello".to_vec();
A
Adolfo Ochagavía 已提交
1056
        assert_eq!(String::from_utf8(xs), Ok(String::from_str("hello")));
1057

N
NODA, Kai 已提交
1058
        let xs = "ศไทย中华Việt Nam".as_bytes().to_vec();
A
Adolfo Ochagavía 已提交
1059
        assert_eq!(String::from_utf8(xs), Ok(String::from_str("ศไทย中华Việt Nam")));
1060

N
NODA, Kai 已提交
1061
        let xs = b"hello\xFF".to_vec();
1062
        assert_eq!(String::from_utf8(xs),
N
NODA, Kai 已提交
1063
                   Err(b"hello\xFF".to_vec()));
1064 1065 1066 1067 1068
    }

    #[test]
    fn test_from_utf8_lossy() {
        let xs = b"hello";
J
Jorge Aparicio 已提交
1069 1070
        let ys: str::CowString = "hello".into_cow();
        assert_eq!(String::from_utf8_lossy(xs), ys);
1071

A
Adolfo Ochagavía 已提交
1072
        let xs = "ศไทย中华Việt Nam".as_bytes();
J
Jorge Aparicio 已提交
1073 1074
        let ys: str::CowString = "ศไทย中华Việt Nam".into_cow();
        assert_eq!(String::from_utf8_lossy(xs), ys);
1075 1076

        let xs = b"Hello\xC2 There\xFF Goodbye";
A
Adolfo Ochagavía 已提交
1077
        assert_eq!(String::from_utf8_lossy(xs),
A
Alex Crichton 已提交
1078
                   String::from_str("Hello\u{FFFD} There\u{FFFD} Goodbye").into_cow());
1079 1080 1081

        let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
        assert_eq!(String::from_utf8_lossy(xs),
A
Alex Crichton 已提交
1082
                   String::from_str("Hello\u{FFFD}\u{FFFD} There\u{FFFD} Goodbye").into_cow());
1083 1084

        let xs = b"\xF5foo\xF5\x80bar";
A
Adolfo Ochagavía 已提交
1085
        assert_eq!(String::from_utf8_lossy(xs),
A
Alex Crichton 已提交
1086
                   String::from_str("\u{FFFD}foo\u{FFFD}\u{FFFD}bar").into_cow());
1087 1088

        let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
A
Adolfo Ochagavía 已提交
1089
        assert_eq!(String::from_utf8_lossy(xs),
A
Alex Crichton 已提交
1090
                   String::from_str("\u{FFFD}foo\u{FFFD}bar\u{FFFD}baz").into_cow());
1091 1092 1093

        let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
        assert_eq!(String::from_utf8_lossy(xs),
A
Alex Crichton 已提交
1094
                   String::from_str("\u{FFFD}foo\u{FFFD}bar\u{FFFD}\u{FFFD}baz").into_cow());
1095 1096

        let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
A
Alex Crichton 已提交
1097 1098
        assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\
                                               foo\u{10000}bar").into_cow());
1099 1100 1101

        // surrogates
        let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
A
Alex Crichton 已提交
1102 1103
        assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}\u{FFFD}\u{FFFD}foo\
                                               \u{FFFD}\u{FFFD}\u{FFFD}bar").into_cow());
1104 1105
    }

1106 1107 1108
    #[test]
    fn test_from_utf16() {
        let pairs =
A
Adolfo Ochagavía 已提交
1109
            [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"),
1110 1111 1112 1113 1114
              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 已提交
1115
             (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"),
1116 1117 1118 1119 1120 1121 1122
              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 已提交
1123
             (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"),
1124 1125 1126 1127 1128 1129 1130 1131
              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 已提交
1132
             (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"),
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
              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
A
Alex Crichton 已提交
1145
             (String::from_str("\u{20000}"),
1146 1147 1148 1149
              vec![0xD840, 0xDC00])];

        for p in pairs.iter() {
            let (s, u) = (*p).clone();
1150
            let s_as_utf16 = s.utf16_units().collect::<Vec<u16>>();
1151 1152 1153 1154 1155 1156 1157 1158 1159
            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);
1160
            assert_eq!(u_as_string.utf16_units().collect::<Vec<u16>>(), u);
1161 1162 1163 1164 1165 1166 1167
        }
    }

    #[test]
    fn test_utf16_invalid() {
        // completely positive cases tested above.
        // lead + eof
N
Nick Cameron 已提交
1168
        assert_eq!(String::from_utf16(&[0xD800]), None);
1169
        // lead + lead
N
Nick Cameron 已提交
1170
        assert_eq!(String::from_utf16(&[0xD800, 0xD800]), None);
1171 1172

        // isolated trail
N
Nick Cameron 已提交
1173
        assert_eq!(String::from_utf16(&[0x0061, 0xDC00]), None);
1174 1175

        // general
N
Nick Cameron 已提交
1176
        assert_eq!(String::from_utf16(&[0xD800, 0xd801, 0xdc8b, 0xD800]), None);
1177 1178 1179 1180 1181 1182
    }

    #[test]
    fn test_from_utf16_lossy() {
        // completely positive cases tested above.
        // lead + eof
A
Alex Crichton 已提交
1183
        assert_eq!(String::from_utf16_lossy(&[0xD800]), String::from_str("\u{FFFD}"));
1184
        // lead + lead
A
Alex Crichton 已提交
1185 1186
        assert_eq!(String::from_utf16_lossy(&[0xD800, 0xD800]),
                   String::from_str("\u{FFFD}\u{FFFD}"));
1187 1188

        // isolated trail
A
Alex Crichton 已提交
1189
        assert_eq!(String::from_utf16_lossy(&[0x0061, 0xDC00]), String::from_str("a\u{FFFD}"));
1190 1191

        // general
N
Nick Cameron 已提交
1192
        assert_eq!(String::from_utf16_lossy(&[0xD800, 0xd801, 0xdc8b, 0xD800]),
A
Alex Crichton 已提交
1193
                   String::from_str("\u{FFFD}𐒋\u{FFFD}"));
1194
    }
1195

1196 1197 1198 1199 1200 1201 1202 1203
    #[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 已提交
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
    #[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"));
        }
    }

1214 1215
    #[test]
    fn test_push_bytes() {
1216
        let mut s = String::from_str("ABC");
1217
        unsafe {
N
NODA, Kai 已提交
1218
            let mv = s.as_mut_vec();
N
Nick Cameron 已提交
1219
            mv.push_all(&[b'D']);
1220
        }
1221
        assert_eq!(s, "ABCD");
1222 1223 1224 1225
    }

    #[test]
    fn test_push_str() {
1226
        let mut s = String::new();
1227
        s.push_str("");
1228
        assert_eq!(s.slice_from(0), "");
1229
        s.push_str("abc");
1230
        assert_eq!(s.slice_from(0), "abc");
1231
        s.push_str("ประเทศไทย中华Việt Nam");
1232
        assert_eq!(s.slice_from(0), "abcประเทศไทย中华Việt Nam");
1233 1234 1235
    }

    #[test]
1236
    fn test_push() {
1237
        let mut data = String::from_str("ประเทศไทย中");
1238 1239 1240 1241 1242
        data.push('华');
        data.push('b'); // 1 byte
        data.push('¢'); // 2 byte
        data.push('€'); // 3 byte
        data.push('𤭢'); // 4 byte
1243
        assert_eq!(data, "ประเทศไทย中华b¢€𤭢");
1244 1245
    }

1246
    #[test]
N
NODA, Kai 已提交
1247
    fn test_pop() {
1248
        let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
N
NODA, Kai 已提交
1249 1250 1251 1252 1253
        assert_eq!(data.pop().unwrap(), '𤭢'); // 4 bytes
        assert_eq!(data.pop().unwrap(), '€'); // 3 bytes
        assert_eq!(data.pop().unwrap(), '¢'); // 2 bytes
        assert_eq!(data.pop().unwrap(), 'b'); // 1 bytes
        assert_eq!(data.pop().unwrap(), '华');
1254
        assert_eq!(data, "ประเทศไทย中");
1255 1256
    }

1257 1258
    #[test]
    fn test_str_truncate() {
1259
        let mut s = String::from_str("12345");
1260
        s.truncate(5);
1261
        assert_eq!(s, "12345");
1262
        s.truncate(3);
1263
        assert_eq!(s, "123");
1264
        s.truncate(0);
1265
        assert_eq!(s, "");
1266

1267
        let mut s = String::from_str("12345");
1268
        let p = s.as_ptr();
1269 1270
        s.truncate(3);
        s.push_str("6");
1271
        let p_ = s.as_ptr();
1272 1273 1274 1275 1276 1277
        assert_eq!(p_, p);
    }

    #[test]
    #[should_fail]
    fn test_str_truncate_invalid_len() {
1278
        let mut s = String::from_str("12345");
1279 1280 1281 1282 1283 1284
        s.truncate(6);
    }

    #[test]
    #[should_fail]
    fn test_str_truncate_split_codepoint() {
A
Alex Crichton 已提交
1285
        let mut s = String::from_str("\u{FC}"); // ü
1286 1287
        s.truncate(1);
    }
1288 1289 1290

    #[test]
    fn test_str_clear() {
1291
        let mut s = String::from_str("12345");
1292 1293
        s.clear();
        assert_eq!(s.len(), 0);
1294
        assert_eq!(s, "");
1295
    }
1296 1297 1298 1299 1300

    #[test]
    fn test_str_add() {
        let a = String::from_str("12345");
        let b = a + "2";
J
Jorge Aparicio 已提交
1301
        let b = b + "2";
1302
        assert_eq!(b.len(), 7);
1303
        assert_eq!(b, "1234522");
1304
    }
1305

1306 1307 1308 1309 1310
    #[test]
    fn remove() {
        let mut s = "ศไทย中华Việt Nam; foobar".to_string();;
        assert_eq!(s.remove(0), Some('ศ'));
        assert_eq!(s.len(), 33);
1311
        assert_eq!(s, "ไทย中华Việt Nam; foobar");
1312 1313 1314
        assert_eq!(s.remove(33), None);
        assert_eq!(s.remove(300), None);
        assert_eq!(s.remove(17), Some('ệ'));
1315
        assert_eq!(s, "ไทย中华Vit Nam; foobar");
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
    }

    #[test] #[should_fail]
    fn remove_bad() {
        "ศ".to_string().remove(1);
    }

    #[test]
    fn insert() {
        let mut s = "foobar".to_string();
        s.insert(0, 'ệ');
1327
        assert_eq!(s, "ệfoobar");
1328
        s.insert(6, 'ย');
1329
        assert_eq!(s, "ệfooยbar");
1330 1331 1332 1333 1334
    }

    #[test] #[should_fail] fn insert_bad1() { "".to_string().insert(1, 't'); }
    #[test] #[should_fail] fn insert_bad2() { "ệ".to_string().insert(1, 't'); }

1335 1336 1337 1338 1339 1340 1341 1342 1343
    #[test]
    fn test_slicing() {
        let s = "foobar".to_string();
        assert_eq!("foobar", s[]);
        assert_eq!("foo", s[..3]);
        assert_eq!("bar", s[3..]);
        assert_eq!("oob", s[1..4]);
    }

1344 1345
    #[test]
    fn test_simple_types() {
1346 1347 1348 1349 1350 1351 1352 1353
        assert_eq!(1i.to_string(), "1");
        assert_eq!((-1i).to_string(), "-1");
        assert_eq!(200u.to_string(), "200");
        assert_eq!(2u8.to_string(), "2");
        assert_eq!(true.to_string(), "true");
        assert_eq!(false.to_string(), "false");
        assert_eq!(().to_string(), "()");
        assert_eq!(("hi".to_string()).to_string(), "hi");
1354 1355 1356 1357 1358
    }

    #[test]
    fn test_vectors() {
        let x: Vec<int> = vec![];
1359 1360 1361
        assert_eq!(x.to_string(), "[]");
        assert_eq!((vec![1i]).to_string(), "[1]");
        assert_eq!((vec![1i, 2, 3]).to_string(), "[1, 2, 3]");
1362
        assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_string() ==
1363
               "[[], [1], [1, 1]]");
1364 1365
    }

1366 1367 1368 1369 1370 1371 1372
    #[test]
    fn test_from_iterator() {
        let s = "ศไทย中华Việt Nam".to_string();
        let t = "ศไทย中华";
        let u = "Việt Nam";

        let a: String = s.chars().collect();
1373
        assert_eq!(s, a);
1374 1375 1376

        let mut b = t.to_string();
        b.extend(u.chars());
1377 1378 1379 1380 1381 1382 1383 1384
        assert_eq!(s, b);

        let c: String = vec![t, u].into_iter().collect();
        assert_eq!(s, c);

        let mut d = t.to_string();
        d.extend(vec![u].into_iter());
        assert_eq!(s, d);
1385 1386
    }

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
    #[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) {
1416
        let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
        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());
        });
    }
1438
}