string.rs 12.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// 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.

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

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

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

use hash;
22
use str;
23
use str::{CharRange, StrAllocating};
24 25
use vec::Vec;

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

32
impl String {
J
Joseph Crail 已提交
33
    /// Creates a new string buffer initialized with the empty string.
34
    #[inline]
35 36
    pub fn new() -> String {
        String {
37 38 39 40 41 42
            vec: Vec::new(),
        }
    }

    /// Creates a new string buffer with the given capacity.
    #[inline]
43 44
    pub fn with_capacity(capacity: uint) -> String {
        String {
45 46 47 48 49 50
            vec: Vec::with_capacity(capacity),
        }
    }

    /// Creates a new string buffer from length, capacity, and a pointer.
    #[inline]
51 52
    pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut u8) -> String {
        String {
53 54 55 56 57 58
            vec: Vec::from_raw_parts(length, capacity, ptr),
        }
    }

    /// Creates a new string buffer from the given string.
    #[inline]
59 60
    pub fn from_str(string: &str) -> String {
        String {
61 62 63 64
            vec: Vec::from_slice(string.as_bytes())
        }
    }

65 66
    #[allow(missing_doc)]
    #[deprecated = "obsoleted by the removal of ~str"]
67
    #[inline]
68
    pub fn from_owned_str(string: String) -> String {
69
        string
70 71
    }

72 73 74 75 76
    /// 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.
77
    #[inline]
78
    pub fn from_utf8(vec: Vec<u8>) -> Result<String, Vec<u8>> {
79
        if str::is_utf8(vec.as_slice()) {
80
            Ok(String { vec: vec })
81
        } else {
82
            Err(vec)
83 84 85 86 87 88 89 90 91
        }
    }

    /// Return the underlying byte buffer, encoded as UTF-8.
    #[inline]
    pub fn into_bytes(self) -> Vec<u8> {
        self.vec
    }

92 93 94
    /// Pushes the given string onto this buffer; then, returns `self` so that it can be used
    /// again.
    #[inline]
95
    pub fn append(mut self, second: &str) -> String {
96 97 98 99 100 101
        self.push_str(second);
        self
    }

    /// Creates a string buffer by repeating a character `length` times.
    #[inline]
102
    pub fn from_char(length: uint, ch: char) -> String {
103
        if length == 0 {
104
            return String::new()
105 106
        }

107
        let mut buf = String::new();
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
        buf.push_char(ch);
        let size = buf.len() * length;
        buf.reserve(size);
        for _ in range(1, length) {
            buf.push_char(ch)
        }
        buf
    }

    /// Pushes the given string onto this string buffer.
    #[inline]
    pub fn push_str(&mut self, string: &str) {
        self.vec.push_all(string.as_bytes())
    }

123
    /// Push `ch` onto the given string `count` times.
124 125 126 127 128 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
    #[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.
    #[inline]
    pub fn byte_capacity(&self) -> uint {
        self.vec.capacity()
    }

    /// Reserves capacity for at least `extra` additional bytes in this string buffer.
    #[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.
    #[inline]
    pub fn reserve(&mut self, capacity: uint) {
        self.vec.reserve(capacity)
    }

    /// Reserves capacity for exactly `capacity` bytes in this string buffer.
    #[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.
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.vec.shrink_to_fit()
    }

    /// Adds the given character to the end of the string.
    #[inline]
    pub fn push_char(&mut self, ch: char) {
        let cur_len = self.len();
165 166
        // This may use up to 4 bytes.
        self.vec.reserve_additional(4);
167

168
        unsafe {
169 170
            // Attempt to not use an intermediate buffer by just pushing bytes
            // directly onto this string.
171 172 173 174 175
            let slice = Slice {
                data: self.vec.as_ptr().offset(cur_len as int),
                len: 4,
            };
            let used = ch.encode_utf8(mem::transmute(slice));
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
            self.vec.set_len(cur_len + used);
        }
    }

    /// Pushes the given bytes onto this string buffer. This is unsafe because it does not check
    /// to ensure that the resulting string will be valid UTF-8.
    #[inline]
    pub unsafe fn push_bytes(&mut self, bytes: &[u8]) {
        self.vec.push_all(bytes)
    }

    /// Works with the underlying buffer as a byte slice.
    #[inline]
    pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
        self.vec.as_slice()
    }

193 194 195 196 197 198 199
    /// Works with the underlying buffer as a mutable byte slice. Unsafe
    /// because this can be used to violate the UTF-8 property.
    #[inline]
    pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] {
        self.vec.as_mut_slice()
    }

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
    /// Shorten a string to the specified length (which must be <= the current length)
    #[inline]
    pub fn truncate(&mut self, len: uint) {
        assert!(self.as_slice().is_char_boundary(len));
        self.vec.truncate(len)
    }

    /// Appends a byte to this string buffer. The caller must preserve the valid UTF-8 property.
    #[inline]
    pub unsafe fn push_byte(&mut self, byte: u8) {
        self.push_bytes([byte])
    }

    /// Removes the last byte from the string buffer and returns it. Returns `None` if this string
    /// buffer is empty.
    ///
    /// The caller must preserve the valid UTF-8 property.
    #[inline]
    pub unsafe fn pop_byte(&mut self) -> Option<u8> {
        let len = self.len();
        if len == 0 {
            return None
        }

        let byte = self.as_slice()[len - 1];
        self.vec.set_len(len - 1);
        Some(byte)
    }

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    /// Removes the last character from the string buffer and returns it. Returns `None` if this
    /// string buffer is empty.
    #[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)
    }

