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;
21 // FIXME: ICE's abound if you import the `Slice` type while importing `Slice` trait
22 use core::raw::Slice as RawSlice;
24 use {Mutable, MutableSeq};
27 use str::{CharRange, StrAllocating, MaybeOwned, Owned};
28 use str::Slice as MaybeOwnedSlice; // So many `Slice`s...
31 /// A growable string stored as a UTF-8 encoded buffer.
32 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord)]
38 /// Creates a new string buffer initialized with the empty string.
43 /// let mut s = String::new();
46 pub fn new() -> String {
52 /// Creates a new string buffer with the given capacity.
53 /// The string will be able to hold exactly `capacity` bytes without
54 /// reallocating. If `capacity` is 0, the string will not allocate.
59 /// let mut s = String::with_capacity(10);
62 pub fn with_capacity(capacity: uint) -> String {
64 vec: Vec::with_capacity(capacity),
68 /// Creates a new string buffer from the given string.
73 /// let s = String::from_str("hello");
74 /// assert_eq!(s.as_slice(), "hello");
77 pub fn from_str(string: &str) -> String {
79 vec: Vec::from_slice(string.as_bytes())
83 /// Deprecated. Replaced by `string::raw::from_parts`
85 #[deprecated = "Replaced by string::raw::from_parts"]
86 pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut u8) -> String {
87 raw::from_parts(ptr, length, capacity)
91 #[deprecated = "obsoleted by the removal of ~str"]
93 pub fn from_owned_str(string: String) -> String {
97 /// Returns the vector as a string buffer, if possible, taking care not to
100 /// Returns `Err` with the original vector if the vector contains invalid
106 /// let hello_vec = vec![104, 101, 108, 108, 111];
107 /// let s = String::from_utf8(hello_vec);
108 /// assert_eq!(s, Ok("hello".to_string()));
110 /// let invalid_vec = vec![240, 144, 128];
111 /// let s = String::from_utf8(invalid_vec);
112 /// assert_eq!(s, Err(vec![240, 144, 128]));
115 pub fn from_utf8(vec: Vec<u8>) -> Result<String, Vec<u8>> {
116 if str::is_utf8(vec.as_slice()) {
117 Ok(String { vec: vec })
123 /// Converts a vector of bytes to a new UTF-8 string.
124 /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
129 /// let input = b"Hello \xF0\x90\x80World";
130 /// let output = String::from_utf8_lossy(input);
131 /// assert_eq!(output.as_slice(), "Hello \uFFFDWorld");
133 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> MaybeOwned<'a> {
135 return MaybeOwnedSlice(unsafe { mem::transmute(v) })
138 static TAG_CONT_U8: u8 = 128u8;
139 static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
142 fn unsafe_get(xs: &[u8], i: uint) -> u8 {
143 unsafe { *xs.unsafe_get(i) }
145 fn safe_get(xs: &[u8], i: uint, total: uint) -> u8 {
153 let mut res = String::with_capacity(total);
157 res.push_bytes(v.slice_to(i))
161 // subseqidx is the index of the first byte of the subsequence we're looking at.
162 // It's used to copy a bunch of contiguous good codepoints at once instead of copying
164 let mut subseqidx = 0;
168 let byte = unsafe_get(v, i);
171 macro_rules! error(() => ({
174 res.push_bytes(v.slice(subseqidx, i_));
177 res.push_bytes(REPLACEMENT);
182 // subseqidx handles this
184 let w = str::utf8_char_width(byte);
188 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
195 match (byte, safe_get(v, i, total)) {
196 (0xE0 , 0xA0 .. 0xBF) => (),
197 (0xE1 .. 0xEC, 0x80 .. 0xBF) => (),
198 (0xED , 0x80 .. 0x9F) => (),
199 (0xEE .. 0xEF, 0x80 .. 0xBF) => (),
206 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
213 match (byte, safe_get(v, i, total)) {
214 (0xF0 , 0x90 .. 0xBF) => (),
215 (0xF1 .. 0xF3, 0x80 .. 0xBF) => (),
216 (0xF4 , 0x80 .. 0x8F) => (),
223 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
228 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
241 if subseqidx < total {
243 res.push_bytes(v.slice(subseqidx, total))
246 Owned(res.into_string())
249 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
250 /// if `v` contains any invalid data.
256 /// let mut v = [0xD834, 0xDD1E, 0x006d, 0x0075,
257 /// 0x0073, 0x0069, 0x0063];
258 /// assert_eq!(String::from_utf16(v), Some("𝄞music".to_string()));
260 /// // 𝄞mu<invalid>ic
262 /// assert_eq!(String::from_utf16(v), None);
264 pub fn from_utf16(v: &[u16]) -> Option<String> {
265 let mut s = String::with_capacity(v.len() / 2);
266 for c in str::utf16_items(v) {
268 str::ScalarValue(c) => s.push_char(c),
269 str::LoneSurrogate(_) => return None
275 /// Decode a UTF-16 encoded vector `v` into a string, replacing
276 /// invalid data with the replacement character (U+FFFD).
280 /// // 𝄞mus<invalid>ic<invalid>
281 /// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
282 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
285 /// assert_eq!(String::from_utf16_lossy(v),
286 /// "𝄞mus\uFFFDic\uFFFD".to_string());
288 pub fn from_utf16_lossy(v: &[u16]) -> String {
289 str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
292 /// Convert a vector of `char`s to a `String`.
297 /// let chars = ['h', 'e', 'l', 'l', 'o'];
298 /// let s = String::from_chars(chars);
299 /// assert_eq!(s.as_slice(), "hello");
302 pub fn from_chars(chs: &[char]) -> String {
303 chs.iter().map(|c| *c).collect()
306 /// Return the underlying byte buffer, encoded as UTF-8.
311 /// let s = String::from_str("hello");
312 /// let bytes = s.into_bytes();
313 /// assert_eq!(bytes, vec![104, 101, 108, 108, 111]);
316 pub fn into_bytes(self) -> Vec<u8> {
320 /// Pushes the given `String` onto this buffer then returns `self` so that it can be
326 /// let s = String::from_str("hello");
327 /// let big = s.append(" ").append("world").append("!");
328 /// // s has now been moved and cannot be used
330 /// assert_eq!(big.as_slice(), "hello world!");
333 pub fn append(mut self, second: &str) -> String {
334 self.push_str(second);
338 /// Creates a string buffer by repeating a character `length` times.
343 /// let s = String::from_char(5, 'a');
344 /// assert_eq!(s.as_slice(), "aaaaa");
347 pub fn from_char(length: uint, ch: char) -> String {
352 let mut buf = String::new();
354 let size = buf.len() * length;
356 for _ in range(1, length) {
362 /// Converts a byte to a UTF-8 string.
366 /// Fails with invalid UTF-8 (i.e., the byte is greater than 127).
371 /// let s = String::from_byte(104);
372 /// assert_eq!(s.as_slice(), "h");
374 pub fn from_byte(b: u8) -> String {
376 String::from_char(1, b as char)
379 /// Pushes the given string onto this string buffer.
384 /// let mut s = String::from_str("foo");
385 /// s.push_str("bar");
386 /// assert_eq!(s.as_slice(), "foobar");
389 pub fn push_str(&mut self, string: &str) {
390 self.vec.push_all(string.as_bytes())
393 /// Pushes `ch` onto the given string `count` times.
398 /// let mut s = String::from_str("foo");
400 /// assert_eq!(s.as_slice(), "fooZZZZZ");
403 pub fn grow(&mut self, count: uint, ch: char) {
404 for _ in range(0, count) {
409 /// Returns the number of bytes that this string buffer can hold without reallocating.
414 /// let s = String::with_capacity(10);
415 /// assert!(s.byte_capacity() >= 10);
418 pub fn byte_capacity(&self) -> uint {
422 /// Reserves capacity for at least `extra` additional bytes in this string buffer.
427 /// let mut s = String::with_capacity(10);
428 /// let before = s.byte_capacity();
429 /// s.reserve_additional(100);
430 /// assert!(s.byte_capacity() - before >= 100);
433 pub fn reserve_additional(&mut self, extra: uint) {
434 self.vec.reserve_additional(extra)
437 /// Reserves capacity for at least `capacity` bytes in this string buffer.
442 /// let mut s = String::new();
444 /// assert!(s.byte_capacity() >= 10);
447 pub fn reserve(&mut self, capacity: uint) {
448 self.vec.reserve(capacity)
451 /// Reserves capacity for exactly `capacity` bytes in this string buffer.
456 /// let mut s = String::new();
457 /// s.reserve_exact(10);
458 /// assert_eq!(s.byte_capacity(), 10);
461 pub fn reserve_exact(&mut self, capacity: uint) {
462 self.vec.reserve_exact(capacity)
465 /// Shrinks the capacity of this string buffer to match its length.
470 /// let mut s = String::from_str("foo");
472 /// assert!(s.byte_capacity() >= 100);
473 /// s.shrink_to_fit();
474 /// assert_eq!(s.byte_capacity(), 3);
477 pub fn shrink_to_fit(&mut self) {
478 self.vec.shrink_to_fit()
481 /// Adds the given character to the end of the string.
486 /// let mut s = String::from_str("abc");
487 /// s.push_char('1');
488 /// s.push_char('2');
489 /// s.push_char('3');
490 /// assert_eq!(s.as_slice(), "abc123");
493 pub fn push_char(&mut self, ch: char) {
494 let cur_len = self.len();
495 // This may use up to 4 bytes.
496 self.vec.reserve_additional(4);
499 // Attempt to not use an intermediate buffer by just pushing bytes
500 // directly onto this string.
501 let slice = RawSlice {
502 data: self.vec.as_ptr().offset(cur_len as int),
505 let used = ch.encode_utf8(mem::transmute(slice)).unwrap_or(0);
506 self.vec.set_len(cur_len + used);
510 /// Pushes the given bytes onto this string buffer.
511 /// This is unsafe because it does not check
512 /// to ensure that the resulting string will be valid UTF-8.
517 /// let mut s = String::new();
519 /// s.push_bytes([104, 101, 108, 108, 111]);
521 /// assert_eq!(s.as_slice(), "hello");
524 pub unsafe fn push_bytes(&mut self, bytes: &[u8]) {
525 self.vec.push_all(bytes)
528 /// Works with the underlying buffer as a byte slice.
533 /// let s = String::from_str("hello");
534 /// let b: &[_] = &[104, 101, 108, 108, 111];
535 /// assert_eq!(s.as_bytes(), b);
538 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
542 /// Works with the underlying buffer as a mutable byte slice.
544 /// This is unsafe because it does not check
545 /// to ensure that the resulting string will be valid UTF-8.
550 /// let mut s = String::from_str("hello");
552 /// let bytes = s.as_mut_bytes();
556 /// let b: &[_] = &[104, 51, 108, 108, 48];
557 /// assert_eq!(s.as_bytes(), b);
558 /// assert_eq!(s.as_slice(), "h3ll0")
561 pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] {
562 self.vec.as_mut_slice()
565 /// Shortens a string to the specified length.
569 /// Fails if `len` > current length.
574 /// let mut s = String::from_str("hello");
576 /// assert_eq!(s.as_slice(), "he");
579 pub fn truncate(&mut self, len: uint) {
580 assert!(self.as_slice().is_char_boundary(len));
581 self.vec.truncate(len)
584 /// Appends a byte to this string buffer.
586 /// This is unsafe because it does not check
587 /// to ensure that the resulting string will be valid UTF-8.
592 /// let mut s = String::from_str("hell");
594 /// s.push_byte(111);
596 /// assert_eq!(s.as_slice(), "hello");
599 pub unsafe fn push_byte(&mut self, byte: u8) {
603 /// Removes the last byte from the string buffer and returns it.
604 /// Returns `None` if this string buffer is empty.
606 /// This is unsafe because it does not check
607 /// to ensure that the resulting string will be valid UTF-8.
612 /// let mut s = String::from_str("foo");
614 /// assert_eq!(s.pop_byte(), Some(111));
615 /// assert_eq!(s.pop_byte(), Some(111));
616 /// assert_eq!(s.pop_byte(), Some(102));
617 /// assert_eq!(s.pop_byte(), None);
621 pub unsafe fn pop_byte(&mut self) -> Option<u8> {
622 let len = self.len();
627 let byte = self.as_bytes()[len - 1];
628 self.vec.set_len(len - 1);
632 /// Removes the last character from the string buffer and returns it.
633 /// Returns `None` if this string buffer is empty.
638 /// let mut s = String::from_str("foo");
639 /// assert_eq!(s.pop_char(), Some('o'));
640 /// assert_eq!(s.pop_char(), Some('o'));
641 /// assert_eq!(s.pop_char(), Some('f'));
642 /// assert_eq!(s.pop_char(), None);
645 pub fn pop_char(&mut self) -> Option<char> {
646 let len = self.len();
651 let CharRange {ch, next} = self.as_slice().char_range_at_reverse(len);
653 self.vec.set_len(next);
658 /// Removes the first byte from the string buffer and returns it.
659 /// Returns `None` if this string buffer is empty.
661 /// This is unsafe because it does not check
662 /// to ensure that the resulting string will be valid UTF-8.
667 /// let mut s = String::from_str("foo");
669 /// assert_eq!(s.shift_byte(), Some(102));
670 /// assert_eq!(s.shift_byte(), Some(111));
671 /// assert_eq!(s.shift_byte(), Some(111));
672 /// assert_eq!(s.shift_byte(), None);
675 pub unsafe fn shift_byte(&mut self) -> Option<u8> {
679 /// Removes the first character from the string buffer and returns it.
680 /// Returns `None` if this string buffer is empty.
684 /// This is a O(n) operation as it requires copying every element in the buffer.
689 /// let mut s = String::from_str("foo");
690 /// assert_eq!(s.shift_char(), Some('f'));
691 /// assert_eq!(s.shift_char(), Some('o'));
692 /// assert_eq!(s.shift_char(), Some('o'));
693 /// assert_eq!(s.shift_char(), None);
695 pub fn shift_char(&mut self) -> Option<char> {
696 let len = self.len();
701 let CharRange {ch, next} = self.as_slice().char_range_at(0);
702 let new_len = len - next;
704 ptr::copy_memory(self.vec.as_mut_ptr(), self.vec.as_ptr().offset(next as int), new_len);
705 self.vec.set_len(new_len);
710 /// Views the string buffer as a mutable sequence of bytes.
712 /// This is unsafe because it does not check
713 /// to ensure that the resulting string will be valid UTF-8.
718 /// let mut s = String::from_str("hello");
720 /// let vec = s.as_mut_vec();
721 /// assert!(vec == &mut vec![104, 101, 108, 108, 111]);
724 /// assert_eq!(s.as_slice(), "olleh");
726 pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
731 impl Collection for String {
733 fn len(&self) -> uint {
738 impl Mutable for String {
740 fn clear(&mut self) {
745 impl FromIterator<char> for String {
746 fn from_iter<I:Iterator<char>>(iterator: I) -> String {
747 let mut buf = String::new();
748 buf.extend(iterator);
753 impl Extendable<char> for String {
754 fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
761 impl Str for String {
763 fn as_slice<'a>(&'a self) -> &'a str {
765 mem::transmute(self.vec.as_slice())
770 impl StrAllocating for String {
772 fn into_string(self) -> String {
777 impl Default for String {
778 fn default() -> String {
783 impl fmt::Show for String {
784 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
785 self.as_slice().fmt(f)
789 impl<H: hash::Writer> hash::Hash<H> for String {
791 fn hash(&self, hasher: &mut H) {
792 self.as_slice().hash(hasher)
796 impl<'a, S: Str> Equiv<S> for String {
798 fn equiv(&self, other: &S) -> bool {
799 self.as_slice() == other.as_slice()
803 impl<S: Str> Add<S, String> for String {
804 fn add(&self, other: &S) -> String {
805 let mut s = String::from_str(self.as_slice());
806 s.push_str(other.as_slice());
811 /// Unsafe operations
814 use core::ptr::RawPtr;
815 use core::raw::Slice;
820 /// Creates a new `String` from a length, capacity, and pointer.
822 /// This is unsafe because:
823 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
824 /// * We assume that the `Vec` contains valid UTF-8.
826 pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
828 vec: Vec::from_raw_parts(length, capacity, buf),
832 /// Creates a `String` from a `*const u8` buffer of the given length.
834 /// This function is unsafe because of two reasons:
835 /// * A raw pointer is dereferenced and transmuted to `&[u8]`;
836 /// * The slice is not checked to see whether it contains valid UTF-8.
837 pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
838 use slice::CloneableVector;
839 let slice: &[u8] = mem::transmute(Slice {
843 self::from_utf8(slice.to_vec())
846 /// Creates a `String` from a null-terminated `*const u8` buffer.
848 /// This function is unsafe because we dereference memory until we find the NUL character,
849 /// which is not guaranteed to be present. Additionally, the slice is not checked to see
850 /// whether it contains valid UTF-8
851 pub unsafe fn from_buf(buf: *const u8) -> String {
853 while *buf.offset(len) != 0 {
856 self::from_buf_len(buf, len as uint)
859 /// Converts a vector of bytes to a new `String` without checking if
860 /// it contains valid UTF-8. This is unsafe because it assumes that
861 /// the UTF-8-ness of the vector has already been validated.
863 pub unsafe fn from_utf8(bytes: Vec<u8>) -> String {
864 String { vec: bytes }
873 use {Mutable, MutableSeq};
875 use str::{Str, StrSlice, Owned};
881 let owned: Option<::std::string::String> = from_str("string");
882 assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
886 fn test_from_utf8() {
887 let xs = Vec::from_slice(b"hello");
888 assert_eq!(String::from_utf8(xs), Ok(String::from_str("hello")));
890 let xs = Vec::from_slice("ศไทย中华Việt Nam".as_bytes());
891 assert_eq!(String::from_utf8(xs), Ok(String::from_str("ศไทย中华Việt Nam")));
893 let xs = Vec::from_slice(b"hello\xFF");
894 assert_eq!(String::from_utf8(xs),
895 Err(Vec::from_slice(b"hello\xFF")));
899 fn test_from_utf8_lossy() {
901 assert_eq!(String::from_utf8_lossy(xs), str::Slice("hello"));
903 let xs = "ศไทย中华Việt Nam".as_bytes();
904 assert_eq!(String::from_utf8_lossy(xs), str::Slice("ศไทย中华Việt Nam"));
906 let xs = b"Hello\xC2 There\xFF Goodbye";
907 assert_eq!(String::from_utf8_lossy(xs),
908 Owned(String::from_str("Hello\uFFFD There\uFFFD Goodbye")));
910 let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
911 assert_eq!(String::from_utf8_lossy(xs),
912 Owned(String::from_str("Hello\uFFFD\uFFFD There\uFFFD Goodbye")));
914 let xs = b"\xF5foo\xF5\x80bar";
915 assert_eq!(String::from_utf8_lossy(xs),
916 Owned(String::from_str("\uFFFDfoo\uFFFD\uFFFDbar")));
918 let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
919 assert_eq!(String::from_utf8_lossy(xs),
920 Owned(String::from_str("\uFFFDfoo\uFFFDbar\uFFFDbaz")));
922 let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
923 assert_eq!(String::from_utf8_lossy(xs),
924 Owned(String::from_str("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz")));
926 let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
927 assert_eq!(String::from_utf8_lossy(xs), Owned(String::from_str("\uFFFD\uFFFD\uFFFD\uFFFD\
928 foo\U00010000bar")));
931 let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
932 assert_eq!(String::from_utf8_lossy(xs), Owned(String::from_str("\uFFFD\uFFFD\uFFFDfoo\
933 \uFFFD\uFFFD\uFFFDbar")));
937 fn test_from_utf16() {
939 [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"),
940 vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
941 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
942 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
943 0xd800_u16, 0xdf30_u16, 0x000a_u16]),
945 (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"),
946 vec![0xd801_u16, 0xdc12_u16, 0xd801_u16,
947 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
948 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
949 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16,
950 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16,
953 (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"),
954 vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
955 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
956 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
957 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16,
958 0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16,
959 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16,
960 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),
962 (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"),
963 vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
964 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
965 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
966 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16,
967 0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16,
968 0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16,
969 0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16,
970 0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16,
971 0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16,
972 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16,
974 // Issue #12318, even-numbered non-BMP planes
975 (String::from_str("\U00020000"),
976 vec![0xD840, 0xDC00])];
978 for p in pairs.iter() {
979 let (s, u) = (*p).clone();
980 let s_as_utf16 = s.as_slice().utf16_units().collect::<Vec<u16>>();
981 let u_as_string = String::from_utf16(u.as_slice()).unwrap();
983 assert!(str::is_utf16(u.as_slice()));
984 assert_eq!(s_as_utf16, u);
986 assert_eq!(u_as_string, s);
987 assert_eq!(String::from_utf16_lossy(u.as_slice()), s);
989 assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
990 assert_eq!(u_as_string.as_slice().utf16_units().collect::<Vec<u16>>(), u);
995 fn test_utf16_invalid() {
996 // completely positive cases tested above.
998 assert_eq!(String::from_utf16([0xD800]), None);
1000 assert_eq!(String::from_utf16([0xD800, 0xD800]), None);
1003 assert_eq!(String::from_utf16([0x0061, 0xDC00]), None);
1006 assert_eq!(String::from_utf16([0xD800, 0xd801, 0xdc8b, 0xD800]), None);
1010 fn test_from_utf16_lossy() {
1011 // completely positive cases tested above.
1013 assert_eq!(String::from_utf16_lossy([0xD800]), String::from_str("\uFFFD"));
1015 assert_eq!(String::from_utf16_lossy([0xD800, 0xD800]), String::from_str("\uFFFD\uFFFD"));
1018 assert_eq!(String::from_utf16_lossy([0x0061, 0xDC00]), String::from_str("a\uFFFD"));
1021 assert_eq!(String::from_utf16_lossy([0xD800, 0xd801, 0xdc8b, 0xD800]),
1022 String::from_str("\uFFFD𐒋\uFFFD"));
1026 fn test_from_buf_len() {
1028 let a = vec![65u8, 65, 65, 65, 65, 65, 65, 0];
1029 assert_eq!(super::raw::from_buf_len(a.as_ptr(), 3), String::from_str("AAA"));
1034 fn test_from_buf() {
1036 let a = vec![65, 65, 65, 65, 65, 65, 65, 0];
1038 let c = super::raw::from_buf(b);
1039 assert_eq!(c, String::from_str("AAAAAAA"));
1044 fn test_push_bytes() {
1045 let mut s = String::from_str("ABC");
1047 s.push_bytes([b'D']);
1049 assert_eq!(s.as_slice(), "ABCD");
1053 fn test_push_str() {
1054 let mut s = String::new();
1056 assert_eq!(s.as_slice().slice_from(0), "");
1058 assert_eq!(s.as_slice().slice_from(0), "abc");
1059 s.push_str("ประเทศไทย中华Việt Nam");
1060 assert_eq!(s.as_slice().slice_from(0), "abcประเทศไทย中华Việt Nam");
1064 fn test_push_char() {
1065 let mut data = String::from_str("ประเทศไทย中");
1066 data.push_char('华');
1067 data.push_char('b'); // 1 byte
1068 data.push_char('¢'); // 2 byte
1069 data.push_char('€'); // 3 byte
1070 data.push_char('𤭢'); // 4 byte
1071 assert_eq!(data.as_slice(), "ประเทศไทย中华b¢€𤭢");
1075 fn test_pop_char() {
1076 let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
1077 assert_eq!(data.pop_char().unwrap(), '𤭢'); // 4 bytes
1078 assert_eq!(data.pop_char().unwrap(), '€'); // 3 bytes
1079 assert_eq!(data.pop_char().unwrap(), '¢'); // 2 bytes
1080 assert_eq!(data.pop_char().unwrap(), 'b'); // 1 bytes
1081 assert_eq!(data.pop_char().unwrap(), '华');
1082 assert_eq!(data.as_slice(), "ประเทศไทย中");
1086 fn test_shift_char() {
1087 let mut data = String::from_str("𤭢€¢b华ประเทศไทย中");
1088 assert_eq!(data.shift_char().unwrap(), '𤭢'); // 4 bytes
1089 assert_eq!(data.shift_char().unwrap(), '€'); // 3 bytes
1090 assert_eq!(data.shift_char().unwrap(), '¢'); // 2 bytes
1091 assert_eq!(data.shift_char().unwrap(), 'b'); // 1 bytes
1092 assert_eq!(data.shift_char().unwrap(), '华');
1093 assert_eq!(data.as_slice(), "ประเทศไทย中");
1097 fn test_str_truncate() {
1098 let mut s = String::from_str("12345");
1100 assert_eq!(s.as_slice(), "12345");
1102 assert_eq!(s.as_slice(), "123");
1104 assert_eq!(s.as_slice(), "");
1106 let mut s = String::from_str("12345");
1107 let p = s.as_slice().as_ptr();
1110 let p_ = s.as_slice().as_ptr();
1116 fn test_str_truncate_invalid_len() {
1117 let mut s = String::from_str("12345");
1123 fn test_str_truncate_split_codepoint() {
1124 let mut s = String::from_str("\u00FC"); // ü
1129 fn test_str_clear() {
1130 let mut s = String::from_str("12345");
1132 assert_eq!(s.len(), 0);
1133 assert_eq!(s.as_slice(), "");
1138 let a = String::from_str("12345");
1140 let b = b + String::from_str("2");
1141 assert_eq!(b.len(), 7);
1142 assert_eq!(b.as_slice(), "1234522");
1146 fn bench_with_capacity(b: &mut Bencher) {
1148 String::with_capacity(100)
1153 fn bench_push_str(b: &mut Bencher) {
1154 let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
1156 let mut r = String::new();
1162 fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
1163 let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
1164 Lorem ipsum dolor sit amet, consectetur. ";
1166 assert_eq!(100, s.len());
1168 let _ = String::from_utf8_lossy(s);
1173 fn from_utf8_lossy_100_multibyte(b: &mut Bencher) {
1174 let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
1175 assert_eq!(100, s.len());
1177 let _ = String::from_utf8_lossy(s);
1182 fn from_utf8_lossy_invalid(b: &mut Bencher) {
1183 let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1185 let _ = String::from_utf8_lossy(s);
1190 fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
1191 let s = Vec::from_elem(100, 0xF5u8);
1193 let _ = String::from_utf8_lossy(s.as_slice());