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;
23 use {Collection, Mutable, MutableSeq};
26 use str::{CharRange, StrAllocating, MaybeOwned, Owned, Slice};
29 /// A growable string stored as a UTF-8 encoded buffer.
30 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord)]
36 /// Creates a new string buffer initialized with the empty string.
41 /// let mut s = String::new();
44 pub fn new() -> String {
50 /// Creates a new string buffer with the given capacity.
51 /// The string will be able to hold exactly `capacity` bytes without
52 /// reallocating. If `capacity` is 0, the string will not allocate.
57 /// let mut s = String::with_capacity(10);
60 pub fn with_capacity(capacity: uint) -> String {
62 vec: Vec::with_capacity(capacity),
66 /// Creates a new string buffer from the given string.
71 /// let s = String::from_str("hello");
72 /// assert_eq!(s.as_slice(), "hello");
75 pub fn from_str(string: &str) -> String {
77 vec: Vec::from_slice(string.as_bytes())
81 /// Deprecated. Replaced by `string::raw::from_parts`
83 #[deprecated = "Replaced by string::raw::from_parts"]
84 pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut u8) -> String {
85 raw::from_parts(ptr, length, capacity)
89 #[deprecated = "obsoleted by the removal of ~str"]
91 pub fn from_owned_str(string: String) -> String {
95 /// Returns the vector as a string buffer, if possible, taking care not to
98 /// Returns `Err` with the original vector if the vector contains invalid
104 /// let hello_vec = vec![104, 101, 108, 108, 111];
105 /// let s = String::from_utf8(hello_vec);
106 /// assert_eq!(s, Ok("hello".to_string()));
108 /// let invalid_vec = vec![240, 144, 128];
109 /// let s = String::from_utf8(invalid_vec);
110 /// assert_eq!(s, Err(vec![240, 144, 128]));
113 pub fn from_utf8(vec: Vec<u8>) -> Result<String, Vec<u8>> {
114 if str::is_utf8(vec.as_slice()) {
115 Ok(String { vec: vec })
121 /// Converts a vector of bytes to a new utf-8 string.
122 /// Any invalid utf-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
127 /// let input = b"Hello \xF0\x90\x80World";
128 /// let output = String::from_utf8_lossy(input);
129 /// assert_eq!(output.as_slice(), "Hello \uFFFDWorld");
131 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> MaybeOwned<'a> {
133 return Slice(unsafe { mem::transmute(v) })
136 static TAG_CONT_U8: u8 = 128u8;
137 static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
140 fn unsafe_get(xs: &[u8], i: uint) -> u8 {
141 unsafe { *xs.unsafe_ref(i) }
143 fn safe_get(xs: &[u8], i: uint, total: uint) -> u8 {
151 let mut res = String::with_capacity(total);
155 res.push_bytes(v.slice_to(i))
159 // subseqidx is the index of the first byte of the subsequence we're looking at.
160 // It's used to copy a bunch of contiguous good codepoints at once instead of copying
162 let mut subseqidx = 0;
166 let byte = unsafe_get(v, i);
169 macro_rules! error(() => ({
172 res.push_bytes(v.slice(subseqidx, i_));
175 res.push_bytes(REPLACEMENT);
180 // subseqidx handles this
182 let w = str::utf8_char_width(byte);
186 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
193 match (byte, safe_get(v, i, total)) {
194 (0xE0 , 0xA0 .. 0xBF) => (),
195 (0xE1 .. 0xEC, 0x80 .. 0xBF) => (),
196 (0xED , 0x80 .. 0x9F) => (),
197 (0xEE .. 0xEF, 0x80 .. 0xBF) => (),
204 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
211 match (byte, safe_get(v, i, total)) {
212 (0xF0 , 0x90 .. 0xBF) => (),
213 (0xF1 .. 0xF3, 0x80 .. 0xBF) => (),
214 (0xF4 , 0x80 .. 0x8F) => (),
221 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
226 if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
239 if subseqidx < total {
241 res.push_bytes(v.slice(subseqidx, total))
244 Owned(res.into_string())
247 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
248 /// if `v` contains any invalid data.
254 /// let mut v = [0xD834, 0xDD1E, 0x006d, 0x0075,
255 /// 0x0073, 0x0069, 0x0063];
256 /// assert_eq!(String::from_utf16(v), Some("𝄞music".to_string()));
258 /// // 𝄞mu<invalid>ic
260 /// assert_eq!(String::from_utf16(v), None);
262 pub fn from_utf16(v: &[u16]) -> Option<String> {
263 let mut s = String::with_capacity(v.len() / 2);
264 for c in str::utf16_items(v) {
266 str::ScalarValue(c) => s.push_char(c),
267 str::LoneSurrogate(_) => return None
273 /// Decode a UTF-16 encoded vector `v` into a string, replacing
274 /// invalid data with the replacement character (U+FFFD).
278 /// // 𝄞mus<invalid>ic<invalid>
279 /// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
280 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
283 /// assert_eq!(String::from_utf16_lossy(v),
284 /// "𝄞mus\uFFFDic\uFFFD".to_string());
286 pub fn from_utf16_lossy(v: &[u16]) -> String {
287 str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
290 /// Convert a vector of chars to a string.
295 /// let chars = ['h', 'e', 'l', 'l', 'o'];
296 /// let s = String::from_chars(chars);
297 /// assert_eq!(s.as_slice(), "hello");
300 pub fn from_chars(chs: &[char]) -> String {
301 chs.iter().map(|c| *c).collect()
304 /// Return the underlying byte buffer, encoded as UTF-8.
309 /// let s = String::from_str("hello");
310 /// let bytes = s.into_bytes();
311 /// assert_eq!(bytes, vec![104, 101, 108, 108, 111]);
314 pub fn into_bytes(self) -> Vec<u8> {
318 /// Pushes the given string onto this buffer; then, returns `self` so that it can be used
324 /// let s = String::from_str("hello");
325 /// let big = s.append(" ").append("world").append("!");
326 /// // s has now been moved and cannot be used
328 /// assert_eq!(big.as_slice(), "hello world!");
331 pub fn append(mut self, second: &str) -> String {
332 self.push_str(second);
336 /// Creates a string buffer by repeating a character `length` times.
341 /// let s = String::from_char(5, 'a');
342 /// assert_eq!(s.as_slice(), "aaaaa");
345 pub fn from_char(length: uint, ch: char) -> String {
350 let mut buf = String::new();
352 let size = buf.len() * length;
354 for _ in range(1, length) {
360 /// Convert a byte to a UTF-8 string.
364 /// Fails if invalid UTF-8
369 /// let s = String::from_byte(104);
370 /// assert_eq!(s.as_slice(), "h");
372 pub fn from_byte(b: u8) -> String {
374 String::from_char(1, b as char)
377 /// Pushes the given string onto this string buffer.
382 /// let mut s = String::from_str("foo");
383 /// s.push_str("bar");
384 /// assert_eq!(s.as_slice(), "foobar");
387 pub fn push_str(&mut self, string: &str) {
388 self.vec.push_all(string.as_bytes())
391 /// Push `ch` onto the given string `count` times.
396 /// let mut s = String::from_str("foo");
398 /// assert_eq!(s.as_slice(), "fooZZZZZ");
401 pub fn grow(&mut self, count: uint, ch: char) {
402 for _ in range(0, count) {
407 /// Returns the number of bytes that this string buffer can hold without reallocating.
412 /// let s = String::with_capacity(10);
413 /// assert!(s.byte_capacity() >= 10);
416 pub fn byte_capacity(&self) -> uint {
420 /// Reserves capacity for at least `extra` additional bytes in this string buffer.
425 /// let mut s = String::with_capacity(10);
426 /// let before = s.byte_capacity();
427 /// s.reserve_additional(100);
428 /// assert!(s.byte_capacity() - before >= 100);
431 pub fn reserve_additional(&mut self, extra: uint) {
432 self.vec.reserve_additional(extra)
435 /// Reserves capacity for at least `capacity` bytes in this string buffer.
440 /// let mut s = String::new();
442 /// assert!(s.byte_capacity() >= 10);
445 pub fn reserve(&mut self, capacity: uint) {
446 self.vec.reserve(capacity)
449 /// Reserves capacity for exactly `capacity` bytes in this string buffer.
454 /// let mut s = String::new();
455 /// s.reserve_exact(10);
456 /// assert_eq!(s.byte_capacity(), 10);
459 pub fn reserve_exact(&mut self, capacity: uint) {
460 self.vec.reserve_exact(capacity)
463 /// Shrinks the capacity of this string buffer to match its length.
468 /// let mut s = String::from_str("foo");
470 /// assert!(s.byte_capacity() >= 100);
471 /// s.shrink_to_fit();
472 /// assert_eq!(s.byte_capacity(), 3);
475 pub fn shrink_to_fit(&mut self) {
476 self.vec.shrink_to_fit()
479 /// Adds the given character to the end of the string.
484 /// let mut s = String::from_str("abc");
485 /// s.push_char('1');
486 /// s.push_char('2');
487 /// s.push_char('3');
488 /// assert_eq!(s.as_slice(), "abc123");
491 pub fn push_char(&mut self, ch: char) {
492 let cur_len = self.len();
493 // This may use up to 4 bytes.
494 self.vec.reserve_additional(4);
497 // Attempt to not use an intermediate buffer by just pushing bytes
498 // directly onto this string.
500 data: self.vec.as_ptr().offset(cur_len as int),
503 let used = ch.encode_utf8(mem::transmute(slice));
504 self.vec.set_len(cur_len + used);
508 /// Pushes the given bytes onto this string buffer.
509 /// This is unsafe because it does not check
510 /// to ensure that the resulting string will be valid UTF-8.
515 /// let mut s = String::new();
517 /// s.push_bytes([104, 101, 108, 108, 111]);
519 /// assert_eq!(s.as_slice(), "hello");
522 pub unsafe fn push_bytes(&mut self, bytes: &[u8]) {
523 self.vec.push_all(bytes)
526 /// Works with the underlying buffer as a byte slice.
531 /// let s = String::from_str("hello");
532 /// assert_eq!(s.as_bytes(), &[104, 101, 108, 108, 111]);
535 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
539 /// Works with the underlying buffer as a mutable byte slice.
541 /// This is unsafe because it does not check
542 /// to ensure that the resulting string will be valid UTF-8.
547 /// let mut s = String::from_str("hello");
549 /// let bytes = s.as_mut_bytes();
553 /// assert_eq!(s.as_bytes(), &[104, 51, 108, 108, 48]);
554 /// assert_eq!(s.as_slice(), "h3ll0")
557 pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] {
558 self.vec.as_mut_slice()
561 /// Shorten a string to the specified length.
565 /// Fails if `len` > current length.
570 /// let mut s = String::from_str("hello");
572 /// assert_eq!(s.as_slice(), "he");
575 pub fn truncate(&mut self, len: uint) {
576 assert!(self.as_slice().is_char_boundary(len));
577 self.vec.truncate(len)
580 /// Appends a byte to this string buffer.
582 /// This is unsafe because it does not check
583 /// to ensure that the resulting string will be valid UTF-8.
588 /// let mut s = String::from_str("hell");
590 /// s.push_byte(111);
592 /// assert_eq!(s.as_slice(), "hello");
595 pub unsafe fn push_byte(&mut self, byte: u8) {
599 /// Removes the last byte from the string buffer and returns it.
600 /// Returns `None` if this string buffer is empty.
602 /// This is unsafe because it does not check
603 /// to ensure that the resulting string will be valid UTF-8.
608 /// let mut s = String::from_str("foo");
610 /// assert_eq!(s.pop_byte(), Some(111));
611 /// assert_eq!(s.pop_byte(), Some(111));
612 /// assert_eq!(s.pop_byte(), Some(102));
613 /// assert_eq!(s.pop_byte(), None);
617 pub unsafe fn pop_byte(&mut self) -> Option<u8> {
618 let len = self.len();
623 let byte = self.as_bytes()[len - 1];
624 self.vec.set_len(len - 1);
628 /// Removes the last character from the string buffer and returns it.
629 /// Returns `None` if this string buffer is empty.
634 /// let mut s = String::from_str("foo");
635 /// assert_eq!(s.pop_char(), Some('o'));
636 /// assert_eq!(s.pop_char(), Some('o'));
637 /// assert_eq!(s.pop_char(), Some('f'));
638 /// assert_eq!(s.pop_char(), None);
641 pub fn pop_char(&mut self) -> Option<char> {
642 let len = self.len();
647 let CharRange {ch, next} = self.as_slice().char_range_at_reverse(len);
649 self.vec.set_len(next);
654 /// Removes the first byte from the string buffer and returns it.
655 /// Returns `None` if this string buffer is empty.
657 /// This is unsafe because it does not check
658 /// to ensure that the resulting string will be valid UTF-8.
663 /// let mut s = String::from_str("foo");
665 /// assert_eq!(s.shift_byte(), Some(102));
666 /// assert_eq!(s.shift_byte(), Some(111));
667 /// assert_eq!(s.shift_byte(), Some(111));
668 /// assert_eq!(s.shift_byte(), None);
671 pub unsafe fn shift_byte(&mut self) -> Option<u8> {
675 /// Removes the first character from the string buffer and returns it.
676 /// Returns `None` if this string buffer is empty.
680 /// This is a O(n) operation as it requires copying every element in the buffer.
685 /// let mut s = String::from_str("foo");
686 /// assert_eq!(s.shift_char(), Some('f'));
687 /// assert_eq!(s.shift_char(), Some('o'));
688 /// assert_eq!(s.shift_char(), Some('o'));
689 /// assert_eq!(s.shift_char(), None);
691 pub fn shift_char (&mut self) -> Option<char> {
692 let len = self.len();
697 let CharRange {ch, next} = self.as_slice().char_range_at(0);
698 let new_len = len - next;
700 ptr::copy_memory(self.vec.as_mut_ptr(), self.vec.as_ptr().offset(next as int), new_len);
701 self.vec.set_len(new_len);
706 /// Views the string buffer as a mutable sequence of bytes.
708 /// This is unsafe because it does not check
709 /// to ensure that the resulting string will be valid UTF-8.
714 /// let mut s = String::from_str("hello");
716 /// let vec = s.as_mut_vec();
717 /// assert!(vec == &mut vec![104, 101, 108, 108, 111]);
720 /// assert_eq!(s.as_slice(), "olleh");
722 pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
727 impl Collection for String {
729 fn len(&self) -> uint {
734 impl Mutable for String {
736 fn clear(&mut self) {
741 impl FromIterator<char> for String {
742 fn from_iter<I:Iterator<char>>(iterator: I) -> String {
743 let mut buf = String::new();
744 buf.extend(iterator);
749 impl Extendable<char> for String {
750 fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
757 impl Str for String {
759 fn as_slice<'a>(&'a self) -> &'a str {
761 mem::transmute(self.vec.as_slice())
766 impl StrAllocating for String {
768 fn into_string(self) -> String {
773 impl Default for String {
774 fn default() -> String {
779 impl fmt::Show for String {
780 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
781 self.as_slice().fmt(f)
785 impl<H: hash::Writer> hash::Hash<H> for String {
787 fn hash(&self, hasher: &mut H) {
788 self.as_slice().hash(hasher)
792 impl<'a, S: Str> Equiv<S> for String {
794 fn equiv(&self, other: &S) -> bool {
795 self.as_slice() == other.as_slice()
799 impl<S: Str> Add<S, String> for String {
800 fn add(&self, other: &S) -> String {
801 let mut s = String::from_str(self.as_slice());
802 s.push_str(other.as_slice());
807 /// Unsafe operations
810 use core::ptr::RawPtr;
811 use core::raw::Slice;
816 /// Creates a new `String` from length, capacity, and a pointer.
818 /// This is unsafe because:
819 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`
820 /// * We assume that the `Vec` contains valid UTF-8
822 pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
824 vec: Vec::from_raw_parts(length, capacity, buf),
828 /// Create `String` from a *u8 buffer of the given length
830 /// This function is unsafe because of two reasons:
831 /// * A raw pointer is dereferenced and transmuted to `&[u8]`
832 /// * The slice is not checked to see whether it contains valid UTF-8
833 pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
834 use slice::CloneableVector;
835 let slice: &[u8] = mem::transmute(Slice {
839 self::from_utf8(slice.to_vec())
842 /// Create a `String` from a null-terminated *u8 buffer
844 /// This function is unsafe because we dereference memory until we find the NUL character,
845 /// which is not guaranteed to be present. Additionaly, the slice is not checked to see
846 /// whether it contains valid UTF-8
847 pub unsafe fn from_buf(buf: *const u8) -> String {
849 while *buf.offset(len) != 0 {
852 self::from_buf_len(buf, len as uint)
855 /// Converts a vector of bytes to a new `String` without checking if
856 /// it contains valid UTF-8. This is unsafe because it assumes that
857 /// the utf-8-ness of the vector has already been validated.
859 pub unsafe fn from_utf8(bytes: Vec<u8>) -> String {
860 String { vec: bytes }
869 use {Mutable, MutableSeq};
871 use str::{Str, StrSlice, Owned, Slice};
877 let owned: Option<::std::string::String> = from_str("string");
878 assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
882 fn test_from_utf8() {
883 let xs = Vec::from_slice(b"hello");
884 assert_eq!(String::from_utf8(xs), Ok(String::from_str("hello")));
886 let xs = Vec::from_slice("ศไทย中华Việt Nam".as_bytes());
887 assert_eq!(String::from_utf8(xs), Ok(String::from_str("ศไทย中华Việt Nam")));
889 let xs = Vec::from_slice(b"hello\xFF");
890 assert_eq!(String::from_utf8(xs),
891 Err(Vec::from_slice(b"hello\xFF")));
895 fn test_from_utf8_lossy() {
897 assert_eq!(String::from_utf8_lossy(xs), Slice("hello"));
899 let xs = "ศไทย中华Việt Nam".as_bytes();
900 assert_eq!(String::from_utf8_lossy(xs), Slice("ศไทย中华Việt Nam"));
902 let xs = b"Hello\xC2 There\xFF Goodbye";
903 assert_eq!(String::from_utf8_lossy(xs),
904 Owned(String::from_str("Hello\uFFFD There\uFFFD Goodbye")));
906 let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
907 assert_eq!(String::from_utf8_lossy(xs),
908 Owned(String::from_str("Hello\uFFFD\uFFFD There\uFFFD Goodbye")));
910 let xs = b"\xF5foo\xF5\x80bar";
911 assert_eq!(String::from_utf8_lossy(xs),
912 Owned(String::from_str("\uFFFDfoo\uFFFD\uFFFDbar")));
914 let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
915 assert_eq!(String::from_utf8_lossy(xs),
916 Owned(String::from_str("\uFFFDfoo\uFFFDbar\uFFFDbaz")));
918 let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
919 assert_eq!(String::from_utf8_lossy(xs),
920 Owned(String::from_str("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz")));
922 let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
923 assert_eq!(String::from_utf8_lossy(xs), Owned(String::from_str("\uFFFD\uFFFD\uFFFD\uFFFD\
924 foo\U00010000bar")));
927 let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
928 assert_eq!(String::from_utf8_lossy(xs), Owned(String::from_str("\uFFFD\uFFFD\uFFFDfoo\
929 \uFFFD\uFFFD\uFFFDbar")));
933 fn test_from_utf16() {
935 [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"),
936 vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
937 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
938 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
939 0xd800_u16, 0xdf30_u16, 0x000a_u16]),
941 (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"),
942 vec![0xd801_u16, 0xdc12_u16, 0xd801_u16,
943 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
944 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
945 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16,
946 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16,
949 (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"),
950 vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
951 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
952 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
953 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16,
954 0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16,
955 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16,
956 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),
958 (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"),
959 vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
960 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
961 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
962 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16,
963 0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16,
964 0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16,
965 0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16,
966 0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16,
967 0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16,
968 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16,
970 // Issue #12318, even-numbered non-BMP planes
971 (String::from_str("\U00020000"),
972 vec![0xD840, 0xDC00])];
974 for p in pairs.iter() {
975 let (s, u) = (*p).clone();
976 let s_as_utf16 = s.as_slice().utf16_units().collect::<Vec<u16>>();
977 let u_as_string = String::from_utf16(u.as_slice()).unwrap();
979 assert!(str::is_utf16(u.as_slice()));
980 assert_eq!(s_as_utf16, u);
982 assert_eq!(u_as_string, s);
983 assert_eq!(String::from_utf16_lossy(u.as_slice()), s);
985 assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
986 assert_eq!(u_as_string.as_slice().utf16_units().collect::<Vec<u16>>(), u);
991 fn test_utf16_invalid() {
992 // completely positive cases tested above.
994 assert_eq!(String::from_utf16([0xD800]), None);
996 assert_eq!(String::from_utf16([0xD800, 0xD800]), None);
999 assert_eq!(String::from_utf16([0x0061, 0xDC00]), None);
1002 assert_eq!(String::from_utf16([0xD800, 0xd801, 0xdc8b, 0xD800]), None);
1006 fn test_from_utf16_lossy() {
1007 // completely positive cases tested above.
1009 assert_eq!(String::from_utf16_lossy([0xD800]), String::from_str("\uFFFD"));
1011 assert_eq!(String::from_utf16_lossy([0xD800, 0xD800]), String::from_str("\uFFFD\uFFFD"));
1014 assert_eq!(String::from_utf16_lossy([0x0061, 0xDC00]), String::from_str("a\uFFFD"));
1017 assert_eq!(String::from_utf16_lossy([0xD800, 0xd801, 0xdc8b, 0xD800]),
1018 String::from_str("\uFFFD𐒋\uFFFD"));
1022 fn test_from_buf_len() {
1024 let a = vec![65u8, 65, 65, 65, 65, 65, 65, 0];
1025 assert_eq!(super::raw::from_buf_len(a.as_ptr(), 3), String::from_str("AAA"));
1030 fn test_from_buf() {
1032 let a = vec![65, 65, 65, 65, 65, 65, 65, 0];
1034 let c = super::raw::from_buf(b);
1035 assert_eq!(c, String::from_str("AAAAAAA"));
1040 fn test_push_bytes() {
1041 let mut s = String::from_str("ABC");
1043 s.push_bytes([ 'D' as u8 ]);
1045 assert_eq!(s.as_slice(), "ABCD");
1049 fn test_push_str() {
1050 let mut s = String::new();
1052 assert_eq!(s.as_slice().slice_from(0), "");
1054 assert_eq!(s.as_slice().slice_from(0), "abc");
1055 s.push_str("ประเทศไทย中华Việt Nam");
1056 assert_eq!(s.as_slice().slice_from(0), "abcประเทศไทย中华Việt Nam");
1060 fn test_push_char() {
1061 let mut data = String::from_str("ประเทศไทย中");
1062 data.push_char('华');
1063 data.push_char('b'); // 1 byte
1064 data.push_char('¢'); // 2 byte
1065 data.push_char('€'); // 3 byte
1066 data.push_char('𤭢'); // 4 byte
1067 assert_eq!(data.as_slice(), "ประเทศไทย中华b¢€𤭢");
1071 fn test_pop_char() {
1072 let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
1073 assert_eq!(data.pop_char().unwrap(), '𤭢'); // 4 bytes
1074 assert_eq!(data.pop_char().unwrap(), '€'); // 3 bytes
1075 assert_eq!(data.pop_char().unwrap(), '¢'); // 2 bytes
1076 assert_eq!(data.pop_char().unwrap(), 'b'); // 1 bytes
1077 assert_eq!(data.pop_char().unwrap(), '华');
1078 assert_eq!(data.as_slice(), "ประเทศไทย中");
1082 fn test_shift_char() {
1083 let mut data = String::from_str("𤭢€¢b华ประเทศไทย中");
1084 assert_eq!(data.shift_char().unwrap(), '𤭢'); // 4 bytes
1085 assert_eq!(data.shift_char().unwrap(), '€'); // 3 bytes
1086 assert_eq!(data.shift_char().unwrap(), '¢'); // 2 bytes
1087 assert_eq!(data.shift_char().unwrap(), 'b'); // 1 bytes
1088 assert_eq!(data.shift_char().unwrap(), '华');
1089 assert_eq!(data.as_slice(), "ประเทศไทย中");
1093 fn test_str_truncate() {
1094 let mut s = String::from_str("12345");
1096 assert_eq!(s.as_slice(), "12345");
1098 assert_eq!(s.as_slice(), "123");
1100 assert_eq!(s.as_slice(), "");
1102 let mut s = String::from_str("12345");
1103 let p = s.as_slice().as_ptr();
1106 let p_ = s.as_slice().as_ptr();
1112 fn test_str_truncate_invalid_len() {
1113 let mut s = String::from_str("12345");
1119 fn test_str_truncate_split_codepoint() {
1120 let mut s = String::from_str("\u00FC"); // ü
1125 fn test_str_clear() {
1126 let mut s = String::from_str("12345");
1128 assert_eq!(s.len(), 0);
1129 assert_eq!(s.as_slice(), "");
1134 let a = String::from_str("12345");
1136 let b = b + String::from_str("2");
1137 assert_eq!(b.len(), 7);
1138 assert_eq!(b.as_slice(), "1234522");
1142 fn bench_with_capacity(b: &mut Bencher) {
1144 String::with_capacity(100)
1149 fn bench_push_str(b: &mut Bencher) {
1150 let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
1152 let mut r = String::new();
1158 fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
1159 let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
1160 Lorem ipsum dolor sit amet, consectetur. ";
1162 assert_eq!(100, s.len());
1164 let _ = String::from_utf8_lossy(s);
1169 fn from_utf8_lossy_100_multibyte(b: &mut Bencher) {
1170 let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
1171 assert_eq!(100, s.len());
1173 let _ = String::from_utf8_lossy(s);
1178 fn from_utf8_lossy_invalid(b: &mut Bencher) {
1179 let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1181 let _ = String::from_utf8_lossy(s);
1186 fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
1187 let s = Vec::from_elem(100, 0xF5u8);
1189 let _ = String::from_utf8_lossy(s.as_slice());