245 246 247 248 249
    /// Removes the first byte from the string buffer and returns it. Returns `None` if this string
    /// buffer is empty.
    ///
    /// The caller must preserve the valid UTF-8 property.
    pub unsafe fn shift_byte(&mut self) -> Option<u8> {
250 251 252 253 254 255 256 257 258 259
        self.vec.shift()
    }

    /// Removes the first character from the string buffer and returns it. Returns `None` if this
    /// string buffer is empty.
    ///
    /// # Warning
    ///
    /// This is a O(n) operation as it requires copying every element in the buffer.
    pub fn shift_char (&mut self) -> Option<char> {
260 261 262 263 264
        let len = self.len();
        if len == 0 {
            return None
        }

265 266 267 268 269 270 271
        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)
272
    }
273 274 275 276 277 278 279

    /// Views the string buffer as a mutable sequence of bytes.
    ///
    /// Callers must preserve the valid UTF-8 property.
    pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
        &mut self.vec
    }
280 281
}

282
impl Container for String {
283 284 285 286 287 288
    #[inline]
    fn len(&self) -> uint {
        self.vec.len()
    }
}

289
impl Mutable for String {
290 291 292 293 294 295
    #[inline]
    fn clear(&mut self) {
        self.vec.clear()
    }
}

296 297 298
impl FromIterator<char> for String {
    fn from_iter<I:Iterator<char>>(iterator: I) -> String {
        let mut buf = String::new();
299 300 301 302 303
        buf.extend(iterator);
        buf
    }
}

304
impl Extendable<char> for String {
305 306 307 308 309 310 311
    fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
        for ch in iterator {
            self.push_char(ch)
        }
    }
}

312
impl Str for String {
313 314 315
    #[inline]
    fn as_slice<'a>(&'a self) -> &'a str {
        unsafe {
A
Alex Crichton 已提交
316
            mem::transmute(self.vec.as_slice())
317 318
        }
    }
319
}
320

321
impl StrAllocating for String {
322
    #[inline]
323
    fn into_string(self) -> String {
324 325
        self
    }
326 327
}

328 329 330
impl Default for String {
    fn default() -> String {
        String::new()
331 332 333
    }
}

334
impl fmt::Show for String {
335 336 337 338 339
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.as_slice().fmt(f)
    }
}

340
impl<H: hash::Writer> hash::Hash<H> for String {
341 342 343 344 345 346
    #[inline]
    fn hash(&self, hasher: &mut H) {
        self.as_slice().hash(hasher)
    }
}

347
impl<'a, S: Str> Equiv<S> for String {
348 349 350 351 352 353
    #[inline]
    fn equiv(&self, other: &S) -> bool {
        self.as_slice() == other.as_slice()
    }
}

354 355
#[cfg(test)]
mod tests {
356 357 358
    use std::prelude::*;
    use test::Bencher;

359
    use str::{Str, StrSlice};
360
    use super::String;
361 362

    #[bench]
363 364
    fn bench_with_capacity(b: &mut Bencher) {
        b.iter(|| {
365
            String::with_capacity(100)
366 367 368 369
        });
    }

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

    #[test]
    fn test_push_bytes() {
380
        let mut s = String::from_str("ABC");
381 382 383 384 385 386 387 388
        unsafe {
            s.push_bytes([ 'D' as u8 ]);
        }
        assert_eq!(s.as_slice(), "ABCD");
    }

    #[test]
    fn test_push_str() {
389
        let mut s = String::new();
390 391 392 393 394 395 396 397 398 399
        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() {
400
        let mut data = String::from_str("ประเทศไทย中");
401 402 403 404 405 406 407 408
        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¢€𤭢");
    }

409 410
    #[test]
    fn test_pop_char() {
411
        let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
412 413 414 415 416 417 418 419 420 421
        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() {
422
        let mut data = String::from_str("𤭢€¢b华ประเทศไทย中");
423 424 425 426 427 428 429 430
        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(), "ประเทศไทย中");
    }

431 432
    #[test]
    fn test_str_truncate() {
433
        let mut s = String::from_str("12345");
434 435 436 437 438 439 440
        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(), "");

441
        let mut s = String::from_str("12345");
442 443 444 445 446 447 448 449 450 451
        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() {
452
        let mut s = String::from_str("12345");
453 454 455 456 457 458
        s.truncate(6);
    }

    #[test]
    #[should_fail]
    fn test_str_truncate_split_codepoint() {
459
        let mut s = String::from_str("\u00FC"); // ü
460 461
        s.truncate(1);
    }
462 463 464

    #[test]
    fn test_str_clear() {
465
        let mut s = String::from_str("12345");
466 467 468 469
        s.clear();
        assert_eq!(s.len(), 0);
        assert_eq!(s.as_slice(), "");
    }
470
}