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;
23 use core::iter::FromIterator;
25 use core::ops::{self, Deref, Add, Index};
27 use core::raw::Slice as RawSlice;
28 use unicode::str as unicode_str;
29 use unicode::str::Utf16Item;
31 use str::{self, CharRange, FromStr, Utf8Error};
32 use vec::{DerefVec, Vec, as_vec};
34 /// A growable string stored as a UTF-8 encoded buffer.
35 #[derive(Clone, PartialOrd, Eq, Ord)]
41 /// A possible error value from the `String::from_utf8` function.
43 pub struct FromUtf8Error {
48 /// A possible error value from the `String::from_utf16` function.
50 #[allow(missing_copy_implementations)]
51 pub struct FromUtf16Error(());
54 /// Creates a new string buffer initialized with the empty string.
59 /// let mut s = String::new();
63 pub fn new() -> String {
69 /// Creates a new string buffer with the given capacity.
70 /// The string will be able to hold exactly `capacity` bytes without
71 /// reallocating. If `capacity` is 0, the string will not allocate.
76 /// let mut s = String::with_capacity(10);
80 pub fn with_capacity(capacity: uint) -> String {
82 vec: Vec::with_capacity(capacity),
86 /// Creates a new string buffer from the given string.
91 /// let s = String::from_str("hello");
92 /// assert_eq!(s.as_slice(), "hello");
95 #[experimental = "needs investigation to see if to_string() can match perf"]
96 pub fn from_str(string: &str) -> String {
97 String { vec: ::slice::SliceExt::to_vec(string.as_bytes()) }
100 /// Returns the vector as a string buffer, if possible, taking care not to
105 /// If the given vector is not valid UTF-8, then the original vector and the
106 /// corresponding error is returned.
111 /// use std::str::Utf8Error;
113 /// let hello_vec = vec![104, 101, 108, 108, 111];
114 /// let s = String::from_utf8(hello_vec).unwrap();
115 /// assert_eq!(s, "hello");
117 /// let invalid_vec = vec![240, 144, 128];
118 /// let s = String::from_utf8(invalid_vec).err().unwrap();
119 /// assert_eq!(s.utf8_error(), Utf8Error::TooShort);
120 /// assert_eq!(s.into_bytes(), vec![240, 144, 128]);
124 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
125 match str::from_utf8(vec.as_slice()) {
126 Ok(..) => Ok(String { vec: vec }),
127 Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
131 /// Converts a vector of bytes to a new UTF-8 string.
132 /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
137 /// let input = b"Hello \xF0\x90\x80World";
138 /// let output = String::from_utf8_lossy(input);
139 /// assert_eq!(output.as_slice(), "Hello \u{FFFD}World");
142 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> CowString<'a> {
144 match str::from_utf8(v) {
145 Ok(s) => return Cow::Borrowed(s),
147 if let Utf8Error::InvalidByte(firstbad) = e {
153 static TAG_CONT_U8: u8 = 128u8;
154 static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
156 fn unsafe_get(xs: &[u8], i: uint) -> u8 {
157 unsafe { *xs.get_unchecked(i) }
159 fn safe_get(xs: &[u8], i: uint, total: uint) -> u8 {
167 let mut res = String::with_capacity(total);
171 res.as_mut_vec().push_all(v.index(&(0..i)))
175 // subseqidx is the index of the first byte of the subsequence we're looking at.
176 // It's used to copy a bunch of contiguous good codepoints at once instead of copying
178 let mut subseqidx = i;
182 let byte = unsafe_get(v, i);
185 macro_rules! error { () => ({
188 res.as_mut_vec().push_all(v.index(&(subseqidx..i_)));
191 res.as_mut_vec().push_all(REPLACEMENT);
196 // subseqidx handles this
198 let w = unicode_str::utf8_char_width(byte);
202 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
209 match (byte, safe_get(v, i, total)) {
210 (0xE0 , 0xA0 ... 0xBF) => (),
211 (0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
212 (0xED , 0x80 ... 0x9F) => (),
213 (0xEE ... 0xEF, 0x80 ... 0xBF) => (),
220 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
227 match (byte, safe_get(v, i, total)) {
228 (0xF0 , 0x90 ... 0xBF) => (),
229 (0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
230 (0xF4 , 0x80 ... 0x8F) => (),
237 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
242 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
255 if subseqidx < total {
257 res.as_mut_vec().push_all(v.index(&(subseqidx..total)))
263 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
264 /// if `v` contains any invalid data.
270 /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
271 /// 0x0073, 0x0069, 0x0063];
272 /// assert_eq!(String::from_utf16(v).unwrap(),
273 /// "𝄞music".to_string());
275 /// // 𝄞mu<invalid>ic
277 /// assert!(String::from_utf16(v).is_err());
280 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
281 let mut s = String::with_capacity(v.len());
282 for c in unicode_str::utf16_items(v) {
284 Utf16Item::ScalarValue(c) => s.push(c),
285 Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())),
291 /// Decode a UTF-16 encoded vector `v` into a string, replacing
292 /// invalid data with the replacement character (U+FFFD).
297 /// // 𝄞mus<invalid>ic<invalid>
298 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
299 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
302 /// assert_eq!(String::from_utf16_lossy(v),
303 /// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
306 pub fn from_utf16_lossy(v: &[u16]) -> String {
307 unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
310 /// Creates a new `String` from a length, capacity, and pointer.
312 /// This is unsafe because:
313 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
314 /// * We assume that the `Vec` contains valid UTF-8.
317 pub unsafe fn from_raw_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
319 vec: Vec::from_raw_parts(buf, length, capacity),
323 /// Converts a vector of bytes to a new `String` without checking if
324 /// it contains valid UTF-8. This is unsafe because it assumes that
325 /// the UTF-8-ness of the vector has already been validated.
328 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
329 String { vec: bytes }
332 /// Return the underlying byte buffer, encoded as UTF-8.
337 /// let s = String::from_str("hello");
338 /// let bytes = s.into_bytes();
339 /// assert_eq!(bytes, vec![104, 101, 108, 108, 111]);
343 pub fn into_bytes(self) -> Vec<u8> {
347 /// Pushes the given string onto this string buffer.
352 /// let mut s = String::from_str("foo");
353 /// s.push_str("bar");
354 /// assert_eq!(s.as_slice(), "foobar");
358 pub fn push_str(&mut self, string: &str) {
359 self.vec.push_all(string.as_bytes())
362 /// Returns the number of bytes that this string buffer can hold without
368 /// let s = String::with_capacity(10);
369 /// assert!(s.capacity() >= 10);
373 pub fn capacity(&self) -> uint {
377 /// Reserves capacity for at least `additional` more bytes to be inserted
378 /// in the given `String`. The collection may reserve more space to avoid
379 /// frequent reallocations.
383 /// Panics if the new capacity overflows `uint`.
388 /// let mut s = String::new();
390 /// assert!(s.capacity() >= 10);
394 pub fn reserve(&mut self, additional: uint) {
395 self.vec.reserve(additional)
398 /// Reserves the minimum capacity for exactly `additional` more bytes to be
399 /// inserted in the given `String`. Does nothing if the capacity is already
402 /// Note that the allocator may give the collection more space than it
403 /// requests. Therefore capacity can not be relied upon to be precisely
404 /// minimal. Prefer `reserve` if future insertions are expected.
408 /// Panics if the new capacity overflows `uint`.
413 /// let mut s = String::new();
415 /// assert!(s.capacity() >= 10);
419 pub fn reserve_exact(&mut self, additional: uint) {
420 self.vec.reserve_exact(additional)
423 /// Shrinks the capacity of this string buffer to match its length.
428 /// let mut s = String::from_str("foo");
430 /// assert!(s.capacity() >= 100);
431 /// s.shrink_to_fit();
432 /// assert_eq!(s.capacity(), 3);
436 pub fn shrink_to_fit(&mut self) {
437 self.vec.shrink_to_fit()
440 /// Adds the given character to the end of the string.
445 /// let mut s = String::from_str("abc");
449 /// assert_eq!(s.as_slice(), "abc123");
453 pub fn push(&mut self, ch: char) {
454 if (ch as u32) < 0x80 {
455 self.vec.push(ch as u8);
459 let cur_len = self.len();
460 // This may use up to 4 bytes.
464 // Attempt to not use an intermediate buffer by just pushing bytes
465 // directly onto this string.
466 let slice = RawSlice {
467 data: self.vec.as_ptr().offset(cur_len as int),
470 let used = ch.encode_utf8(mem::transmute(slice)).unwrap_or(0);
471 self.vec.set_len(cur_len + used);
475 /// Works with the underlying buffer as a byte slice.
480 /// let s = String::from_str("hello");
481 /// let b: &[_] = &[104, 101, 108, 108, 111];
482 /// assert_eq!(s.as_bytes(), b);
486 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
490 /// Shortens a string to the specified length.
494 /// Panics if `new_len` > current length,
495 /// or if `new_len` is not a character boundary.
500 /// let mut s = String::from_str("hello");
502 /// assert_eq!(s.as_slice(), "he");
506 pub fn truncate(&mut self, new_len: uint) {
507 assert!(self.is_char_boundary(new_len));
508 self.vec.truncate(new_len)
511 /// Removes the last character from the string buffer and returns it.
512 /// Returns `None` if this string buffer is empty.
517 /// let mut s = String::from_str("foo");
518 /// assert_eq!(s.pop(), Some('o'));
519 /// assert_eq!(s.pop(), Some('o'));
520 /// assert_eq!(s.pop(), Some('f'));
521 /// assert_eq!(s.pop(), None);
525 pub fn pop(&mut self) -> Option<char> {
526 let len = self.len();
531 let CharRange {ch, next} = self.char_range_at_reverse(len);
533 self.vec.set_len(next);
538 /// Removes the character from the string buffer at byte position `idx` and
543 /// This is an O(n) operation as it requires copying every element in the
548 /// If `idx` does not lie on a character boundary, or if it is out of
549 /// bounds, then this function will panic.
554 /// let mut s = String::from_str("foo");
555 /// assert_eq!(s.remove(0), 'f');
556 /// assert_eq!(s.remove(1), 'o');
557 /// assert_eq!(s.remove(0), 'o');
560 pub fn remove(&mut self, idx: uint) -> char {
561 let len = self.len();
564 let CharRange { ch, next } = self.char_range_at(idx);
566 ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
567 self.vec.as_ptr().offset(next as int),
569 self.vec.set_len(len - (next - idx));
574 /// Insert a character into the string buffer at byte position `idx`.
578 /// This is an O(n) operation as it requires copying every element in the
583 /// If `idx` does not lie on a character boundary or is out of bounds, then
584 /// this function will panic.
586 pub fn insert(&mut self, idx: uint, ch: char) {
587 let len = self.len();
589 assert!(self.is_char_boundary(idx));
591 let mut bits = [0; 4];
592 let amt = ch.encode_utf8(&mut bits).unwrap();
595 ptr::copy_memory(self.vec.as_mut_ptr().offset((idx + amt) as int),
596 self.vec.as_ptr().offset(idx as int),
598 ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
601 self.vec.set_len(len + amt);
605 /// Views the string buffer as a mutable sequence of bytes.
607 /// This is unsafe because it does not check
608 /// to ensure that the resulting string will be valid UTF-8.
613 /// let mut s = String::from_str("hello");
615 /// let vec = s.as_mut_vec();
616 /// assert!(vec == &mut vec![104, 101, 108, 108, 111]);
619 /// assert_eq!(s.as_slice(), "olleh");
622 pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
626 /// Return the number of bytes in this string.
631 /// let a = "foo".to_string();
632 /// assert_eq!(a.len(), 3);
636 pub fn len(&self) -> uint { self.vec.len() }
638 /// Returns true if the string contains no bytes
643 /// let mut v = String::new();
644 /// assert!(v.is_empty());
646 /// assert!(!v.is_empty());
649 pub fn is_empty(&self) -> bool { self.len() == 0 }
651 /// Truncates the string, returning it to 0 length.
656 /// let mut s = "foo".to_string();
658 /// assert!(s.is_empty());
662 pub fn clear(&mut self) {
668 /// Consume this error, returning the bytes that were attempted to make a
671 pub fn into_bytes(self) -> Vec<u8> { self.bytes }
673 /// Access the underlying UTF8-error that was the cause of this error.
675 pub fn utf8_error(&self) -> Utf8Error { self.error }
678 impl fmt::Show for FromUtf8Error {
679 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
680 fmt::String::fmt(self, f)
684 impl fmt::String for FromUtf8Error {
685 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
686 fmt::String::fmt(&self.error, f)
690 impl fmt::Show for FromUtf16Error {
691 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
692 fmt::String::fmt(self, f)
696 impl fmt::String for FromUtf16Error {
697 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
698 fmt::String::fmt("invalid utf-16: lone surrogate found", f)
703 impl FromIterator<char> for String {
704 fn from_iter<I:Iterator<Item=char>>(iterator: I) -> String {
705 let mut buf = String::new();
706 buf.extend(iterator);
712 impl<'a> FromIterator<&'a str> for String {
713 fn from_iter<I:Iterator<Item=&'a str>>(iterator: I) -> String {
714 let mut buf = String::new();
715 buf.extend(iterator);
720 #[experimental = "waiting on Extend stabilization"]
721 impl Extend<char> for String {
722 fn extend<I:Iterator<Item=char>>(&mut self, mut iterator: I) {
723 let (lower_bound, _) = iterator.size_hint();
724 self.reserve(lower_bound);
731 #[experimental = "waiting on Extend stabilization"]
732 impl<'a> Extend<&'a str> for String {
733 fn extend<I: Iterator<Item=&'a str>>(&mut self, mut iterator: I) {
734 // A guess that at least one byte per iterator element will be needed.
735 let (lower_bound, _) = iterator.size_hint();
736 self.reserve(lower_bound);
744 impl PartialEq for String {
746 fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
748 fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) }
751 macro_rules! impl_eq {
752 ($lhs:ty, $rhs: ty) => {
754 impl<'a> PartialEq<$rhs> for $lhs {
756 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
758 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
762 impl<'a> PartialEq<$lhs> for $rhs {
764 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
766 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
772 impl_eq! { String, &'a str }
773 impl_eq! { CowString<'a>, String }
776 impl<'a, 'b> PartialEq<&'b str> for CowString<'a> {
778 fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) }
780 fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) }
784 impl<'a, 'b> PartialEq<CowString<'a>> for &'b str {
786 fn eq(&self, other: &CowString<'a>) -> bool { PartialEq::eq(&**self, &**other) }
788 fn ne(&self, other: &CowString<'a>) -> bool { PartialEq::ne(&**self, &**other) }
791 #[experimental = "waiting on Str stabilization"]
792 impl Str for String {
795 fn as_slice<'a>(&'a self) -> &'a str {
796 unsafe { mem::transmute(self.vec.as_slice()) }
801 impl Default for String {
803 fn default() -> String {
808 #[experimental = "waiting on fmt stabilization"]
809 impl fmt::String for String {
810 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
811 fmt::String::fmt(&**self, f)
815 #[experimental = "waiting on fmt stabilization"]
816 impl fmt::Show for String {
817 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
818 fmt::Show::fmt(&**self, f)
822 #[experimental = "waiting on Hash stabilization"]
823 impl<H: hash::Writer> hash::Hash<H> for String {
825 fn hash(&self, hasher: &mut H) {
826 (**self).hash(hasher)
830 #[unstable = "recent addition, needs more experience"]
831 impl<'a> Add<&'a str> for String {
832 type Output = String;
834 fn add(mut self, other: &str) -> String {
835 self.push_str(other);
840 impl ops::Index<ops::Range<uint>> for String {
843 fn index(&self, index: &ops::Range<uint>) -> &str {
844 &self.index(&FullRange)[*index]
847 impl ops::Index<ops::RangeTo<uint>> for String {
850 fn index(&self, index: &ops::RangeTo<uint>) -> &str {
851 &self.index(&FullRange)[*index]
854 impl ops::Index<ops::RangeFrom<uint>> for String {
857 fn index(&self, index: &ops::RangeFrom<uint>) -> &str {
858 &self.index(&FullRange)[*index]
861 impl ops::Index<ops::FullRange> for String {
864 fn index(&self, _index: &ops::FullRange) -> &str {
865 unsafe { mem::transmute(self.vec.as_slice()) }
870 impl ops::Deref for String {
873 fn deref<'a>(&'a self) -> &'a str {
874 unsafe { mem::transmute(self.vec.index(&FullRange)) }
878 /// Wrapper type providing a `&String` reference via `Deref`.
880 pub struct DerefString<'a> {
884 impl<'a> Deref for DerefString<'a> {
885 type Target = String;
887 fn deref<'b>(&'b self) -> &'b String {
888 unsafe { mem::transmute(&*self.x) }
892 /// Convert a string slice to a wrapper type providing a `&String` reference.
897 /// use std::string::as_string;
899 /// fn string_consumer(s: String) {
900 /// assert_eq!(s, "foo".to_string());
903 /// let string = as_string("foo").clone();
904 /// string_consumer(string);
907 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
908 DerefString { x: as_vec(x.as_bytes()) }
911 impl FromStr for String {
913 fn from_str(s: &str) -> Option<String> {
914 Some(String::from_str(s))
918 /// A generic trait for converting a value to a string
920 /// Converts the value of `self` to an owned string
921 fn to_string(&self) -> String;
925 impl<T: fmt::Show> ToString for T {
926 fn to_string(&self) -> String {
927 use core::fmt::Writer;
928 let mut buf = String::new();
929 let _ = buf.write_fmt(format_args!("{}", self));
936 impl<T: fmt::String> ToString for T {
937 fn to_string(&self) -> String {
938 use core::fmt::Writer;
939 let mut buf = String::new();
940 let _ = buf.write_fmt(format_args!("{}", self));
946 impl IntoCow<'static, String, str> for String {
947 fn into_cow(self) -> CowString<'static> {
952 impl<'a> IntoCow<'a, String, str> for &'a str {
953 fn into_cow(self) -> CowString<'a> {
958 /// A clone-on-write string
960 pub type CowString<'a> = Cow<'a, String, str>;
962 impl<'a> Str for CowString<'a> {
964 fn as_slice<'b>(&'b self) -> &'b str {
969 impl fmt::Writer for String {
970 fn write_str(&mut self, s: &str) -> fmt::Result {
982 use core::iter::repeat;
983 use super::{as_string, CowString};
984 use core::ops::FullRange;
987 fn test_as_string() {
989 assert_eq!(x, as_string(x).as_slice());
994 let owned: Option<::std::string::String> = "string".parse();
995 assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
999 fn test_from_utf8() {
1000 let xs = b"hello".to_vec();
1001 assert_eq!(String::from_utf8(xs).unwrap(),
1002 String::from_str("hello"));
1004 let xs = "ศไทย中华Việt Nam".as_bytes().to_vec();
1005 assert_eq!(String::from_utf8(xs).unwrap(),
1006 String::from_str("ศไทย中华Việt Nam"));
1008 let xs = b"hello\xFF".to_vec();
1009 let err = String::from_utf8(xs).err().unwrap();
1010 assert_eq!(err.utf8_error(), Utf8Error::TooShort);
1011 assert_eq!(err.into_bytes(), b"hello\xff".to_vec());
1015 fn test_from_utf8_lossy() {
1017 let ys: CowString = "hello".into_cow();
1018 assert_eq!(String::from_utf8_lossy(xs), ys);
1020 let xs = "ศไทย中华Việt Nam".as_bytes();
1021 let ys: CowString = "ศไทย中华Việt Nam".into_cow();
1022 assert_eq!(String::from_utf8_lossy(xs), ys);
1024 let xs = b"Hello\xC2 There\xFF Goodbye";
1025 assert_eq!(String::from_utf8_lossy(xs),
1026 String::from_str("Hello\u{FFFD} There\u{FFFD} Goodbye").into_cow());
1028 let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1029 assert_eq!(String::from_utf8_lossy(xs),
1030 String::from_str("Hello\u{FFFD}\u{FFFD} There\u{FFFD} Goodbye").into_cow());
1032 let xs = b"\xF5foo\xF5\x80bar";
1033 assert_eq!(String::from_utf8_lossy(xs),
1034 String::from_str("\u{FFFD}foo\u{FFFD}\u{FFFD}bar").into_cow());
1036 let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
1037 assert_eq!(String::from_utf8_lossy(xs),
1038 String::from_str("\u{FFFD}foo\u{FFFD}bar\u{FFFD}baz").into_cow());
1040 let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
1041 assert_eq!(String::from_utf8_lossy(xs),
1042 String::from_str("\u{FFFD}foo\u{FFFD}bar\u{FFFD}\u{FFFD}baz").into_cow());
1044 let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
1045 assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\
1046 foo\u{10000}bar").into_cow());
1049 let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
1050 assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}\u{FFFD}\u{FFFD}foo\
1051 \u{FFFD}\u{FFFD}\u{FFFD}bar").into_cow());
1055 fn test_from_utf16() {
1057 [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"),
1058 vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
1059 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
1060 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
1061 0xd800_u16, 0xdf30_u16, 0x000a_u16]),
1063 (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"),
1064 vec![0xd801_u16, 0xdc12_u16, 0xd801_u16,
1065 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
1066 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
1067 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16,
1068 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16,
1071 (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"),
1072 vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
1073 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
1074 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
1075 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16,
1076 0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16,
1077 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16,
1078 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),
1080 (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"),
1081 vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
1082 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
1083 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
1084 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16,
1085 0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16,
1086 0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16,
1087 0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16,
1088 0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16,
1089 0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16,
1090 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16,
1092 // Issue #12318, even-numbered non-BMP planes
1093 (String::from_str("\u{20000}"),
1094 vec![0xD840, 0xDC00])];
1096 for p in pairs.iter() {
1097 let (s, u) = (*p).clone();
1098 let s_as_utf16 = s.utf16_units().collect::<Vec<u16>>();
1099 let u_as_string = String::from_utf16(u.as_slice()).unwrap();
1101 assert!(::unicode::str::is_utf16(u.as_slice()));
1102 assert_eq!(s_as_utf16, u);
1104 assert_eq!(u_as_string, s);
1105 assert_eq!(String::from_utf16_lossy(u.as_slice()), s);
1107 assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
1108 assert_eq!(u_as_string.utf16_units().collect::<Vec<u16>>(), u);
1113 fn test_utf16_invalid() {
1114 // completely positive cases tested above.
1116 assert!(String::from_utf16(&[0xD800]).is_err());
1118 assert!(String::from_utf16(&[0xD800, 0xD800]).is_err());
1121 assert!(String::from_utf16(&[0x0061, 0xDC00]).is_err());
1124 assert!(String::from_utf16(&[0xD800, 0xd801, 0xdc8b, 0xD800]).is_err());
1128 fn test_from_utf16_lossy() {
1129 // completely positive cases tested above.
1131 assert_eq!(String::from_utf16_lossy(&[0xD800]), String::from_str("\u{FFFD}"));
1133 assert_eq!(String::from_utf16_lossy(&[0xD800, 0xD800]),
1134 String::from_str("\u{FFFD}\u{FFFD}"));
1137 assert_eq!(String::from_utf16_lossy(&[0x0061, 0xDC00]), String::from_str("a\u{FFFD}"));
1140 assert_eq!(String::from_utf16_lossy(&[0xD800, 0xd801, 0xdc8b, 0xD800]),
1141 String::from_str("\u{FFFD}𐒋\u{FFFD}"));
1145 fn test_push_bytes() {
1146 let mut s = String::from_str("ABC");
1148 let mv = s.as_mut_vec();
1149 mv.push_all(&[b'D']);
1151 assert_eq!(s, "ABCD");
1155 fn test_push_str() {
1156 let mut s = String::new();
1158 assert_eq!(s.slice_from(0), "");
1160 assert_eq!(s.slice_from(0), "abc");
1161 s.push_str("ประเทศไทย中华Việt Nam");
1162 assert_eq!(s.slice_from(0), "abcประเทศไทย中华Việt Nam");
1167 let mut data = String::from_str("ประเทศไทย中");
1169 data.push('b'); // 1 byte
1170 data.push('¢'); // 2 byte
1171 data.push('€'); // 3 byte
1172 data.push('𤭢'); // 4 byte
1173 assert_eq!(data, "ประเทศไทย中华b¢€𤭢");
1178 let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
1179 assert_eq!(data.pop().unwrap(), '𤭢'); // 4 bytes
1180 assert_eq!(data.pop().unwrap(), '€'); // 3 bytes
1181 assert_eq!(data.pop().unwrap(), '¢'); // 2 bytes
1182 assert_eq!(data.pop().unwrap(), 'b'); // 1 bytes
1183 assert_eq!(data.pop().unwrap(), '华');
1184 assert_eq!(data, "ประเทศไทย中");
1188 fn test_str_truncate() {
1189 let mut s = String::from_str("12345");
1191 assert_eq!(s, "12345");
1193 assert_eq!(s, "123");
1197 let mut s = String::from_str("12345");
1201 let p_ = s.as_ptr();
1207 fn test_str_truncate_invalid_len() {
1208 let mut s = String::from_str("12345");
1214 fn test_str_truncate_split_codepoint() {
1215 let mut s = String::from_str("\u{FC}"); // ü
1220 fn test_str_clear() {
1221 let mut s = String::from_str("12345");
1223 assert_eq!(s.len(), 0);
1229 let a = String::from_str("12345");
1232 assert_eq!(b.len(), 7);
1233 assert_eq!(b, "1234522");
1238 let mut s = "ศไทย中华Việt Nam; foobar".to_string();;
1239 assert_eq!(s.remove(0), 'ศ');
1240 assert_eq!(s.len(), 33);
1241 assert_eq!(s, "ไทย中华Việt Nam; foobar");
1242 assert_eq!(s.remove(17), 'ệ');
1243 assert_eq!(s, "ไทย中华Vit Nam; foobar");
1246 #[test] #[should_fail]
1248 "ศ".to_string().remove(1);
1253 let mut s = "foobar".to_string();
1255 assert_eq!(s, "ệfoobar");
1257 assert_eq!(s, "ệfooยbar");
1260 #[test] #[should_fail] fn insert_bad1() { "".to_string().insert(1, 't'); }
1261 #[test] #[should_fail] fn insert_bad2() { "ệ".to_string().insert(1, 't'); }
1265 let s = "foobar".to_string();
1266 assert_eq!("foobar", &s[]);
1267 assert_eq!("foo", &s[..3]);
1268 assert_eq!("bar", &s[3..]);
1269 assert_eq!("oob", &s[1..4]);
1273 fn test_simple_types() {
1274 assert_eq!(1i.to_string(), "1");
1275 assert_eq!((-1i).to_string(), "-1");
1276 assert_eq!(200u.to_string(), "200");
1277 assert_eq!(2u8.to_string(), "2");
1278 assert_eq!(true.to_string(), "true");
1279 assert_eq!(false.to_string(), "false");
1280 assert_eq!(().to_string(), "()");
1281 assert_eq!(("hi".to_string()).to_string(), "hi");
1286 let x: Vec<int> = vec![];
1287 assert_eq!(x.to_string(), "[]");
1288 assert_eq!((vec![1i]).to_string(), "[1]");
1289 assert_eq!((vec![1i, 2, 3]).to_string(), "[1, 2, 3]");
1290 assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_string() ==
1291 "[[], [1], [1, 1]]");
1295 fn test_from_iterator() {
1296 let s = "ศไทย中华Việt Nam".to_string();
1300 let a: String = s.chars().collect();
1303 let mut b = t.to_string();
1304 b.extend(u.chars());
1307 let c: String = vec![t, u].into_iter().collect();
1310 let mut d = t.to_string();
1311 d.extend(vec![u].into_iter());
1316 fn bench_with_capacity(b: &mut Bencher) {
1318 String::with_capacity(100)
1323 fn bench_push_str(b: &mut Bencher) {
1324 let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
1326 let mut r = String::new();
1331 const REPETITIONS: u64 = 10_000;
1334 fn bench_push_str_one_byte(b: &mut Bencher) {
1335 b.bytes = REPETITIONS;
1337 let mut r = String::new();
1338 for _ in range(0, REPETITIONS) {
1345 fn bench_push_char_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_two_bytes(b: &mut Bencher) {
1357 b.bytes = REPETITIONS * 2;
1359 let mut r = String::new();
1360 for _ in range(0, REPETITIONS) {
1367 fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
1368 let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
1369 Lorem ipsum dolor sit amet, consectetur. ";
1371 assert_eq!(100, s.len());
1373 let _ = String::from_utf8_lossy(s);
1378 fn from_utf8_lossy_100_multibyte(b: &mut Bencher) {
1379 let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
1380 assert_eq!(100, s.len());
1382 let _ = String::from_utf8_lossy(s);
1387 fn from_utf8_lossy_invalid(b: &mut Bencher) {
1388 let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1390 let _ = String::from_utf8_lossy(s);
1395 fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
1396 let s = repeat(0xf5u8).take(100).collect::<Vec<_>>();
1398 let _ = String::from_utf8_lossy(s.as_slice());