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::default::Default;
22 // FIXME: ICE's abound if you import the `Slice` type while importing `Slice` trait
23 use core::raw::Slice as RawSlice;
26 use slice::CloneSliceAllocPrelude;
28 use str::{CharRange, StrAllocating, MaybeOwned, Owned};
29 use str::Slice as MaybeOwnedSlice; // So many `Slice`s...
30 use vec::{DerefVec, Vec, as_vec};
32 /// A growable string stored as a UTF-8 encoded buffer.
33 #[deriving(Clone, PartialEq, 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]) -> MaybeOwned<'a> {
126 return MaybeOwnedSlice(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 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 = [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 /// Return the underlying byte buffer, encoded as UTF-8.
305 /// let s = String::from_str("hello");
306 /// let bytes = s.into_bytes();
307 /// assert_eq!(bytes, vec![104, 101, 108, 108, 111]);
311 pub fn into_bytes(self) -> Vec<u8> {
315 /// Creates a string buffer by repeating a character `length` times.
320 /// let s = String::from_char(5, 'a');
321 /// assert_eq!(s.as_slice(), "aaaaa");
324 #[unstable = "may be replaced with iterators, questionable usability, and \
325 the name may change"]
326 pub fn from_char(length: uint, ch: char) -> String {
331 let mut buf = String::new();
333 let size = buf.len() * (length - 1);
334 buf.reserve_exact(size);
335 for _ in range(1, length) {
341 /// Pushes the given string onto this string buffer.
346 /// let mut s = String::from_str("foo");
347 /// s.push_str("bar");
348 /// assert_eq!(s.as_slice(), "foobar");
351 #[unstable = "extra variants of `push`, could possibly be based on iterators"]
352 pub fn push_str(&mut self, string: &str) {
353 self.vec.push_all(string.as_bytes())
356 /// Pushes `ch` onto the given string `count` times.
361 /// let mut s = String::from_str("foo");
363 /// assert_eq!(s.as_slice(), "fooZZZZZ");
366 #[unstable = "duplicate of iterator-based functionality"]
367 pub fn grow(&mut self, count: uint, ch: char) {
368 for _ in range(0, count) {
373 /// Returns the number of bytes that this string buffer can hold without reallocating.
378 /// let s = String::with_capacity(10);
379 /// assert!(s.capacity() >= 10);
382 #[unstable = "matches collection reform specification, waiting for dust to settle"]
383 pub fn capacity(&self) -> uint {
387 /// Deprecated: Renamed to `reserve`.
388 #[deprecated = "Renamed to `reserve`"]
389 pub fn reserve_additional(&mut self, extra: uint) {
390 self.vec.reserve(extra)
393 /// Reserves capacity for at least `additional` more bytes to be inserted in the given
394 /// `String`. The collection may reserve more space to avoid frequent reallocations.
398 /// Panics if the new capacity overflows `uint`.
403 /// let mut s = String::new();
405 /// assert!(s.capacity() >= 10);
408 #[unstable = "matches collection reform specification, waiting for dust to settle"]
409 pub fn reserve(&mut self, additional: uint) {
410 self.vec.reserve(additional)
413 /// Reserves the minimum capacity for exactly `additional` more bytes to be inserted in the
414 /// given `String`. Does nothing if the capacity is already sufficient.
416 /// Note that the allocator may give the collection more space than it requests. Therefore
417 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
418 /// insertions are expected.
422 /// Panics if the new capacity overflows `uint`.
427 /// let mut s = String::new();
429 /// assert!(s.capacity() >= 10);
432 #[unstable = "matches collection reform specification, waiting for dust to settle"]
433 pub fn reserve_exact(&mut self, additional: uint) {
434 self.vec.reserve_exact(additional)
437 /// Shrinks the capacity of this string buffer to match its length.
442 /// let mut s = String::from_str("foo");
444 /// assert!(s.capacity() >= 100);
445 /// s.shrink_to_fit();
446 /// assert_eq!(s.capacity(), 3);
449 #[unstable = "matches collection reform specification, waiting for dust to settle"]
450 pub fn shrink_to_fit(&mut self) {
451 self.vec.shrink_to_fit()
454 /// Adds the given character to the end of the string.
459 /// let mut s = String::from_str("abc");
463 /// assert_eq!(s.as_slice(), "abc123");
466 #[stable = "function just renamed from push_char"]
467 pub fn push(&mut self, ch: char) {
468 let cur_len = self.len();
469 // This may use up to 4 bytes.
473 // Attempt to not use an intermediate buffer by just pushing bytes
474 // directly onto this string.
475 let slice = RawSlice {
476 data: self.vec.as_ptr().offset(cur_len as int),
479 let used = ch.encode_utf8(mem::transmute(slice)).unwrap_or(0);
480 self.vec.set_len(cur_len + used);
484 /// Works with the underlying buffer as a byte slice.
489 /// let s = String::from_str("hello");
490 /// let b: &[_] = &[104, 101, 108, 108, 111];
491 /// assert_eq!(s.as_bytes(), b);
495 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
499 /// Shortens a string to the specified length.
503 /// Fails if `new_len` > current length,
504 /// or if `new_len` is not a character boundary.
509 /// let mut s = String::from_str("hello");
511 /// assert_eq!(s.as_slice(), "he");
514 #[unstable = "the panic conventions for strings are under development"]
515 pub fn truncate(&mut self, new_len: uint) {
516 assert!(self.as_slice().is_char_boundary(new_len));
517 self.vec.truncate(new_len)
520 /// Removes the last character from the string buffer and returns it.
521 /// Returns `None` if this string buffer is empty.
526 /// let mut s = String::from_str("foo");
527 /// assert_eq!(s.pop(), Some('o'));
528 /// assert_eq!(s.pop(), Some('o'));
529 /// assert_eq!(s.pop(), Some('f'));
530 /// assert_eq!(s.pop(), None);
533 #[unstable = "this function was just renamed from pop_char"]
534 pub fn pop(&mut self) -> Option<char> {
535 let len = self.len();
540 let CharRange {ch, next} = self.as_slice().char_range_at_reverse(len);
542 self.vec.set_len(next);
547 /// Removes the character from the string buffer at byte position `idx` and
548 /// returns it. Returns `None` if `idx` is out of bounds.
552 /// This is a O(n) operation as it requires copying every element in the
557 /// If `idx` does not lie on a character boundary, then this function will
563 /// let mut s = String::from_str("foo");
564 /// assert_eq!(s.remove(0), Some('f'));
565 /// assert_eq!(s.remove(1), Some('o'));
566 /// assert_eq!(s.remove(0), Some('o'));
567 /// assert_eq!(s.remove(0), None);
569 #[unstable = "the panic semantics of this function and return type \
571 pub fn remove(&mut self, idx: uint) -> Option<char> {
572 let len = self.len();
573 if idx >= len { return None }
575 let CharRange { ch, next } = self.as_slice().char_range_at(idx);
577 ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
578 self.vec.as_ptr().offset(next as int),
580 self.vec.set_len(len - (next - idx));
585 /// Insert a character into the string buffer at byte position `idx`.
589 /// This is a O(n) operation as it requires copying every element in the
594 /// If `idx` does not lie on a character boundary or is out of bounds, then
595 /// this function will panic.
596 #[unstable = "the panic semantics of this function are uncertain"]
597 pub fn insert(&mut self, idx: uint, ch: char) {
598 let len = self.len();
600 assert!(self.as_slice().is_char_boundary(idx));
602 let mut bits = [0, ..4];
603 let amt = ch.encode_utf8(bits).unwrap();
606 ptr::copy_memory(self.vec.as_mut_ptr().offset((idx + amt) as int),
607 self.vec.as_ptr().offset(idx as int),
609 ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
612 self.vec.set_len(len + amt);
616 /// Views the string buffer as a mutable sequence of bytes.
618 /// This is unsafe because it does not check
619 /// to ensure that the resulting string will be valid UTF-8.
624 /// let mut s = String::from_str("hello");
626 /// let vec = s.as_mut_vec();
627 /// assert!(vec == &mut vec![104, 101, 108, 108, 111]);
630 /// assert_eq!(s.as_slice(), "olleh");
632 #[unstable = "the name of this method may be changed"]
633 pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
637 /// Return the number of bytes in this string.
642 /// let a = "foo".to_string();
643 /// assert_eq!(a.len(), 3);
647 pub fn len(&self) -> uint { self.vec.len() }
649 /// Returns true if the string contains no bytes
654 /// let mut v = String::new();
655 /// assert!(v.is_empty());
657 /// assert!(!v.is_empty());
659 pub fn is_empty(&self) -> bool { self.len() == 0 }
661 /// Truncates the string, returning it to 0 length.
666 /// let mut s = "foo".to_string();
668 /// assert!(s.is_empty());
672 pub fn clear(&mut self) {
677 #[experimental = "waiting on FromIterator stabilization"]
678 impl FromIterator<char> for String {
679 fn from_iter<I:Iterator<char>>(iterator: I) -> String {
680 let mut buf = String::new();
681 buf.extend(iterator);
686 #[experimental = "waiting on Extend stabilization"]
687 impl Extend<char> for String {
688 fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
695 #[experimental = "waiting on Str stabilization"]
696 impl Str for String {
699 fn as_slice<'a>(&'a self) -> &'a str {
701 mem::transmute(self.vec.as_slice())
706 #[experimental = "waiting on StrAllocating stabilization"]
707 impl StrAllocating for String {
709 fn into_string(self) -> String {
715 impl Default for String {
716 fn default() -> String {
721 #[experimental = "waiting on Show stabilization"]
722 impl fmt::Show for String {
723 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
724 self.as_slice().fmt(f)
728 #[experimental = "waiting on Hash stabilization"]
729 impl<H: hash::Writer> hash::Hash<H> for String {
731 fn hash(&self, hasher: &mut H) {
732 self.as_slice().hash(hasher)
736 #[experimental = "waiting on Equiv stabilization"]
737 impl<'a, S: Str> Equiv<S> for String {
739 fn equiv(&self, other: &S) -> bool {
740 self.as_slice() == other.as_slice()
744 #[experimental = "waiting on Add stabilization"]
745 impl<S: Str> Add<S, String> for String {
746 fn add(&self, other: &S) -> String {
747 let mut s = String::from_str(self.as_slice());
748 s.push_str(other.as_slice());
753 impl ops::Slice<uint, str> for String {
755 fn as_slice_<'a>(&'a self) -> &'a str {
760 fn slice_from_or_fail<'a>(&'a self, from: &uint) -> &'a str {
765 fn slice_to_or_fail<'a>(&'a self, to: &uint) -> &'a str {
770 fn slice_or_fail<'a>(&'a self, from: &uint, to: &uint) -> &'a str {
775 #[experimental = "waiting on Deref stabilization"]
776 impl ops::Deref<str> for String {
777 fn deref<'a>(&'a self) -> &'a str { self.as_slice() }
780 /// Wrapper type providing a `&String` reference via `Deref`.
782 pub struct DerefString<'a> {
786 impl<'a> Deref<String> for DerefString<'a> {
787 fn deref<'b>(&'b self) -> &'b String {
788 unsafe { mem::transmute(&*self.x) }
792 /// Convert a string slice to a wrapper type providing a `&String` reference.
794 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
795 DerefString { x: as_vec(x.as_bytes()) }
798 /// Unsafe operations
799 #[unstable = "waiting on raw module conventions"]
802 use core::ptr::RawPtr;
803 use core::raw::Slice;
808 /// Creates a new `String` from a length, capacity, and pointer.
810 /// This is unsafe because:
811 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
812 /// * We assume that the `Vec` contains valid UTF-8.
814 pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
816 vec: Vec::from_raw_parts(buf, length, capacity),
820 /// Creates a `String` from a `*const u8` buffer of the given length.
822 /// This function is unsafe because of two reasons:
823 /// * A raw pointer is dereferenced and transmuted to `&[u8]`;
824 /// * The slice is not checked to see whether it contains valid UTF-8.
825 pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
826 use slice::CloneSliceAllocPrelude;
827 let slice: &[u8] = mem::transmute(Slice {
831 self::from_utf8(slice.to_vec())
834 /// Creates a `String` from a null-terminated `*const u8` buffer.
836 /// This function is unsafe because we dereference memory until we find the NUL character,
837 /// which is not guaranteed to be present. Additionally, the slice is not checked to see
838 /// whether it contains valid UTF-8
839 pub unsafe fn from_buf(buf: *const u8) -> String {
841 while *buf.offset(len) != 0 {
844 self::from_buf_len(buf, len as uint)
847 /// Converts a vector of bytes to a new `String` without checking if
848 /// it contains valid UTF-8. This is unsafe because it assumes that
849 /// the UTF-8-ness of the vector has already been validated.
851 pub unsafe fn from_utf8(bytes: Vec<u8>) -> String {
852 String { vec: bytes }
862 use str::{Str, StrPrelude, Owned};
863 use super::{as_string, String};
865 use slice::CloneSliceAllocPrelude;
868 fn test_as_string() {
870 assert_eq!(x, as_string(x).as_slice());
875 let owned: Option<::std::string::String> = from_str("string");
876 assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
880 fn test_from_utf8() {
881 let xs = b"hello".to_vec();
882 assert_eq!(String::from_utf8(xs), Ok(String::from_str("hello")));
884 let xs = "ศไทย中华Việt Nam".as_bytes().to_vec();
885 assert_eq!(String::from_utf8(xs), Ok(String::from_str("ศไทย中华Việt Nam")));
887 let xs = b"hello\xFF".to_vec();
888 assert_eq!(String::from_utf8(xs),
889 Err(b"hello\xFF".to_vec()));
893 fn test_from_utf8_lossy() {
895 assert_eq!(String::from_utf8_lossy(xs), str::Slice("hello"));
897 let xs = "ศไทย中华Việt Nam".as_bytes();
898 assert_eq!(String::from_utf8_lossy(xs), str::Slice("ศไทย中华Việt Nam"));
900 let xs = b"Hello\xC2 There\xFF Goodbye";
901 assert_eq!(String::from_utf8_lossy(xs),
902 Owned(String::from_str("Hello\uFFFD There\uFFFD Goodbye")));
904 let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
905 assert_eq!(String::from_utf8_lossy(xs),
906 Owned(String::from_str("Hello\uFFFD\uFFFD There\uFFFD Goodbye")));
908 let xs = b"\xF5foo\xF5\x80bar";
909 assert_eq!(String::from_utf8_lossy(xs),
910 Owned(String::from_str("\uFFFDfoo\uFFFD\uFFFDbar")));
912 let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
913 assert_eq!(String::from_utf8_lossy(xs),
914 Owned(String::from_str("\uFFFDfoo\uFFFDbar\uFFFDbaz")));
916 let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
917 assert_eq!(String::from_utf8_lossy(xs),
918 Owned(String::from_str("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz")));
920 let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
921 assert_eq!(String::from_utf8_lossy(xs), Owned(String::from_str("\uFFFD\uFFFD\uFFFD\uFFFD\
922 foo\U00010000bar")));
925 let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
926 assert_eq!(String::from_utf8_lossy(xs), Owned(String::from_str("\uFFFD\uFFFD\uFFFDfoo\
927 \uFFFD\uFFFD\uFFFDbar")));
931 fn test_from_utf16() {
933 [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"),
934 vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
935 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
936 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
937 0xd800_u16, 0xdf30_u16, 0x000a_u16]),
939 (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"),
940 vec![0xd801_u16, 0xdc12_u16, 0xd801_u16,
941 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
942 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
943 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16,
944 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16,
947 (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"),
948 vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
949 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
950 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
951 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16,
952 0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16,
953 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16,
954 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),
956 (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"),
957 vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
958 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
959 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
960 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16,
961 0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16,
962 0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16,
963 0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16,
964 0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16,
965 0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16,
966 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16,
968 // Issue #12318, even-numbered non-BMP planes
969 (String::from_str("\U00020000"),
970 vec![0xD840, 0xDC00])];
972 for p in pairs.iter() {
973 let (s, u) = (*p).clone();
974 let s_as_utf16 = s.as_slice().utf16_units().collect::<Vec<u16>>();
975 let u_as_string = String::from_utf16(u.as_slice()).unwrap();
977 assert!(str::is_utf16(u.as_slice()));
978 assert_eq!(s_as_utf16, u);
980 assert_eq!(u_as_string, s);
981 assert_eq!(String::from_utf16_lossy(u.as_slice()), s);
983 assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
984 assert_eq!(u_as_string.as_slice().utf16_units().collect::<Vec<u16>>(), u);
989 fn test_utf16_invalid() {
990 // completely positive cases tested above.
992 assert_eq!(String::from_utf16([0xD800]), None);
994 assert_eq!(String::from_utf16([0xD800, 0xD800]), None);
997 assert_eq!(String::from_utf16([0x0061, 0xDC00]), None);
1000 assert_eq!(String::from_utf16([0xD800, 0xd801, 0xdc8b, 0xD800]), None);
1004 fn test_from_utf16_lossy() {
1005 // completely positive cases tested above.
1007 assert_eq!(String::from_utf16_lossy([0xD800]), String::from_str("\uFFFD"));
1009 assert_eq!(String::from_utf16_lossy([0xD800, 0xD800]), String::from_str("\uFFFD\uFFFD"));
1012 assert_eq!(String::from_utf16_lossy([0x0061, 0xDC00]), String::from_str("a\uFFFD"));
1015 assert_eq!(String::from_utf16_lossy([0xD800, 0xd801, 0xdc8b, 0xD800]),
1016 String::from_str("\uFFFD𐒋\uFFFD"));
1020 fn test_from_buf_len() {
1022 let a = vec![65u8, 65, 65, 65, 65, 65, 65, 0];
1023 assert_eq!(super::raw::from_buf_len(a.as_ptr(), 3), String::from_str("AAA"));
1028 fn test_from_buf() {
1030 let a = vec![65, 65, 65, 65, 65, 65, 65, 0];
1032 let c = super::raw::from_buf(b);
1033 assert_eq!(c, String::from_str("AAAAAAA"));
1038 fn test_push_bytes() {
1039 let mut s = String::from_str("ABC");
1041 let mv = s.as_mut_vec();
1042 mv.push_all([b'D']);
1044 assert_eq!(s.as_slice(), "ABCD");
1048 fn test_push_str() {
1049 let mut s = String::new();
1051 assert_eq!(s.as_slice().slice_from(0), "");
1053 assert_eq!(s.as_slice().slice_from(0), "abc");
1054 s.push_str("ประเทศไทย中华Việt Nam");
1055 assert_eq!(s.as_slice().slice_from(0), "abcประเทศไทย中华Việt Nam");
1060 let mut data = String::from_str("ประเทศไทย中");
1062 data.push('b'); // 1 byte
1063 data.push('¢'); // 2 byte
1064 data.push('€'); // 3 byte
1065 data.push('𤭢'); // 4 byte
1066 assert_eq!(data.as_slice(), "ประเทศไทย中华b¢€𤭢");
1071 let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
1072 assert_eq!(data.pop().unwrap(), '𤭢'); // 4 bytes
1073 assert_eq!(data.pop().unwrap(), '€'); // 3 bytes
1074 assert_eq!(data.pop().unwrap(), '¢'); // 2 bytes
1075 assert_eq!(data.pop().unwrap(), 'b'); // 1 bytes
1076 assert_eq!(data.pop().unwrap(), '华');
1077 assert_eq!(data.as_slice(), "ประเทศไทย中");
1081 fn test_str_truncate() {
1082 let mut s = String::from_str("12345");
1084 assert_eq!(s.as_slice(), "12345");
1086 assert_eq!(s.as_slice(), "123");
1088 assert_eq!(s.as_slice(), "");
1090 let mut s = String::from_str("12345");
1091 let p = s.as_slice().as_ptr();
1094 let p_ = s.as_slice().as_ptr();
1100 fn test_str_truncate_invalid_len() {
1101 let mut s = String::from_str("12345");
1107 fn test_str_truncate_split_codepoint() {
1108 let mut s = String::from_str("\u00FC"); // ü
1113 fn test_str_clear() {
1114 let mut s = String::from_str("12345");
1116 assert_eq!(s.len(), 0);
1117 assert_eq!(s.as_slice(), "");
1122 let a = String::from_str("12345");
1124 let b = b + String::from_str("2");
1125 assert_eq!(b.len(), 7);
1126 assert_eq!(b.as_slice(), "1234522");
1131 let mut s = "ศไทย中华Việt Nam; foobar".to_string();;
1132 assert_eq!(s.remove(0), Some('ศ'));
1133 assert_eq!(s.len(), 33);
1134 assert_eq!(s.as_slice(), "ไทย中华Việt Nam; foobar");
1135 assert_eq!(s.remove(33), None);
1136 assert_eq!(s.remove(300), None);
1137 assert_eq!(s.remove(17), Some('ệ'));
1138 assert_eq!(s.as_slice(), "ไทย中华Vit Nam; foobar");
1141 #[test] #[should_fail]
1143 "ศ".to_string().remove(1);
1148 let mut s = "foobar".to_string();
1150 assert_eq!(s.as_slice(), "ệfoobar");
1152 assert_eq!(s.as_slice(), "ệfooยbar");
1155 #[test] #[should_fail] fn insert_bad1() { "".to_string().insert(1, 't'); }
1156 #[test] #[should_fail] fn insert_bad2() { "ệ".to_string().insert(1, 't'); }
1160 let s = "foobar".to_string();
1161 assert_eq!("foobar", s[]);
1162 assert_eq!("foo", s[..3]);
1163 assert_eq!("bar", s[3..]);
1164 assert_eq!("oob", s[1..4]);
1168 fn bench_with_capacity(b: &mut Bencher) {
1170 String::with_capacity(100)
1175 fn bench_push_str(b: &mut Bencher) {
1176 let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
1178 let mut r = String::new();
1184 fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
1185 let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
1186 Lorem ipsum dolor sit amet, consectetur. ";
1188 assert_eq!(100, s.len());
1190 let _ = String::from_utf8_lossy(s);
1195 fn from_utf8_lossy_100_multibyte(b: &mut Bencher) {
1196 let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
1197 assert_eq!(100, s.len());
1199 let _ = String::from_utf8_lossy(s);
1204 fn from_utf8_lossy_invalid(b: &mut Bencher) {
1205 let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1207 let _ = String::from_utf8_lossy(s);
1212 fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
1213 let s = Vec::from_elem(100, 0xF5u8);
1215 let _ = String::from_utf8_lossy(s.as_slice());