1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // ignore-lexer-test FIXME #15679
13 //! An owned, growable string that enforces that its contents are valid UTF-8.
19 use core::borrow::{Cow, IntoCow};
20 use core::default::Default;
21 use core::error::Error;
24 use core::iter::FromIterator;
26 use core::ops::{self, Deref, Add, Index};
28 use core::raw::Slice as RawSlice;
29 use unicode::str as unicode_str;
30 use unicode::str::Utf16Item;
32 use str::{self, CharRange, FromStr, Utf8Error};
33 use vec::{DerefVec, Vec, as_vec};
35 /// A growable string stored as a UTF-8 encoded buffer.
36 #[derive(Clone, PartialOrd, Eq, Ord)]
42 /// A possible error value from the `String::from_utf8` function.
45 pub struct FromUtf8Error {
50 /// A possible error value from the `String::from_utf16` function.
52 #[allow(missing_copy_implementations)]
54 pub struct FromUtf16Error(());
57 /// Creates a new string buffer initialized with the empty string.
62 /// let mut s = String::new();
66 pub fn new() -> String {
72 /// Creates a new string buffer with the given capacity.
73 /// The string will be able to hold exactly `capacity` bytes without
74 /// reallocating. If `capacity` is 0, the string will not allocate.
79 /// let mut s = String::with_capacity(10);
83 pub fn with_capacity(capacity: uint) -> String {
85 vec: Vec::with_capacity(capacity),
89 /// Creates a new string buffer from the given string.
94 /// let s = String::from_str("hello");
95 /// assert_eq!(s.as_slice(), "hello");
98 #[unstable = "needs investigation to see if to_string() can match perf"]
99 pub fn from_str(string: &str) -> String {
100 String { vec: ::slice::SliceExt::to_vec(string.as_bytes()) }
103 /// Returns the vector as a string buffer, if possible, taking care not to
108 /// If the given vector is not valid UTF-8, then the original vector and the
109 /// corresponding error is returned.
114 /// use std::str::Utf8Error;
116 /// let hello_vec = vec![104, 101, 108, 108, 111];
117 /// let s = String::from_utf8(hello_vec).unwrap();
118 /// assert_eq!(s, "hello");
120 /// let invalid_vec = vec![240, 144, 128];
121 /// let s = String::from_utf8(invalid_vec).err().unwrap();
122 /// assert_eq!(s.utf8_error(), Utf8Error::TooShort);
123 /// assert_eq!(s.into_bytes(), vec![240, 144, 128]);
127 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
128 match str::from_utf8(vec.as_slice()) {
129 Ok(..) => Ok(String { vec: vec }),
130 Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
134 /// Converts a vector of bytes to a new UTF-8 string.
135 /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
140 /// let input = b"Hello \xF0\x90\x80World";
141 /// let output = String::from_utf8_lossy(input);
142 /// assert_eq!(output.as_slice(), "Hello \u{FFFD}World");
145 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> CowString<'a> {
147 match str::from_utf8(v) {
148 Ok(s) => return Cow::Borrowed(s),
150 if let Utf8Error::InvalidByte(firstbad) = e {
156 static TAG_CONT_U8: u8 = 128u8;
157 static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
159 fn unsafe_get(xs: &[u8], i: uint) -> u8 {
160 unsafe { *xs.get_unchecked(i) }
162 fn safe_get(xs: &[u8], i: uint, total: uint) -> u8 {
170 let mut res = String::with_capacity(total);
174 res.as_mut_vec().push_all(&v[..i])
178 // subseqidx is the index of the first byte of the subsequence we're looking at.
179 // It's used to copy a bunch of contiguous good codepoints at once instead of copying
181 let mut subseqidx = i;
185 let byte = unsafe_get(v, i);
188 macro_rules! error { () => ({
191 res.as_mut_vec().push_all(&v[subseqidx..i_]);
194 res.as_mut_vec().push_all(REPLACEMENT);
199 // subseqidx handles this
201 let w = unicode_str::utf8_char_width(byte);
205 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
212 match (byte, safe_get(v, i, total)) {
213 (0xE0 , 0xA0 ... 0xBF) => (),
214 (0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
215 (0xED , 0x80 ... 0x9F) => (),
216 (0xEE ... 0xEF, 0x80 ... 0xBF) => (),
223 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
230 match (byte, safe_get(v, i, total)) {
231 (0xF0 , 0x90 ... 0xBF) => (),
232 (0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
233 (0xF4 , 0x80 ... 0x8F) => (),
240 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
245 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
258 if subseqidx < total {
260 res.as_mut_vec().push_all(&v[subseqidx..total])
266 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
267 /// if `v` contains any invalid data.
273 /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
274 /// 0x0073, 0x0069, 0x0063];
275 /// assert_eq!(String::from_utf16(v).unwrap(),
276 /// "𝄞music".to_string());
278 /// // 𝄞mu<invalid>ic
280 /// assert!(String::from_utf16(v).is_err());
283 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
284 let mut s = String::with_capacity(v.len());
285 for c in unicode_str::utf16_items(v) {
287 Utf16Item::ScalarValue(c) => s.push(c),
288 Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())),
294 /// Decode a UTF-16 encoded vector `v` into a string, replacing
295 /// invalid data with the replacement character (U+FFFD).
300 /// // 𝄞mus<invalid>ic<invalid>
301 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
302 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
305 /// assert_eq!(String::from_utf16_lossy(v),
306 /// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
310 pub fn from_utf16_lossy(v: &[u16]) -> String {
311 unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
314 /// Creates a new `String` from a length, capacity, and pointer.
316 /// This is unsafe because:
317 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
318 /// * We assume that the `Vec` contains valid UTF-8.
321 pub unsafe fn from_raw_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
323 vec: Vec::from_raw_parts(buf, length, capacity),
327 /// Converts a vector of bytes to a new `String` without checking if
328 /// it contains valid UTF-8. This is unsafe because it assumes that
329 /// the UTF-8-ness of the vector has already been validated.
332 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
333 String { vec: bytes }
336 /// Return the underlying byte buffer, encoded as UTF-8.
341 /// let s = String::from_str("hello");
342 /// let bytes = s.into_bytes();
343 /// assert_eq!(bytes, vec![104, 101, 108, 108, 111]);
347 pub fn into_bytes(self) -> Vec<u8> {
351 /// Pushes the given string onto this string buffer.
356 /// let mut s = String::from_str("foo");
357 /// s.push_str("bar");
358 /// assert_eq!(s.as_slice(), "foobar");
362 pub fn push_str(&mut self, string: &str) {
363 self.vec.push_all(string.as_bytes())
366 /// Returns the number of bytes that this string buffer can hold without
372 /// let s = String::with_capacity(10);
373 /// assert!(s.capacity() >= 10);
377 pub fn capacity(&self) -> uint {
381 /// Reserves capacity for at least `additional` more bytes to be inserted
382 /// in the given `String`. The collection may reserve more space to avoid
383 /// frequent reallocations.
387 /// Panics if the new capacity overflows `uint`.
392 /// let mut s = String::new();
394 /// assert!(s.capacity() >= 10);
398 pub fn reserve(&mut self, additional: uint) {
399 self.vec.reserve(additional)
402 /// Reserves the minimum capacity for exactly `additional` more bytes to be
403 /// inserted in the given `String`. Does nothing if the capacity is already
406 /// Note that the allocator may give the collection more space than it
407 /// requests. Therefore capacity can not be relied upon to be precisely
408 /// minimal. Prefer `reserve` if future insertions are expected.
412 /// Panics if the new capacity overflows `uint`.
417 /// let mut s = String::new();
419 /// assert!(s.capacity() >= 10);
423 pub fn reserve_exact(&mut self, additional: uint) {
424 self.vec.reserve_exact(additional)
427 /// Shrinks the capacity of this string buffer to match its length.
432 /// let mut s = String::from_str("foo");
434 /// assert!(s.capacity() >= 100);
435 /// s.shrink_to_fit();
436 /// assert_eq!(s.capacity(), 3);
440 pub fn shrink_to_fit(&mut self) {
441 self.vec.shrink_to_fit()
444 /// Adds the given character to the end of the string.
449 /// let mut s = String::from_str("abc");
453 /// assert_eq!(s.as_slice(), "abc123");
457 pub fn push(&mut self, ch: char) {
458 if (ch as u32) < 0x80 {
459 self.vec.push(ch as u8);
463 let cur_len = self.len();
464 // This may use up to 4 bytes.
468 // Attempt to not use an intermediate buffer by just pushing bytes
469 // directly onto this string.
470 let slice = RawSlice {
471 data: self.vec.as_ptr().offset(cur_len as int),
474 let used = ch.encode_utf8(mem::transmute(slice)).unwrap_or(0);
475 self.vec.set_len(cur_len + used);
479 /// Works with the underlying buffer as a byte slice.
484 /// let s = String::from_str("hello");
485 /// let b: &[_] = &[104, 101, 108, 108, 111];
486 /// assert_eq!(s.as_bytes(), b);
490 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
494 /// Shortens a string to the specified length.
498 /// Panics if `new_len` > current length,
499 /// or if `new_len` is not a character boundary.
504 /// let mut s = String::from_str("hello");
506 /// assert_eq!(s.as_slice(), "he");
510 pub fn truncate(&mut self, new_len: uint) {
511 assert!(self.is_char_boundary(new_len));
512 self.vec.truncate(new_len)
515 /// Removes the last character from the string buffer and returns it.
516 /// Returns `None` if this string buffer is empty.
521 /// let mut s = String::from_str("foo");
522 /// assert_eq!(s.pop(), Some('o'));
523 /// assert_eq!(s.pop(), Some('o'));
524 /// assert_eq!(s.pop(), Some('f'));
525 /// assert_eq!(s.pop(), None);
529 pub fn pop(&mut self) -> Option<char> {
530 let len = self.len();
535 let CharRange {ch, next} = self.char_range_at_reverse(len);
537 self.vec.set_len(next);
542 /// Removes the character from the string buffer at byte position `idx` and
547 /// This is an O(n) operation as it requires copying every element in the
552 /// If `idx` does not lie on a character boundary, or if it is out of
553 /// bounds, then this function will panic.
558 /// let mut s = String::from_str("foo");
559 /// assert_eq!(s.remove(0), 'f');
560 /// assert_eq!(s.remove(1), 'o');
561 /// assert_eq!(s.remove(0), 'o');
565 pub fn remove(&mut self, idx: uint) -> char {
566 let len = self.len();
569 let CharRange { ch, next } = self.char_range_at(idx);
571 ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
572 self.vec.as_ptr().offset(next as int),
574 self.vec.set_len(len - (next - idx));
579 /// Insert a character into the string buffer at byte position `idx`.
583 /// This is an O(n) operation as it requires copying every element in the
588 /// If `idx` does not lie on a character boundary or is out of bounds, then
589 /// this function will panic.
592 pub fn insert(&mut self, idx: uint, ch: char) {
593 let len = self.len();
595 assert!(self.is_char_boundary(idx));
597 let mut bits = [0; 4];
598 let amt = ch.encode_utf8(&mut bits).unwrap();
601 ptr::copy_memory(self.vec.as_mut_ptr().offset((idx + amt) as int),
602 self.vec.as_ptr().offset(idx as int),
604 ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
607 self.vec.set_len(len + amt);
611 /// Views the string buffer as a mutable sequence of bytes.
613 /// This is unsafe because it does not check
614 /// to ensure that the resulting string will be valid UTF-8.
619 /// let mut s = String::from_str("hello");
621 /// let vec = s.as_mut_vec();
622 /// assert!(vec == &mut vec![104, 101, 108, 108, 111]);
625 /// assert_eq!(s.as_slice(), "olleh");
629 pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
633 /// Return the number of bytes in this string.
638 /// let a = "foo".to_string();
639 /// assert_eq!(a.len(), 3);
643 pub fn len(&self) -> uint { self.vec.len() }
645 /// Returns true if the string contains no bytes
650 /// let mut v = String::new();
651 /// assert!(v.is_empty());
653 /// assert!(!v.is_empty());
657 pub fn is_empty(&self) -> bool { self.len() == 0 }
659 /// Truncates the string, returning it to 0 length.
664 /// let mut s = "foo".to_string();
666 /// assert!(s.is_empty());
670 pub fn clear(&mut self) {
676 /// Consume this error, returning the bytes that were attempted to make a
679 pub fn into_bytes(self) -> Vec<u8> { self.bytes }
681 /// Access the underlying UTF8-error that was the cause of this error.
683 pub fn utf8_error(&self) -> Utf8Error { self.error }
687 impl fmt::Display for FromUtf8Error {
688 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
689 fmt::Display::fmt(&self.error, f)
694 impl Error for FromUtf8Error {
695 fn description(&self) -> &str { "invalid utf-8" }
699 impl fmt::Display for FromUtf16Error {
700 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
701 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
706 impl Error for FromUtf16Error {
707 fn description(&self) -> &str { "invalid utf-16" }
711 impl FromIterator<char> for String {
712 fn from_iter<I:Iterator<Item=char>>(iterator: I) -> String {
713 let mut buf = String::new();
714 buf.extend(iterator);
720 impl<'a> FromIterator<&'a str> for String {
721 fn from_iter<I:Iterator<Item=&'a str>>(iterator: I) -> String {
722 let mut buf = String::new();
723 buf.extend(iterator);
728 #[unstable = "waiting on Extend stabilization"]
729 impl Extend<char> for String {
730 fn extend<I:Iterator<Item=char>>(&mut self, mut iterator: I) {
731 let (lower_bound, _) = iterator.size_hint();
732 self.reserve(lower_bound);
739 #[unstable = "waiting on Extend stabilization"]
740 impl<'a> Extend<&'a str> for String {
741 fn extend<I: Iterator<Item=&'a str>>(&mut self, mut iterator: I) {
742 // A guess that at least one byte per iterator element will be needed.
743 let (lower_bound, _) = iterator.size_hint();
744 self.reserve(lower_bound);
752 impl PartialEq for String {
754 fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
756 fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) }
759 macro_rules! impl_eq {
760 ($lhs:ty, $rhs: ty) => {
762 impl<'a> PartialEq<$rhs> for $lhs {
764 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
766 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
770 impl<'a> PartialEq<$lhs> for $rhs {
772 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
774 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
780 impl_eq! { String, &'a str }
781 impl_eq! { CowString<'a>, String }
784 impl<'a, 'b> PartialEq<&'b str> for CowString<'a> {
786 fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) }
788 fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) }
792 impl<'a, 'b> PartialEq<CowString<'a>> for &'b str {
794 fn eq(&self, other: &CowString<'a>) -> bool { PartialEq::eq(&**self, &**other) }
796 fn ne(&self, other: &CowString<'a>) -> bool { PartialEq::ne(&**self, &**other) }
799 #[unstable = "waiting on Str stabilization"]
800 impl Str for String {
803 fn as_slice<'a>(&'a self) -> &'a str {
804 unsafe { mem::transmute(self.vec.as_slice()) }
809 impl Default for String {
812 fn default() -> String {
818 impl fmt::Display for String {
820 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
821 fmt::Display::fmt(&**self, f)
826 impl fmt::Debug for String {
828 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
829 fmt::Debug::fmt(&**self, f)
833 #[unstable = "waiting on Hash stabilization"]
834 impl<H: hash::Writer + hash::Hasher> hash::Hash<H> for String {
836 fn hash(&self, hasher: &mut H) {
837 (**self).hash(hasher)
841 #[unstable = "recent addition, needs more experience"]
842 impl<'a> Add<&'a str> for String {
843 type Output = String;
846 fn add(mut self, other: &str) -> String {
847 self.push_str(other);
852 impl ops::Index<ops::Range<uint>> for String {
855 fn index(&self, index: &ops::Range<uint>) -> &str {
859 impl ops::Index<ops::RangeTo<uint>> for String {
862 fn index(&self, index: &ops::RangeTo<uint>) -> &str {
866 impl ops::Index<ops::RangeFrom<uint>> for String {
869 fn index(&self, index: &ops::RangeFrom<uint>) -> &str {
873 impl ops::Index<ops::FullRange> for String {
876 fn index(&self, _index: &ops::FullRange) -> &str {
877 unsafe { mem::transmute(self.vec.as_slice()) }
882 impl ops::Deref for String {
886 fn deref<'a>(&'a self) -> &'a str {
887 unsafe { mem::transmute(&self.vec[]) }
891 /// Wrapper type providing a `&String` reference via `Deref`.
893 pub struct DerefString<'a> {
897 impl<'a> Deref for DerefString<'a> {
898 type Target = String;
901 fn deref<'b>(&'b self) -> &'b String {
902 unsafe { mem::transmute(&*self.x) }
906 /// Convert a string slice to a wrapper type providing a `&String` reference.
911 /// use std::string::as_string;
913 /// fn string_consumer(s: String) {
914 /// assert_eq!(s, "foo".to_string());
917 /// let string = as_string("foo").clone();
918 /// string_consumer(string);
921 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
922 DerefString { x: as_vec(x.as_bytes()) }
925 impl FromStr for String {
927 fn from_str(s: &str) -> Option<String> {
928 Some(String::from_str(s))
932 /// A generic trait for converting a value to a string
934 /// Converts the value of `self` to an owned string
935 fn to_string(&self) -> String;
938 impl<T: fmt::Display + ?Sized> ToString for T {
940 fn to_string(&self) -> String {
941 use core::fmt::Writer;
942 let mut buf = String::new();
943 let _ = buf.write_fmt(format_args!("{}", self));
949 impl IntoCow<'static, String, str> for String {
951 fn into_cow(self) -> CowString<'static> {
956 impl<'a> IntoCow<'a, String, str> for &'a str {
958 fn into_cow(self) -> CowString<'a> {
963 /// A clone-on-write string
965 pub type CowString<'a> = Cow<'a, String, str>;
967 impl<'a> Str for CowString<'a> {
969 fn as_slice<'b>(&'b self) -> &'b str {
974 impl fmt::Writer for String {
976 fn write_str(&mut self, s: &str) -> fmt::Result {
988 use core::iter::repeat;
989 use super::{as_string, CowString};
990 use core::ops::FullRange;
993 fn test_as_string() {
995 assert_eq!(x, as_string(x).as_slice());
1000 let owned: Option<::std::string::String> = "string".parse();
1001 assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
1005 fn test_unsized_to_string() {
1006 let s: &str = "abc";
1007 let _: String = (*s).to_string();
1011 fn test_from_utf8() {
1012 let xs = b"hello".to_vec();
1013 assert_eq!(String::from_utf8(xs).unwrap(),
1014 String::from_str("hello"));
1016 let xs = "ศไทย中华Việt Nam".as_bytes().to_vec();
1017 assert_eq!(String::from_utf8(xs).unwrap(),
1018 String::from_str("ศไทย中华Việt Nam"));
1020 let xs = b"hello\xFF".to_vec();
1021 let err = String::from_utf8(xs).err().unwrap();
1022 assert_eq!(err.utf8_error(), Utf8Error::TooShort);
1023 assert_eq!(err.into_bytes(), b"hello\xff".to_vec());
1027 fn test_from_utf8_lossy() {
1029 let ys: CowString = "hello".into_cow();
1030 assert_eq!(String::from_utf8_lossy(xs), ys);
1032 let xs = "ศไทย中华Việt Nam".as_bytes();
1033 let ys: CowString = "ศไทย中华Việt Nam".into_cow();
1034 assert_eq!(String::from_utf8_lossy(xs), ys);
1036 let xs = b"Hello\xC2 There\xFF Goodbye";
1037 assert_eq!(String::from_utf8_lossy(xs),
1038 String::from_str("Hello\u{FFFD} There\u{FFFD} Goodbye").into_cow());
1040 let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1041 assert_eq!(String::from_utf8_lossy(xs),
1042 String::from_str("Hello\u{FFFD}\u{FFFD} There\u{FFFD} Goodbye").into_cow());
1044 let xs = b"\xF5foo\xF5\x80bar";
1045 assert_eq!(String::from_utf8_lossy(xs),
1046 String::from_str("\u{FFFD}foo\u{FFFD}\u{FFFD}bar").into_cow());
1048 let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
1049 assert_eq!(String::from_utf8_lossy(xs),
1050 String::from_str("\u{FFFD}foo\u{FFFD}bar\u{FFFD}baz").into_cow());
1052 let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
1053 assert_eq!(String::from_utf8_lossy(xs),
1054 String::from_str("\u{FFFD}foo\u{FFFD}bar\u{FFFD}\u{FFFD}baz").into_cow());
1056 let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
1057 assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\
1058 foo\u{10000}bar").into_cow());
1061 let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
1062 assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}\u{FFFD}\u{FFFD}foo\
1063 \u{FFFD}\u{FFFD}\u{FFFD}bar").into_cow());
1067 fn test_from_utf16() {
1069 [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"),
1070 vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
1071 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
1072 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
1073 0xd800_u16, 0xdf30_u16, 0x000a_u16]),
1075 (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"),
1076 vec![0xd801_u16, 0xdc12_u16, 0xd801_u16,
1077 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
1078 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
1079 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16,
1080 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16,
1083 (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"),
1084 vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
1085 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
1086 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
1087 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16,
1088 0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16,
1089 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16,
1090 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),
1092 (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"),
1093 vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
1094 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
1095 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
1096 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16,
1097 0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16,
1098 0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16,
1099 0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16,
1100 0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16,
1101 0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16,
1102 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16,
1104 // Issue #12318, even-numbered non-BMP planes
1105 (String::from_str("\u{20000}"),
1106 vec![0xD840, 0xDC00])];
1108 for p in pairs.iter() {
1109 let (s, u) = (*p).clone();
1110 let s_as_utf16 = s.utf16_units().collect::<Vec<u16>>();
1111 let u_as_string = String::from_utf16(u.as_slice()).unwrap();
1113 assert!(::unicode::str::is_utf16(u.as_slice()));
1114 assert_eq!(s_as_utf16, u);
1116 assert_eq!(u_as_string, s);
1117 assert_eq!(String::from_utf16_lossy(u.as_slice()), s);
1119 assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
1120 assert_eq!(u_as_string.utf16_units().collect::<Vec<u16>>(), u);
1125 fn test_utf16_invalid() {
1126 // completely positive cases tested above.
1128 assert!(String::from_utf16(&[0xD800]).is_err());
1130 assert!(String::from_utf16(&[0xD800, 0xD800]).is_err());
1133 assert!(String::from_utf16(&[0x0061, 0xDC00]).is_err());
1136 assert!(String::from_utf16(&[0xD800, 0xd801, 0xdc8b, 0xD800]).is_err());
1140 fn test_from_utf16_lossy() {
1141 // completely positive cases tested above.
1143 assert_eq!(String::from_utf16_lossy(&[0xD800]), String::from_str("\u{FFFD}"));
1145 assert_eq!(String::from_utf16_lossy(&[0xD800, 0xD800]),
1146 String::from_str("\u{FFFD}\u{FFFD}"));
1149 assert_eq!(String::from_utf16_lossy(&[0x0061, 0xDC00]), String::from_str("a\u{FFFD}"));
1152 assert_eq!(String::from_utf16_lossy(&[0xD800, 0xd801, 0xdc8b, 0xD800]),
1153 String::from_str("\u{FFFD}𐒋\u{FFFD}"));
1157 fn test_push_bytes() {
1158 let mut s = String::from_str("ABC");
1160 let mv = s.as_mut_vec();
1161 mv.push_all(&[b'D']);
1163 assert_eq!(s, "ABCD");
1167 fn test_push_str() {
1168 let mut s = String::new();
1170 assert_eq!(s.slice_from(0), "");
1172 assert_eq!(s.slice_from(0), "abc");
1173 s.push_str("ประเทศไทย中华Việt Nam");
1174 assert_eq!(s.slice_from(0), "abcประเทศไทย中华Việt Nam");
1179 let mut data = String::from_str("ประเทศไทย中");
1181 data.push('b'); // 1 byte
1182 data.push('¢'); // 2 byte
1183 data.push('€'); // 3 byte
1184 data.push('𤭢'); // 4 byte
1185 assert_eq!(data, "ประเทศไทย中华b¢€𤭢");
1190 let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
1191 assert_eq!(data.pop().unwrap(), '𤭢'); // 4 bytes
1192 assert_eq!(data.pop().unwrap(), '€'); // 3 bytes
1193 assert_eq!(data.pop().unwrap(), '¢'); // 2 bytes
1194 assert_eq!(data.pop().unwrap(), 'b'); // 1 bytes
1195 assert_eq!(data.pop().unwrap(), '华');
1196 assert_eq!(data, "ประเทศไทย中");
1200 fn test_str_truncate() {
1201 let mut s = String::from_str("12345");
1203 assert_eq!(s, "12345");
1205 assert_eq!(s, "123");
1209 let mut s = String::from_str("12345");
1213 let p_ = s.as_ptr();
1219 fn test_str_truncate_invalid_len() {
1220 let mut s = String::from_str("12345");
1226 fn test_str_truncate_split_codepoint() {
1227 let mut s = String::from_str("\u{FC}"); // ü
1232 fn test_str_clear() {
1233 let mut s = String::from_str("12345");
1235 assert_eq!(s.len(), 0);
1241 let a = String::from_str("12345");
1244 assert_eq!(b.len(), 7);
1245 assert_eq!(b, "1234522");
1250 let mut s = "ศไทย中华Việt Nam; foobar".to_string();;
1251 assert_eq!(s.remove(0), 'ศ');
1252 assert_eq!(s.len(), 33);
1253 assert_eq!(s, "ไทย中华Việt Nam; foobar");
1254 assert_eq!(s.remove(17), 'ệ');
1255 assert_eq!(s, "ไทย中华Vit Nam; foobar");
1258 #[test] #[should_fail]
1260 "ศ".to_string().remove(1);
1265 let mut s = "foobar".to_string();
1267 assert_eq!(s, "ệfoobar");
1269 assert_eq!(s, "ệfooยbar");
1272 #[test] #[should_fail] fn insert_bad1() { "".to_string().insert(1, 't'); }
1273 #[test] #[should_fail] fn insert_bad2() { "ệ".to_string().insert(1, 't'); }
1277 let s = "foobar".to_string();
1278 assert_eq!("foobar", &s[]);
1279 assert_eq!("foo", &s[..3]);
1280 assert_eq!("bar", &s[3..]);
1281 assert_eq!("oob", &s[1..4]);
1285 fn test_simple_types() {
1286 assert_eq!(1i.to_string(), "1");
1287 assert_eq!((-1i).to_string(), "-1");
1288 assert_eq!(200u.to_string(), "200");
1289 assert_eq!(2u8.to_string(), "2");
1290 assert_eq!(true.to_string(), "true");
1291 assert_eq!(false.to_string(), "false");
1292 assert_eq!(("hi".to_string()).to_string(), "hi");
1297 let x: Vec<int> = vec![];
1298 assert_eq!(format!("{:?}", x), "[]");
1299 assert_eq!(format!("{:?}", vec![1i]), "[1]");
1300 assert_eq!(format!("{:?}", vec![1i, 2, 3]), "[1, 2, 3]");
1301 assert!(format!("{:?}", vec![vec![], vec![1i], vec![1i, 1]]) ==
1302 "[[], [1], [1, 1]]");
1306 fn test_from_iterator() {
1307 let s = "ศไทย中华Việt Nam".to_string();
1311 let a: String = s.chars().collect();
1314 let mut b = t.to_string();
1315 b.extend(u.chars());
1318 let c: String = vec![t, u].into_iter().collect();
1321 let mut d = t.to_string();
1322 d.extend(vec![u].into_iter());
1327 fn bench_with_capacity(b: &mut Bencher) {
1329 String::with_capacity(100)
1334 fn bench_push_str(b: &mut Bencher) {
1335 let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
1337 let mut r = String::new();
1342 const REPETITIONS: u64 = 10_000;
1345 fn bench_push_str_one_byte(b: &mut Bencher) {
1346 b.bytes = REPETITIONS;
1348 let mut r = String::new();
1349 for _ in range(0, REPETITIONS) {
1356 fn bench_push_char_one_byte(b: &mut Bencher) {
1357 b.bytes = REPETITIONS;
1359 let mut r = String::new();
1360 for _ in range(0, REPETITIONS) {
1367 fn bench_push_char_two_bytes(b: &mut Bencher) {
1368 b.bytes = REPETITIONS * 2;
1370 let mut r = String::new();
1371 for _ in range(0, REPETITIONS) {
1378 fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
1379 let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
1380 Lorem ipsum dolor sit amet, consectetur. ";
1382 assert_eq!(100, s.len());
1384 let _ = String::from_utf8_lossy(s);
1389 fn from_utf8_lossy_100_multibyte(b: &mut Bencher) {
1390 let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
1391 assert_eq!(100, s.len());
1393 let _ = String::from_utf8_lossy(s);
1398 fn from_utf8_lossy_invalid(b: &mut Bencher) {
1399 let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1401 let _ = String::from_utf8_lossy(s);
1406 fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
1407 let s = repeat(0xf5u8).take(100).collect::<Vec<_>>();
1409 let _ = String::from_utf8_lossy(s.as_slice());