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.
17 use core::borrow::{Cow, IntoCow};
18 use core::default::Default;
23 // FIXME: ICE's abound if you import the `Slice` type while importing `Slice` trait
24 use core::raw::Slice as RawSlice;
27 use slice::CloneSliceAllocPrelude;
29 use str::{CharRange, CowString, FromStr, StrAllocating, Owned};
30 use vec::{DerefVec, Vec, as_vec};
32 /// A growable string stored as a UTF-8 encoded buffer.
33 #[deriving(Clone, PartialOrd, Eq, Ord)]
40 /// Creates a new string buffer initialized with the empty string.
45 /// let mut s = String::new();
49 pub fn new() -> String {
55 /// Creates a new string buffer with the given capacity.
56 /// The string will be able to hold exactly `capacity` bytes without
57 /// reallocating. If `capacity` is 0, the string will not allocate.
62 /// let mut s = String::with_capacity(10);
66 pub fn with_capacity(capacity: uint) -> String {
68 vec: Vec::with_capacity(capacity),
72 /// Creates a new string buffer from the given string.
77 /// let s = String::from_str("hello");
78 /// assert_eq!(s.as_slice(), "hello");
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() }
86 /// Returns the vector as a string buffer, if possible, taking care not to
89 /// Returns `Err` with the original vector if the vector contains invalid
95 /// let hello_vec = vec![104, 101, 108, 108, 111];
96 /// let s = String::from_utf8(hello_vec);
97 /// assert_eq!(s, Ok("hello".to_string()));
99 /// let invalid_vec = vec![240, 144, 128];
100 /// let s = String::from_utf8(invalid_vec);
101 /// assert_eq!(s, Err(vec![240, 144, 128]));
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 })
113 /// Converts a vector of bytes to a new UTF-8 string.
114 /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
119 /// let input = b"Hello \xF0\x90\x80World";
120 /// let output = String::from_utf8_lossy(input);
121 /// assert_eq!(output.as_slice(), "Hello \uFFFDWorld");
123 #[unstable = "return type may change"]
124 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> CowString<'a> {
126 return Cow::Borrowed(unsafe { mem::transmute(v) })
129 static TAG_CONT_U8: u8 = 128u8;
130 static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
133 fn unsafe_get(xs: &[u8], i: uint) -> u8 {
134 unsafe { *xs.unsafe_get(i) }
136 fn safe_get(xs: &[u8], i: uint, total: uint) -> u8 {
144 let mut res = String::with_capacity(total);
148 res.as_mut_vec().push_all(v[..i])
152 // subseqidx is the index of the first byte of the subsequence we're looking at.
153 // It's used to copy a bunch of contiguous good codepoints at once instead of copying
155 let mut subseqidx = 0;
159 let byte = unsafe_get(v, i);
162 macro_rules! error(() => ({
165 res.as_mut_vec().push_all(v[subseqidx..i_]);
168 res.as_mut_vec().push_all(REPLACEMENT);
173 // subseqidx handles this
175 let w = str::utf8_char_width(byte);
179 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
186 match (byte, safe_get(v, i, total)) {
187 (0xE0 , 0xA0 ... 0xBF) => (),
188 (0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
189 (0xED , 0x80 ... 0x9F) => (),
190 (0xEE ... 0xEF, 0x80 ... 0xBF) => (),
197 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
204 match (byte, safe_get(v, i, total)) {
205 (0xF0 , 0x90 ... 0xBF) => (),
206 (0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
207 (0xF4 , 0x80 ... 0x8F) => (),
214 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
219 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
232 if subseqidx < total {
234 res.as_mut_vec().push_all(v[subseqidx..total])
237 Cow::Owned(res.into_string())
240 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
241 /// if `v` contains any invalid data.
247 /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
248 /// 0x0073, 0x0069, 0x0063];
249 /// assert_eq!(String::from_utf16(v), Some("𝄞music".to_string()));
251 /// // 𝄞mu<invalid>ic
253 /// assert_eq!(String::from_utf16(v), None);
255 #[unstable = "error value in return may change"]
256 pub fn from_utf16(v: &[u16]) -> Option<String> {
257 let mut s = String::with_capacity(v.len());
258 for c in str::utf16_items(v) {
260 str::ScalarValue(c) => s.push(c),
261 str::LoneSurrogate(_) => return None
267 /// Decode a UTF-16 encoded vector `v` into a string, replacing
268 /// invalid data with the replacement character (U+FFFD).
272 /// // 𝄞mus<invalid>ic<invalid>
273 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
274 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
277 /// assert_eq!(String::from_utf16_lossy(v),
278 /// "𝄞mus\uFFFDic\uFFFD".to_string());
281 pub fn from_utf16_lossy(v: &[u16]) -> String {
282 str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
285 /// Convert a vector of `char`s to a `String`.
290 /// let chars = &['h', 'e', 'l', 'l', 'o'];
291 /// let s = String::from_chars(chars);
292 /// assert_eq!(s.as_slice(), "hello");
295 #[unstable = "may be removed in favor of .collect()"]
296 pub fn from_chars(chs: &[char]) -> String {
297 chs.iter().map(|c| *c).collect()
300 /// Creates a new `String` from a length, capacity, and pointer.
302 /// This is unsafe because:
303 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
304 /// * We assume that the `Vec` contains valid UTF-8.
306 #[unstable = "function just moved from string::raw"]
307 pub unsafe fn from_raw_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
309 vec: Vec::from_raw_parts(buf, length, capacity),
313 /// Creates a `String` from a null-terminated `*const u8` buffer.
315 /// This function is unsafe because we dereference memory until we find the
316 /// NUL character, which is not guaranteed to be present. Additionally, the
317 /// slice is not checked to see whether it contains valid UTF-8
318 #[unstable = "just renamed from `mod raw`"]
319 pub unsafe fn from_raw_buf(buf: *const u8) -> String {
320 String::from_str(str::from_c_str(buf as *const i8))
323 /// Creates a `String` from a `*const u8` buffer of the given length.
325 /// This function is unsafe because it blindly assumes the validity of the
326 /// pointer `buf` for `len` bytes of memory. This function will copy the
327 /// memory from `buf` into a new allocation (owned by the returned
330 /// This function is also unsafe because it does not validate that the
331 /// buffer is valid UTF-8 encoded data.
332 #[unstable = "just renamed from `mod raw`"]
333 pub unsafe fn from_raw_buf_len(buf: *const u8, len: uint) -> String {
334 String::from_utf8_unchecked(Vec::from_raw_buf(buf, len))
337 /// Converts a vector of bytes to a new `String` without checking if
338 /// it contains valid UTF-8. This is unsafe because it assumes that
339 /// the UTF-8-ness of the vector has already been validated.
341 #[unstable = "awaiting stabilization"]
342 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
343 String { vec: bytes }
346 /// Return the underlying byte buffer, encoded as UTF-8.
351 /// let s = String::from_str("hello");
352 /// let bytes = s.into_bytes();
353 /// assert_eq!(bytes, vec![104, 101, 108, 108, 111]);
357 pub fn into_bytes(self) -> Vec<u8> {
361 /// Creates a string buffer by repeating a character `length` times.
366 /// let s = String::from_char(5, 'a');
367 /// assert_eq!(s.as_slice(), "aaaaa");
370 #[unstable = "may be replaced with iterators, questionable usability, and \
371 the name may change"]
372 pub fn from_char(length: uint, ch: char) -> String {
377 let mut buf = String::new();
379 let size = buf.len() * (length - 1);
380 buf.reserve_exact(size);
381 for _ in range(1, length) {
387 /// Pushes the given string onto this string buffer.
392 /// let mut s = String::from_str("foo");
393 /// s.push_str("bar");
394 /// assert_eq!(s.as_slice(), "foobar");
397 #[unstable = "extra variants of `push`, could possibly be based on iterators"]
398 pub fn push_str(&mut self, string: &str) {
399 self.vec.push_all(string.as_bytes())
402 /// Pushes `ch` onto the given string `count` times.
407 /// let mut s = String::from_str("foo");
409 /// assert_eq!(s.as_slice(), "fooZZZZZ");
412 #[unstable = "duplicate of iterator-based functionality"]
413 pub fn grow(&mut self, count: uint, ch: char) {
414 for _ in range(0, count) {
419 /// Returns the number of bytes that this string buffer can hold without reallocating.
424 /// let s = String::with_capacity(10);
425 /// assert!(s.capacity() >= 10);
428 #[unstable = "matches collection reform specification, waiting for dust to settle"]
429 pub fn capacity(&self) -> uint {
433 /// Deprecated: Renamed to `reserve`.
434 #[deprecated = "Renamed to `reserve`"]
435 pub fn reserve_additional(&mut self, extra: uint) {
436 self.vec.reserve(extra)
439 /// Reserves capacity for at least `additional` more bytes to be inserted in the given
440 /// `String`. The collection may reserve more space to avoid frequent reallocations.
444 /// Panics if the new capacity overflows `uint`.
449 /// let mut s = String::new();
451 /// assert!(s.capacity() >= 10);
454 #[unstable = "matches collection reform specification, waiting for dust to settle"]
455 pub fn reserve(&mut self, additional: uint) {
456 self.vec.reserve(additional)
459 /// Reserves the minimum capacity for exactly `additional` more bytes to be inserted in the
460 /// given `String`. Does nothing if the capacity is already sufficient.
462 /// Note that the allocator may give the collection more space than it requests. Therefore
463 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
464 /// insertions are expected.
468 /// Panics if the new capacity overflows `uint`.
473 /// let mut s = String::new();
475 /// assert!(s.capacity() >= 10);
478 #[unstable = "matches collection reform specification, waiting for dust to settle"]
479 pub fn reserve_exact(&mut self, additional: uint) {
480 self.vec.reserve_exact(additional)
483 /// Shrinks the capacity of this string buffer to match its length.
488 /// let mut s = String::from_str("foo");
490 /// assert!(s.capacity() >= 100);
491 /// s.shrink_to_fit();
492 /// assert_eq!(s.capacity(), 3);
495 #[unstable = "matches collection reform specification, waiting for dust to settle"]
496 pub fn shrink_to_fit(&mut self) {
497 self.vec.shrink_to_fit()
500 /// Adds the given character to the end of the string.
505 /// let mut s = String::from_str("abc");
509 /// assert_eq!(s.as_slice(), "abc123");
512 #[stable = "function just renamed from push_char"]
513 pub fn push(&mut self, ch: char) {
514 let cur_len = self.len();
515 // This may use up to 4 bytes.
519 // Attempt to not use an intermediate buffer by just pushing bytes
520 // directly onto this string.
521 let slice = RawSlice {
522 data: self.vec.as_ptr().offset(cur_len as int),
525 let used = ch.encode_utf8(mem::transmute(slice)).unwrap_or(0);
526 self.vec.set_len(cur_len + used);
530 /// Works with the underlying buffer as a byte slice.
535 /// let s = String::from_str("hello");
536 /// let b: &[_] = &[104, 101, 108, 108, 111];
537 /// assert_eq!(s.as_bytes(), b);
541 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
545 /// Shortens a string to the specified length.
549 /// Panics if `new_len` > current length,
550 /// or if `new_len` is not a character boundary.
555 /// let mut s = String::from_str("hello");
557 /// assert_eq!(s.as_slice(), "he");
560 #[unstable = "the panic conventions for strings are under development"]
561 pub fn truncate(&mut self, new_len: uint) {
562 assert!(self.is_char_boundary(new_len));
563 self.vec.truncate(new_len)
566 /// Removes the last character from the string buffer and returns it.
567 /// Returns `None` if this string buffer is empty.
572 /// let mut s = String::from_str("foo");
573 /// assert_eq!(s.pop(), Some('o'));
574 /// assert_eq!(s.pop(), Some('o'));
575 /// assert_eq!(s.pop(), Some('f'));
576 /// assert_eq!(s.pop(), None);
579 #[unstable = "this function was just renamed from pop_char"]
580 pub fn pop(&mut self) -> Option<char> {
581 let len = self.len();
586 let CharRange {ch, next} = self.char_range_at_reverse(len);
588 self.vec.set_len(next);
593 /// Removes the character from the string buffer at byte position `idx` and
594 /// returns it. Returns `None` if `idx` is out of bounds.
598 /// This is an O(n) operation as it requires copying every element in the
603 /// If `idx` does not lie on a character boundary, then this function will
609 /// let mut s = String::from_str("foo");
610 /// assert_eq!(s.remove(0), Some('f'));
611 /// assert_eq!(s.remove(1), Some('o'));
612 /// assert_eq!(s.remove(0), Some('o'));
613 /// assert_eq!(s.remove(0), None);
615 #[unstable = "the panic semantics of this function and return type \
617 pub fn remove(&mut self, idx: uint) -> Option<char> {
618 let len = self.len();
619 if idx >= len { return None }
621 let CharRange { ch, next } = self.char_range_at(idx);
623 ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
624 self.vec.as_ptr().offset(next as int),
626 self.vec.set_len(len - (next - idx));
631 /// Insert a character into the string buffer at byte position `idx`.
635 /// This is an O(n) operation as it requires copying every element in the
640 /// If `idx` does not lie on a character boundary or is out of bounds, then
641 /// this function will panic.
642 #[unstable = "the panic semantics of this function are uncertain"]
643 pub fn insert(&mut self, idx: uint, ch: char) {
644 let len = self.len();
646 assert!(self.is_char_boundary(idx));
648 let mut bits = [0, ..4];
649 let amt = ch.encode_utf8(&mut bits).unwrap();
652 ptr::copy_memory(self.vec.as_mut_ptr().offset((idx + amt) as int),
653 self.vec.as_ptr().offset(idx as int),
655 ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
658 self.vec.set_len(len + amt);
662 /// Views the string buffer as a mutable sequence of bytes.
664 /// This is unsafe because it does not check
665 /// to ensure that the resulting string will be valid UTF-8.
670 /// let mut s = String::from_str("hello");
672 /// let vec = s.as_mut_vec();
673 /// assert!(vec == &mut vec![104, 101, 108, 108, 111]);
676 /// assert_eq!(s.as_slice(), "olleh");
678 #[unstable = "the name of this method may be changed"]
679 pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
683 /// Return the number of bytes in this string.
688 /// let a = "foo".to_string();
689 /// assert_eq!(a.len(), 3);
693 pub fn len(&self) -> uint { self.vec.len() }
695 /// Returns true if the string contains no bytes
700 /// let mut v = String::new();
701 /// assert!(v.is_empty());
703 /// assert!(!v.is_empty());
705 pub fn is_empty(&self) -> bool { self.len() == 0 }
707 /// Truncates the string, returning it to 0 length.
712 /// let mut s = "foo".to_string();
714 /// assert!(s.is_empty());
718 pub fn clear(&mut self) {
723 #[experimental = "waiting on FromIterator stabilization"]
724 impl FromIterator<char> for String {
725 fn from_iter<I:Iterator<char>>(iterator: I) -> String {
726 let mut buf = String::new();
727 buf.extend(iterator);
732 #[experimental = "waiting on Extend stabilization"]
733 impl Extend<char> for String {
734 fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
741 impl PartialEq for String {
743 fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
745 fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) }
748 macro_rules! impl_eq {
749 ($lhs:ty, $rhs: ty) => {
750 impl<'a> PartialEq<$rhs> for $lhs {
752 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
754 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
757 impl<'a> PartialEq<$lhs> for $rhs {
759 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
761 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
767 impl_eq!(String, &'a str)
768 impl_eq!(CowString<'a>, String)
770 impl<'a, 'b> PartialEq<&'b str> for CowString<'a> {
772 fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) }
774 fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) }
777 impl<'a, 'b> PartialEq<CowString<'a>> for &'b str {
779 fn eq(&self, other: &CowString<'a>) -> bool { PartialEq::eq(&**self, &**other) }
781 fn ne(&self, other: &CowString<'a>) -> bool { PartialEq::ne(&**self, &**other) }
784 #[experimental = "waiting on Str stabilization"]
785 impl Str for String {
788 fn as_slice<'a>(&'a self) -> &'a str {
790 mem::transmute(self.vec.as_slice())
795 #[experimental = "waiting on StrAllocating stabilization"]
796 impl StrAllocating for String {
798 fn into_string(self) -> String {
804 impl Default for String {
805 fn default() -> String {
810 #[experimental = "waiting on Show stabilization"]
811 impl fmt::Show for String {
812 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
813 self.as_slice().fmt(f)
817 #[experimental = "waiting on Hash stabilization"]
818 impl<H: hash::Writer> hash::Hash<H> for String {
820 fn hash(&self, hasher: &mut H) {
821 self.as_slice().hash(hasher)
826 #[deprecated = "Use overloaded `core::cmp::PartialEq`"]
827 impl<'a, S: Str> Equiv<S> for String {
829 fn equiv(&self, other: &S) -> bool {
830 self.as_slice() == other.as_slice()
834 #[experimental = "waiting on Add stabilization"]
835 impl<S: Str> Add<S, String> for String {
836 fn add(&self, other: &S) -> String {
837 let mut s = String::from_str(self.as_slice());
838 s.push_str(other.as_slice());
843 impl ops::Slice<uint, str> for String {
845 fn as_slice_<'a>(&'a self) -> &'a str {
850 fn slice_from_or_fail<'a>(&'a self, from: &uint) -> &'a str {
855 fn slice_to_or_fail<'a>(&'a self, to: &uint) -> &'a str {
860 fn slice_or_fail<'a>(&'a self, from: &uint, to: &uint) -> &'a str {
865 #[experimental = "waiting on Deref stabilization"]
866 impl ops::Deref<str> for String {
867 fn deref<'a>(&'a self) -> &'a str { self.as_slice() }
870 /// Wrapper type providing a `&String` reference via `Deref`.
872 pub struct DerefString<'a> {
876 impl<'a> Deref<String> for DerefString<'a> {
877 fn deref<'b>(&'b self) -> &'b String {
878 unsafe { mem::transmute(&*self.x) }
882 /// Convert a string slice to a wrapper type providing a `&String` reference.
884 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
885 DerefString { x: as_vec(x.as_bytes()) }
888 impl FromStr for String {
890 fn from_str(s: &str) -> Option<String> {
891 Some(String::from_str(s))
895 /// Trait for converting a type to a string, consuming it in the process.
896 pub trait IntoString {
897 /// Consume and convert to a string.
898 fn into_string(self) -> String;
901 /// A generic trait for converting a value to a string
903 /// Converts the value of `self` to an owned string
904 fn to_string(&self) -> String;
907 impl<T: fmt::Show> ToString for T {
908 fn to_string(&self) -> String {
909 let mut buf = Vec::<u8>::new();
910 let _ = format_args!(|args| fmt::write(&mut buf, args), "{}", self);
911 String::from_utf8(buf).unwrap()
915 impl IntoCow<'static, String, str> for String {
916 fn into_cow(self) -> CowString<'static> {
921 impl<'a> IntoCow<'a, String, str> for &'a str {
922 fn into_cow(self) -> CowString<'a> {
927 /// Unsafe operations
933 /// Creates a new `String` from a length, capacity, and pointer.
935 /// This is unsafe because:
936 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
937 /// * We assume that the `Vec` contains valid UTF-8.
939 #[deprecated = "renamed to String::from_raw_parts"]
940 pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
941 String::from_raw_parts(buf, length, capacity)
944 /// Creates a `String` from a `*const u8` buffer of the given length.
946 /// This function is unsafe because of two reasons:
948 /// * A raw pointer is dereferenced and transmuted to `&[u8]`;
949 /// * The slice is not checked to see whether it contains valid UTF-8.
950 #[deprecated = "renamed to String::from_raw_buf_len"]
951 pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
952 String::from_raw_buf_len(buf, len)
955 /// Creates a `String` from a null-terminated `*const u8` buffer.
957 /// This function is unsafe because we dereference memory until we find the NUL character,
958 /// which is not guaranteed to be present. Additionally, the slice is not checked to see
959 /// whether it contains valid UTF-8
960 #[deprecated = "renamed to String::from_raw_buf"]
961 pub unsafe fn from_buf(buf: *const u8) -> String {
962 String::from_raw_buf(buf)
965 /// Converts a vector of bytes to a new `String` without checking if
966 /// it contains valid UTF-8. This is unsafe because it assumes that
967 /// the UTF-8-ness of the vector has already been validated.
969 #[deprecated = "renamed to String::from_utf8_unchecked"]
970 pub unsafe fn from_utf8(bytes: Vec<u8>) -> String {
971 String::from_utf8_unchecked(bytes)
980 use slice::CloneSliceAllocPrelude;
981 use str::{Str, StrPrelude};
983 use super::{as_string, String, ToString};
987 fn test_as_string() {
989 assert_eq!(x, as_string(x).as_slice());
994 let owned: Option<::std::string::String> = from_str("string");
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), Ok(String::from_str("hello")));
1003 let xs = "ศไทย中华Việt Nam".as_bytes().to_vec();
1004 assert_eq!(String::from_utf8(xs), Ok(String::from_str("ศไทย中华Việt Nam")));
1006 let xs = b"hello\xFF".to_vec();
1007 assert_eq!(String::from_utf8(xs),
1008 Err(b"hello\xFF".to_vec()));
1012 fn test_from_utf8_lossy() {
1014 let ys: str::CowString = "hello".into_cow();
1015 assert_eq!(String::from_utf8_lossy(xs), ys);
1017 let xs = "ศไทย中华Việt Nam".as_bytes();
1018 let ys: str::CowString = "ศไทย中华Việt Nam".into_cow();
1019 assert_eq!(String::from_utf8_lossy(xs), ys);
1021 let xs = b"Hello\xC2 There\xFF Goodbye";
1022 assert_eq!(String::from_utf8_lossy(xs),
1023 String::from_str("Hello\uFFFD There\uFFFD Goodbye").into_cow());
1025 let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1026 assert_eq!(String::from_utf8_lossy(xs),
1027 String::from_str("Hello\uFFFD\uFFFD There\uFFFD Goodbye").into_cow());
1029 let xs = b"\xF5foo\xF5\x80bar";
1030 assert_eq!(String::from_utf8_lossy(xs),
1031 String::from_str("\uFFFDfoo\uFFFD\uFFFDbar").into_cow());
1033 let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
1034 assert_eq!(String::from_utf8_lossy(xs),
1035 String::from_str("\uFFFDfoo\uFFFDbar\uFFFDbaz").into_cow());
1037 let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
1038 assert_eq!(String::from_utf8_lossy(xs),
1039 String::from_str("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz").into_cow());
1041 let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
1042 assert_eq!(String::from_utf8_lossy(xs), String::from_str("\uFFFD\uFFFD\uFFFD\uFFFD\
1043 foo\U00010000bar").into_cow());
1046 let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
1047 assert_eq!(String::from_utf8_lossy(xs), String::from_str("\uFFFD\uFFFD\uFFFDfoo\
1048 \uFFFD\uFFFD\uFFFDbar").into_cow());
1052 fn test_from_utf16() {
1054 [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"),
1055 vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
1056 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
1057 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
1058 0xd800_u16, 0xdf30_u16, 0x000a_u16]),
1060 (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"),
1061 vec![0xd801_u16, 0xdc12_u16, 0xd801_u16,
1062 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
1063 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
1064 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16,
1065 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16,
1068 (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"),
1069 vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
1070 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
1071 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
1072 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16,
1073 0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16,
1074 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16,
1075 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),
1077 (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"),
1078 vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
1079 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
1080 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
1081 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16,
1082 0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16,
1083 0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16,
1084 0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16,
1085 0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16,
1086 0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16,
1087 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16,
1089 // Issue #12318, even-numbered non-BMP planes
1090 (String::from_str("\U00020000"),
1091 vec![0xD840, 0xDC00])];
1093 for p in pairs.iter() {
1094 let (s, u) = (*p).clone();
1095 let s_as_utf16 = s.utf16_units().collect::<Vec<u16>>();
1096 let u_as_string = String::from_utf16(u.as_slice()).unwrap();
1098 assert!(str::is_utf16(u.as_slice()));
1099 assert_eq!(s_as_utf16, u);
1101 assert_eq!(u_as_string, s);
1102 assert_eq!(String::from_utf16_lossy(u.as_slice()), s);
1104 assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
1105 assert_eq!(u_as_string.utf16_units().collect::<Vec<u16>>(), u);
1110 fn test_utf16_invalid() {
1111 // completely positive cases tested above.
1113 assert_eq!(String::from_utf16(&[0xD800]), None);
1115 assert_eq!(String::from_utf16(&[0xD800, 0xD800]), None);
1118 assert_eq!(String::from_utf16(&[0x0061, 0xDC00]), None);
1121 assert_eq!(String::from_utf16(&[0xD800, 0xd801, 0xdc8b, 0xD800]), None);
1125 fn test_from_utf16_lossy() {
1126 // completely positive cases tested above.
1128 assert_eq!(String::from_utf16_lossy(&[0xD800]), String::from_str("\uFFFD"));
1130 assert_eq!(String::from_utf16_lossy(&[0xD800, 0xD800]), String::from_str("\uFFFD\uFFFD"));
1133 assert_eq!(String::from_utf16_lossy(&[0x0061, 0xDC00]), String::from_str("a\uFFFD"));
1136 assert_eq!(String::from_utf16_lossy(&[0xD800, 0xd801, 0xdc8b, 0xD800]),
1137 String::from_str("\uFFFD𐒋\uFFFD"));
1141 fn test_from_buf_len() {
1143 let a = vec![65u8, 65, 65, 65, 65, 65, 65, 0];
1144 assert_eq!(super::raw::from_buf_len(a.as_ptr(), 3), String::from_str("AAA"));
1149 fn test_from_buf() {
1151 let a = vec![65, 65, 65, 65, 65, 65, 65, 0];
1153 let c = super::raw::from_buf(b);
1154 assert_eq!(c, String::from_str("AAAAAAA"));
1159 fn test_push_bytes() {
1160 let mut s = String::from_str("ABC");
1162 let mv = s.as_mut_vec();
1163 mv.push_all(&[b'D']);
1165 assert_eq!(s, "ABCD");
1169 fn test_push_str() {
1170 let mut s = String::new();
1172 assert_eq!(s.slice_from(0), "");
1174 assert_eq!(s.slice_from(0), "abc");
1175 s.push_str("ประเทศไทย中华Việt Nam");
1176 assert_eq!(s.slice_from(0), "abcประเทศไทย中华Việt Nam");
1181 let mut data = String::from_str("ประเทศไทย中");
1183 data.push('b'); // 1 byte
1184 data.push('¢'); // 2 byte
1185 data.push('€'); // 3 byte
1186 data.push('𤭢'); // 4 byte
1187 assert_eq!(data, "ประเทศไทย中华b¢€𤭢");
1192 let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
1193 assert_eq!(data.pop().unwrap(), '𤭢'); // 4 bytes
1194 assert_eq!(data.pop().unwrap(), '€'); // 3 bytes
1195 assert_eq!(data.pop().unwrap(), '¢'); // 2 bytes
1196 assert_eq!(data.pop().unwrap(), 'b'); // 1 bytes
1197 assert_eq!(data.pop().unwrap(), '华');
1198 assert_eq!(data, "ประเทศไทย中");
1202 fn test_str_truncate() {
1203 let mut s = String::from_str("12345");
1205 assert_eq!(s, "12345");
1207 assert_eq!(s, "123");
1211 let mut s = String::from_str("12345");
1215 let p_ = s.as_ptr();
1221 fn test_str_truncate_invalid_len() {
1222 let mut s = String::from_str("12345");
1228 fn test_str_truncate_split_codepoint() {
1229 let mut s = String::from_str("\u00FC"); // ü
1234 fn test_str_clear() {
1235 let mut s = String::from_str("12345");
1237 assert_eq!(s.len(), 0);
1243 let a = String::from_str("12345");
1245 let b = b + String::from_str("2");
1246 assert_eq!(b.len(), 7);
1247 assert_eq!(b, "1234522");
1252 let mut s = "ศไทย中华Việt Nam; foobar".to_string();;
1253 assert_eq!(s.remove(0), Some('ศ'));
1254 assert_eq!(s.len(), 33);
1255 assert_eq!(s, "ไทย中华Việt Nam; foobar");
1256 assert_eq!(s.remove(33), None);
1257 assert_eq!(s.remove(300), None);
1258 assert_eq!(s.remove(17), Some('ệ'));
1259 assert_eq!(s, "ไทย中华Vit Nam; foobar");
1262 #[test] #[should_fail]
1264 "ศ".to_string().remove(1);
1269 let mut s = "foobar".to_string();
1271 assert_eq!(s, "ệfoobar");
1273 assert_eq!(s, "ệfooยbar");
1276 #[test] #[should_fail] fn insert_bad1() { "".to_string().insert(1, 't'); }
1277 #[test] #[should_fail] fn insert_bad2() { "ệ".to_string().insert(1, 't'); }
1281 let s = "foobar".to_string();
1282 assert_eq!("foobar", s[]);
1283 assert_eq!("foo", s[..3]);
1284 assert_eq!("bar", s[3..]);
1285 assert_eq!("oob", s[1..4]);
1289 fn test_simple_types() {
1290 assert_eq!(1i.to_string(), "1");
1291 assert_eq!((-1i).to_string(), "-1");
1292 assert_eq!(200u.to_string(), "200");
1293 assert_eq!(2u8.to_string(), "2");
1294 assert_eq!(true.to_string(), "true");
1295 assert_eq!(false.to_string(), "false");
1296 assert_eq!(().to_string(), "()");
1297 assert_eq!(("hi".to_string()).to_string(), "hi");
1302 let x: Vec<int> = vec![];
1303 assert_eq!(x.to_string(), "[]");
1304 assert_eq!((vec![1i]).to_string(), "[1]");
1305 assert_eq!((vec![1i, 2, 3]).to_string(), "[1, 2, 3]");
1306 assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_string() ==
1307 "[[], [1], [1, 1]]");
1311 fn bench_with_capacity(b: &mut Bencher) {
1313 String::with_capacity(100)
1318 fn bench_push_str(b: &mut Bencher) {
1319 let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
1321 let mut r = String::new();
1327 fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
1328 let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
1329 Lorem ipsum dolor sit amet, consectetur. ";
1331 assert_eq!(100, s.len());
1333 let _ = String::from_utf8_lossy(s);
1338 fn from_utf8_lossy_100_multibyte(b: &mut Bencher) {
1339 let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
1340 assert_eq!(100, s.len());
1342 let _ = String::from_utf8_lossy(s);
1347 fn from_utf8_lossy_invalid(b: &mut Bencher) {
1348 let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1350 let _ = String::from_utf8_lossy(s);
1355 fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
1356 let s = Vec::from_elem(100, 0xF5u8);
1358 let _ = String::from_utf8_lossy(s.as_slice());