]> git.lizzy.rs Git - rust.git/blob - src/libcollections/string.rs
string: Add test for FromIterator<&str> and Extend<&str>
[rust.git] / src / libcollections / string.rs
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.
4 //
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.
10 //
11 // ignore-lexer-test FIXME #15679
12
13 //! An owned, growable string that enforces that its contents are valid UTF-8.
14
15 use core::prelude::*;
16
17 use core::borrow::{Cow, IntoCow};
18 use core::default::Default;
19 use core::fmt;
20 use core::mem;
21 use core::ptr;
22 use core::ops;
23 // FIXME: ICE's abound if you import the `Slice` type while importing `Slice` trait
24 use core::raw::Slice as RawSlice;
25
26 use hash;
27 use slice::CloneSliceAllocPrelude;
28 use str;
29 use str::{CharRange, CowString, FromStr, StrAllocating, Owned};
30 use vec::{DerefVec, Vec, as_vec};
31
32 /// A growable string stored as a UTF-8 encoded buffer.
33 #[deriving(Clone, PartialOrd, Eq, Ord)]
34 #[stable]
35 pub struct String {
36     vec: Vec<u8>,
37 }
38
39 impl String {
40     /// Creates a new string buffer initialized with the empty string.
41     ///
42     /// # Example
43     ///
44     /// ```
45     /// let mut s = String::new();
46     /// ```
47     #[inline]
48     #[stable]
49     pub fn new() -> String {
50         String {
51             vec: Vec::new(),
52         }
53     }
54
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.
58     ///
59     /// # Example
60     ///
61     /// ```
62     /// let mut s = String::with_capacity(10);
63     /// ```
64     #[inline]
65     #[stable]
66     pub fn with_capacity(capacity: uint) -> String {
67         String {
68             vec: Vec::with_capacity(capacity),
69         }
70     }
71
72     /// Creates a new string buffer from the given string.
73     ///
74     /// # Example
75     ///
76     /// ```
77     /// let s = String::from_str("hello");
78     /// assert_eq!(s.as_slice(), "hello");
79     /// ```
80     #[inline]
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() }
84     }
85
86     /// Returns the vector as a string buffer, if possible, taking care not to
87     /// copy it.
88     ///
89     /// Returns `Err` with the original vector if the vector contains invalid
90     /// UTF-8.
91     ///
92     /// # Example
93     ///
94     /// ```rust
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()));
98     ///
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]));
102     /// ```
103     #[inline]
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 })
108         } else {
109             Err(vec)
110         }
111     }
112
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.
115     ///
116     /// # Example
117     ///
118     /// ```rust
119     /// let input = b"Hello \xF0\x90\x80World";
120     /// let output = String::from_utf8_lossy(input);
121     /// assert_eq!(output.as_slice(), "Hello \uFFFDWorld");
122     /// ```
123     #[unstable = "return type may change"]
124     pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> CowString<'a> {
125         if str::is_utf8(v) {
126             return Cow::Borrowed(unsafe { mem::transmute(v) })
127         }
128
129         static TAG_CONT_U8: u8 = 128u8;
130         static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
131         let mut i = 0;
132         let total = v.len();
133         fn unsafe_get(xs: &[u8], i: uint) -> u8 {
134             unsafe { *xs.unsafe_get(i) }
135         }
136         fn safe_get(xs: &[u8], i: uint, total: uint) -> u8 {
137             if i >= total {
138                 0
139             } else {
140                 unsafe_get(xs, i)
141             }
142         }
143
144         let mut res = String::with_capacity(total);
145
146         if i > 0 {
147             unsafe {
148                 res.as_mut_vec().push_all(v[..i])
149             };
150         }
151
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
154         // them one by one.
155         let mut subseqidx = 0;
156
157         while i < total {
158             let i_ = i;
159             let byte = unsafe_get(v, i);
160             i += 1;
161
162             macro_rules! error(() => ({
163                 unsafe {
164                     if subseqidx != i_ {
165                         res.as_mut_vec().push_all(v[subseqidx..i_]);
166                     }
167                     subseqidx = i;
168                     res.as_mut_vec().push_all(REPLACEMENT);
169                 }
170             }))
171
172             if byte < 128u8 {
173                 // subseqidx handles this
174             } else {
175                 let w = str::utf8_char_width(byte);
176
177                 match w {
178                     2 => {
179                         if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
180                             error!();
181                             continue;
182                         }
183                         i += 1;
184                     }
185                     3 => {
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) => (),
191                             _ => {
192                                 error!();
193                                 continue;
194                             }
195                         }
196                         i += 1;
197                         if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
198                             error!();
199                             continue;
200                         }
201                         i += 1;
202                     }
203                     4 => {
204                         match (byte, safe_get(v, i, total)) {
205                             (0xF0         , 0x90 ... 0xBF) => (),
206                             (0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
207                             (0xF4         , 0x80 ... 0x8F) => (),
208                             _ => {
209                                 error!();
210                                 continue;
211                             }
212                         }
213                         i += 1;
214                         if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
215                             error!();
216                             continue;
217                         }
218                         i += 1;
219                         if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
220                             error!();
221                             continue;
222                         }
223                         i += 1;
224                     }
225                     _ => {
226                         error!();
227                         continue;
228                     }
229                 }
230             }
231         }
232         if subseqidx < total {
233             unsafe {
234                 res.as_mut_vec().push_all(v[subseqidx..total])
235             };
236         }
237         Cow::Owned(res.into_string())
238     }
239
240     /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
241     /// if `v` contains any invalid data.
242     ///
243     /// # Example
244     ///
245     /// ```rust
246     /// // 𝄞music
247     /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
248     ///                   0x0073, 0x0069, 0x0063];
249     /// assert_eq!(String::from_utf16(v), Some("𝄞music".to_string()));
250     ///
251     /// // 𝄞mu<invalid>ic
252     /// v[4] = 0xD800;
253     /// assert_eq!(String::from_utf16(v), None);
254     /// ```
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) {
259             match c {
260                 str::ScalarValue(c) => s.push(c),
261                 str::LoneSurrogate(_) => return None
262             }
263         }
264         Some(s)
265     }
266
267     /// Decode a UTF-16 encoded vector `v` into a string, replacing
268     /// invalid data with the replacement character (U+FFFD).
269     ///
270     /// # Example
271     /// ```rust
272     /// // 𝄞mus<invalid>ic<invalid>
273     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
274     ///           0x0073, 0xDD1E, 0x0069, 0x0063,
275     ///           0xD834];
276     ///
277     /// assert_eq!(String::from_utf16_lossy(v),
278     ///            "𝄞mus\uFFFDic\uFFFD".to_string());
279     /// ```
280     #[stable]
281     pub fn from_utf16_lossy(v: &[u16]) -> String {
282         str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
283     }
284
285     /// Convert a vector of `char`s to a `String`.
286     ///
287     /// # Example
288     ///
289     /// ```rust
290     /// let chars = &['h', 'e', 'l', 'l', 'o'];
291     /// let s = String::from_chars(chars);
292     /// assert_eq!(s.as_slice(), "hello");
293     /// ```
294     #[inline]
295     #[unstable = "may be removed in favor of .collect()"]
296     pub fn from_chars(chs: &[char]) -> String {
297         chs.iter().map(|c| *c).collect()
298     }
299
300     /// Creates a new `String` from a length, capacity, and pointer.
301     ///
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.
305     #[inline]
306     #[unstable = "function just moved from string::raw"]
307     pub unsafe fn from_raw_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
308         String {
309             vec: Vec::from_raw_parts(buf, length, capacity),
310         }
311     }
312
313     /// Creates a `String` from a null-terminated `*const u8` buffer.
314     ///
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))
321     }
322
323     /// Creates a `String` from a `*const u8` buffer of the given length.
324     ///
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
328     /// `String`).
329     ///
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))
335     }
336
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.
340     #[inline]
341     #[unstable = "awaiting stabilization"]
342     pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
343         String { vec: bytes }
344     }
345
346     /// Return the underlying byte buffer, encoded as UTF-8.
347     ///
348     /// # Example
349     ///
350     /// ```
351     /// let s = String::from_str("hello");
352     /// let bytes = s.into_bytes();
353     /// assert_eq!(bytes, vec![104, 101, 108, 108, 111]);
354     /// ```
355     #[inline]
356     #[stable]
357     pub fn into_bytes(self) -> Vec<u8> {
358         self.vec
359     }
360
361     /// Creates a string buffer by repeating a character `length` times.
362     ///
363     /// # Example
364     ///
365     /// ```
366     /// let s = String::from_char(5, 'a');
367     /// assert_eq!(s.as_slice(), "aaaaa");
368     /// ```
369     #[inline]
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 {
373         if length == 0 {
374             return String::new()
375         }
376
377         let mut buf = String::new();
378         buf.push(ch);
379         let size = buf.len() * (length - 1);
380         buf.reserve_exact(size);
381         for _ in range(1, length) {
382             buf.push(ch)
383         }
384         buf
385     }
386
387     /// Pushes the given string onto this string buffer.
388     ///
389     /// # Example
390     ///
391     /// ```
392     /// let mut s = String::from_str("foo");
393     /// s.push_str("bar");
394     /// assert_eq!(s.as_slice(), "foobar");
395     /// ```
396     #[inline]
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())
400     }
401
402     /// Pushes `ch` onto the given string `count` times.
403     ///
404     /// # Example
405     ///
406     /// ```
407     /// let mut s = String::from_str("foo");
408     /// s.grow(5, 'Z');
409     /// assert_eq!(s.as_slice(), "fooZZZZZ");
410     /// ```
411     #[inline]
412     #[unstable = "duplicate of iterator-based functionality"]
413     pub fn grow(&mut self, count: uint, ch: char) {
414         for _ in range(0, count) {
415             self.push(ch)
416         }
417     }
418
419     /// Returns the number of bytes that this string buffer can hold without reallocating.
420     ///
421     /// # Example
422     ///
423     /// ```
424     /// let s = String::with_capacity(10);
425     /// assert!(s.capacity() >= 10);
426     /// ```
427     #[inline]
428     #[unstable = "matches collection reform specification, waiting for dust to settle"]
429     pub fn capacity(&self) -> uint {
430         self.vec.capacity()
431     }
432
433     /// Deprecated: Renamed to `reserve`.
434     #[deprecated = "Renamed to `reserve`"]
435     pub fn reserve_additional(&mut self, extra: uint) {
436         self.vec.reserve(extra)
437     }
438
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.
441     ///
442     /// # Panics
443     ///
444     /// Panics if the new capacity overflows `uint`.
445     ///
446     /// # Example
447     ///
448     /// ```
449     /// let mut s = String::new();
450     /// s.reserve(10);
451     /// assert!(s.capacity() >= 10);
452     /// ```
453     #[inline]
454     #[unstable = "matches collection reform specification, waiting for dust to settle"]
455     pub fn reserve(&mut self, additional: uint) {
456         self.vec.reserve(additional)
457     }
458
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.
461     ///
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.
465     ///
466     /// # Panics
467     ///
468     /// Panics if the new capacity overflows `uint`.
469     ///
470     /// # Example
471     ///
472     /// ```
473     /// let mut s = String::new();
474     /// s.reserve(10);
475     /// assert!(s.capacity() >= 10);
476     /// ```
477     #[inline]
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)
481     }
482
483     /// Shrinks the capacity of this string buffer to match its length.
484     ///
485     /// # Example
486     ///
487     /// ```
488     /// let mut s = String::from_str("foo");
489     /// s.reserve(100);
490     /// assert!(s.capacity() >= 100);
491     /// s.shrink_to_fit();
492     /// assert_eq!(s.capacity(), 3);
493     /// ```
494     #[inline]
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()
498     }
499
500     /// Adds the given character to the end of the string.
501     ///
502     /// # Example
503     ///
504     /// ```
505     /// let mut s = String::from_str("abc");
506     /// s.push('1');
507     /// s.push('2');
508     /// s.push('3');
509     /// assert_eq!(s.as_slice(), "abc123");
510     /// ```
511     #[inline]
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.
516         self.vec.reserve(4);
517
518         unsafe {
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),
523                 len: 4,
524             };
525             let used = ch.encode_utf8(mem::transmute(slice)).unwrap_or(0);
526             self.vec.set_len(cur_len + used);
527         }
528     }
529
530     /// Works with the underlying buffer as a byte slice.
531     ///
532     /// # Example
533     ///
534     /// ```
535     /// let s = String::from_str("hello");
536     /// let b: &[_] = &[104, 101, 108, 108, 111];
537     /// assert_eq!(s.as_bytes(), b);
538     /// ```
539     #[inline]
540     #[stable]
541     pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
542         self.vec.as_slice()
543     }
544
545     /// Shortens a string to the specified length.
546     ///
547     /// # Panics
548     ///
549     /// Panics if `new_len` > current length,
550     /// or if `new_len` is not a character boundary.
551     ///
552     /// # Example
553     ///
554     /// ```
555     /// let mut s = String::from_str("hello");
556     /// s.truncate(2);
557     /// assert_eq!(s.as_slice(), "he");
558     /// ```
559     #[inline]
560     #[unstable = "the panic conventions for strings are under development"]
561     pub fn truncate(&mut self, new_len: uint) {
562         assert!(self.as_slice().is_char_boundary(new_len));
563         self.vec.truncate(new_len)
564     }
565
566     /// Removes the last character from the string buffer and returns it.
567     /// Returns `None` if this string buffer is empty.
568     ///
569     /// # Example
570     ///
571     /// ```
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);
577     /// ```
578     #[inline]
579     #[unstable = "this function was just renamed from pop_char"]
580     pub fn pop(&mut self) -> Option<char> {
581         let len = self.len();
582         if len == 0 {
583             return None
584         }
585
586         let CharRange {ch, next} = self.as_slice().char_range_at_reverse(len);
587         unsafe {
588             self.vec.set_len(next);
589         }
590         Some(ch)
591     }
592
593     /// Removes the character from the string buffer at byte position `idx` and
594     /// returns it. Returns `None` if `idx` is out of bounds.
595     ///
596     /// # Warning
597     ///
598     /// This is an O(n) operation as it requires copying every element in the
599     /// buffer.
600     ///
601     /// # Panics
602     ///
603     /// If `idx` does not lie on a character boundary, then this function will
604     /// panic.
605     ///
606     /// # Example
607     ///
608     /// ```
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);
614     /// ```
615     #[unstable = "the panic semantics of this function and return type \
616                   may change"]
617     pub fn remove(&mut self, idx: uint) -> Option<char> {
618         let len = self.len();
619         if idx >= len { return None }
620
621         let CharRange { ch, next } = self.as_slice().char_range_at(idx);
622         unsafe {
623             ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
624                              self.vec.as_ptr().offset(next as int),
625                              len - next);
626             self.vec.set_len(len - (next - idx));
627         }
628         Some(ch)
629     }
630
631     /// Insert a character into the string buffer at byte position `idx`.
632     ///
633     /// # Warning
634     ///
635     /// This is an O(n) operation as it requires copying every element in the
636     /// buffer.
637     ///
638     /// # Panics
639     ///
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();
645         assert!(idx <= len);
646         assert!(self.as_slice().is_char_boundary(idx));
647         self.vec.reserve(4);
648         let mut bits = [0, ..4];
649         let amt = ch.encode_utf8(&mut bits).unwrap();
650
651         unsafe {
652             ptr::copy_memory(self.vec.as_mut_ptr().offset((idx + amt) as int),
653                              self.vec.as_ptr().offset(idx as int),
654                              len - idx);
655             ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
656                              bits.as_ptr(),
657                              amt);
658             self.vec.set_len(len + amt);
659         }
660     }
661
662     /// Views the string buffer as a mutable sequence of bytes.
663     ///
664     /// This is unsafe because it does not check
665     /// to ensure that the resulting string will be valid UTF-8.
666     ///
667     /// # Example
668     ///
669     /// ```
670     /// let mut s = String::from_str("hello");
671     /// unsafe {
672     ///     let vec = s.as_mut_vec();
673     ///     assert!(vec == &mut vec![104, 101, 108, 108, 111]);
674     ///     vec.reverse();
675     /// }
676     /// assert_eq!(s.as_slice(), "olleh");
677     /// ```
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> {
680         &mut self.vec
681     }
682
683     /// Return the number of bytes in this string.
684     ///
685     /// # Example
686     ///
687     /// ```
688     /// let a = "foo".to_string();
689     /// assert_eq!(a.len(), 3);
690     /// ```
691     #[inline]
692     #[stable]
693     pub fn len(&self) -> uint { self.vec.len() }
694
695     /// Returns true if the string contains no bytes
696     ///
697     /// # Example
698     ///
699     /// ```
700     /// let mut v = String::new();
701     /// assert!(v.is_empty());
702     /// v.push('a');
703     /// assert!(!v.is_empty());
704     /// ```
705     pub fn is_empty(&self) -> bool { self.len() == 0 }
706
707     /// Truncates the string, returning it to 0 length.
708     ///
709     /// # Example
710     ///
711     /// ```
712     /// let mut s = "foo".to_string();
713     /// s.clear();
714     /// assert!(s.is_empty());
715     /// ```
716     #[inline]
717     #[stable]
718     pub fn clear(&mut self) {
719         self.vec.clear()
720     }
721 }
722
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);
728         buf
729     }
730 }
731
732 #[experimental = "waiting on FromIterator stabilization"]
733 impl<'a> FromIterator<&'a str> for String {
734     fn from_iter<I:Iterator<&'a str>>(iterator: I) -> String {
735         let mut buf = String::new();
736         buf.extend(iterator);
737         buf
738     }
739 }
740
741 #[experimental = "waiting on Extend stabilization"]
742 impl Extend<char> for String {
743     fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
744         let (lower_bound, _) = iterator.size_hint();
745         self.reserve(lower_bound);
746         for ch in iterator {
747             self.push(ch)
748         }
749     }
750 }
751
752 #[experimental = "waiting on Extend stabilization"]
753 impl<'a> Extend<&'a str> for String {
754     fn extend<I: Iterator<&'a str>>(&mut self, mut iterator: I) {
755         // A guess that at least one byte per iterator element will be needed.
756         let (lower_bound, _) = iterator.size_hint();
757         self.reserve(lower_bound);
758         for s in iterator {
759             self.push_str(s)
760         }
761     }
762 }
763
764 impl PartialEq for String {
765     #[inline]
766     fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
767     #[inline]
768     fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) }
769 }
770
771 macro_rules! impl_eq {
772     ($lhs:ty, $rhs: ty) => {
773         impl<'a> PartialEq<$rhs> for $lhs {
774             #[inline]
775             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
776             #[inline]
777             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
778         }
779
780         impl<'a> PartialEq<$lhs> for $rhs {
781             #[inline]
782             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
783             #[inline]
784             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
785         }
786
787     }
788 }
789
790 impl_eq!(String, &'a str)
791 impl_eq!(CowString<'a>, String)
792
793 impl<'a, 'b> PartialEq<&'b str> for CowString<'a> {
794     #[inline]
795     fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) }
796     #[inline]
797     fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) }
798 }
799
800 impl<'a, 'b> PartialEq<CowString<'a>> for &'b str {
801     #[inline]
802     fn eq(&self, other: &CowString<'a>) -> bool { PartialEq::eq(&**self, &**other) }
803     #[inline]
804     fn ne(&self, other: &CowString<'a>) -> bool { PartialEq::ne(&**self, &**other) }
805 }
806
807 #[experimental = "waiting on Str stabilization"]
808 impl Str for String {
809     #[inline]
810     #[stable]
811     fn as_slice<'a>(&'a self) -> &'a str {
812         unsafe {
813             mem::transmute(self.vec.as_slice())
814         }
815     }
816 }
817
818 #[experimental = "waiting on StrAllocating stabilization"]
819 impl StrAllocating for String {
820     #[inline]
821     fn into_string(self) -> String {
822         self
823     }
824 }
825
826 #[stable]
827 impl Default for String {
828     fn default() -> String {
829         String::new()
830     }
831 }
832
833 #[experimental = "waiting on Show stabilization"]
834 impl fmt::Show for String {
835     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
836         self.as_slice().fmt(f)
837     }
838 }
839
840 #[experimental = "waiting on Hash stabilization"]
841 impl<H: hash::Writer> hash::Hash<H> for String {
842     #[inline]
843     fn hash(&self, hasher: &mut H) {
844         self.as_slice().hash(hasher)
845     }
846 }
847
848 #[allow(deprecated)]
849 #[deprecated = "Use overloaded `core::cmp::PartialEq`"]
850 impl<'a, S: Str> Equiv<S> for String {
851     #[inline]
852     fn equiv(&self, other: &S) -> bool {
853         self.as_slice() == other.as_slice()
854     }
855 }
856
857 #[experimental = "waiting on Add stabilization"]
858 impl<S: Str> Add<S, String> for String {
859     fn add(&self, other: &S) -> String {
860         let mut s = String::from_str(self.as_slice());
861         s.push_str(other.as_slice());
862         return s;
863     }
864 }
865
866 impl ops::Slice<uint, str> for String {
867     #[inline]
868     fn as_slice_<'a>(&'a self) -> &'a str {
869         self.as_slice()
870     }
871
872     #[inline]
873     fn slice_from_or_fail<'a>(&'a self, from: &uint) -> &'a str {
874         self[][*from..]
875     }
876
877     #[inline]
878     fn slice_to_or_fail<'a>(&'a self, to: &uint) -> &'a str {
879         self[][..*to]
880     }
881
882     #[inline]
883     fn slice_or_fail<'a>(&'a self, from: &uint, to: &uint) -> &'a str {
884         self[][*from..*to]
885     }
886 }
887
888 #[experimental = "waiting on Deref stabilization"]
889 impl ops::Deref<str> for String {
890     fn deref<'a>(&'a self) -> &'a str { self.as_slice() }
891 }
892
893 /// Wrapper type providing a `&String` reference via `Deref`.
894 #[experimental]
895 pub struct DerefString<'a> {
896     x: DerefVec<'a, u8>
897 }
898
899 impl<'a> Deref<String> for DerefString<'a> {
900     fn deref<'b>(&'b self) -> &'b String {
901         unsafe { mem::transmute(&*self.x) }
902     }
903 }
904
905 /// Convert a string slice to a wrapper type providing a `&String` reference.
906 #[experimental]
907 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
908     DerefString { x: as_vec(x.as_bytes()) }
909 }
910
911 impl FromStr for String {
912     #[inline]
913     fn from_str(s: &str) -> Option<String> {
914         Some(String::from_str(s))
915     }
916 }
917
918 /// Trait for converting a type to a string, consuming it in the process.
919 pub trait IntoString {
920     /// Consume and convert to a string.
921     fn into_string(self) -> String;
922 }
923
924 /// A generic trait for converting a value to a string
925 pub trait ToString {
926     /// Converts the value of `self` to an owned string
927     fn to_string(&self) -> String;
928 }
929
930 impl<T: fmt::Show> ToString for T {
931     fn to_string(&self) -> String {
932         let mut buf = Vec::<u8>::new();
933         let _ = format_args!(|args| fmt::write(&mut buf, args), "{}", self);
934         String::from_utf8(buf).unwrap()
935     }
936 }
937
938 impl IntoCow<'static, String, str> for String {
939     fn into_cow(self) -> CowString<'static> {
940         Cow::Owned(self)
941     }
942 }
943
944 impl<'a> IntoCow<'a, String, str> for &'a str {
945     fn into_cow(self) -> CowString<'a> {
946         Cow::Borrowed(self)
947     }
948 }
949
950 /// Unsafe operations
951 #[deprecated]
952 pub mod raw {
953     use super::String;
954     use vec::Vec;
955
956     /// Creates a new `String` from a length, capacity, and pointer.
957     ///
958     /// This is unsafe because:
959     /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
960     /// * We assume that the `Vec` contains valid UTF-8.
961     #[inline]
962     #[deprecated = "renamed to String::from_raw_parts"]
963     pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
964         String::from_raw_parts(buf, length, capacity)
965     }
966
967     /// Creates a `String` from a `*const u8` buffer of the given length.
968     ///
969     /// This function is unsafe because of two reasons:
970     ///
971     /// * A raw pointer is dereferenced and transmuted to `&[u8]`;
972     /// * The slice is not checked to see whether it contains valid UTF-8.
973     #[deprecated = "renamed to String::from_raw_buf_len"]
974     pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
975         String::from_raw_buf_len(buf, len)
976     }
977
978     /// Creates a `String` from a null-terminated `*const u8` buffer.
979     ///
980     /// This function is unsafe because we dereference memory until we find the NUL character,
981     /// which is not guaranteed to be present. Additionally, the slice is not checked to see
982     /// whether it contains valid UTF-8
983     #[deprecated = "renamed to String::from_raw_buf"]
984     pub unsafe fn from_buf(buf: *const u8) -> String {
985         String::from_raw_buf(buf)
986     }
987
988     /// Converts a vector of bytes to a new `String` without checking if
989     /// it contains valid UTF-8. This is unsafe because it assumes that
990     /// the UTF-8-ness of the vector has already been validated.
991     #[inline]
992     #[deprecated = "renamed to String::from_utf8_unchecked"]
993     pub unsafe fn from_utf8(bytes: Vec<u8>) -> String {
994         String::from_utf8_unchecked(bytes)
995     }
996 }
997
998 #[cfg(test)]
999 mod tests {
1000     use std::prelude::*;
1001     use test::Bencher;
1002
1003     use slice::CloneSliceAllocPrelude;
1004     use str::{Str, StrPrelude};
1005     use str;
1006     use super::{as_string, String, ToString};
1007     use vec::Vec;
1008
1009     #[test]
1010     fn test_as_string() {
1011         let x = "foo";
1012         assert_eq!(x, as_string(x).as_slice());
1013     }
1014
1015     #[test]
1016     fn test_from_str() {
1017       let owned: Option<::std::string::String> = from_str("string");
1018       assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
1019     }
1020
1021     #[test]
1022     fn test_from_utf8() {
1023         let xs = b"hello".to_vec();
1024         assert_eq!(String::from_utf8(xs), Ok(String::from_str("hello")));
1025
1026         let xs = "ศไทย中华Việt Nam".as_bytes().to_vec();
1027         assert_eq!(String::from_utf8(xs), Ok(String::from_str("ศไทย中华Việt Nam")));
1028
1029         let xs = b"hello\xFF".to_vec();
1030         assert_eq!(String::from_utf8(xs),
1031                    Err(b"hello\xFF".to_vec()));
1032     }
1033
1034     #[test]
1035     fn test_from_utf8_lossy() {
1036         let xs = b"hello";
1037         let ys: str::CowString = "hello".into_cow();
1038         assert_eq!(String::from_utf8_lossy(xs), ys);
1039
1040         let xs = "ศไทย中华Việt Nam".as_bytes();
1041         let ys: str::CowString = "ศไทย中华Việt Nam".into_cow();
1042         assert_eq!(String::from_utf8_lossy(xs), ys);
1043
1044         let xs = b"Hello\xC2 There\xFF Goodbye";
1045         assert_eq!(String::from_utf8_lossy(xs),
1046                    String::from_str("Hello\uFFFD There\uFFFD Goodbye").into_cow());
1047
1048         let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1049         assert_eq!(String::from_utf8_lossy(xs),
1050                    String::from_str("Hello\uFFFD\uFFFD There\uFFFD Goodbye").into_cow());
1051
1052         let xs = b"\xF5foo\xF5\x80bar";
1053         assert_eq!(String::from_utf8_lossy(xs),
1054                    String::from_str("\uFFFDfoo\uFFFD\uFFFDbar").into_cow());
1055
1056         let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
1057         assert_eq!(String::from_utf8_lossy(xs),
1058                    String::from_str("\uFFFDfoo\uFFFDbar\uFFFDbaz").into_cow());
1059
1060         let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
1061         assert_eq!(String::from_utf8_lossy(xs),
1062                    String::from_str("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz").into_cow());
1063
1064         let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
1065         assert_eq!(String::from_utf8_lossy(xs), String::from_str("\uFFFD\uFFFD\uFFFD\uFFFD\
1066                                                foo\U00010000bar").into_cow());
1067
1068         // surrogates
1069         let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
1070         assert_eq!(String::from_utf8_lossy(xs), String::from_str("\uFFFD\uFFFD\uFFFDfoo\
1071                                                \uFFFD\uFFFD\uFFFDbar").into_cow());
1072     }
1073
1074     #[test]
1075     fn test_from_utf16() {
1076         let pairs =
1077             [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"),
1078               vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
1079                 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
1080                 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
1081                 0xd800_u16, 0xdf30_u16, 0x000a_u16]),
1082
1083              (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"),
1084               vec![0xd801_u16, 0xdc12_u16, 0xd801_u16,
1085                 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
1086                 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
1087                 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16,
1088                 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16,
1089                 0x000a_u16]),
1090
1091              (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"),
1092               vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
1093                 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
1094                 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
1095                 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16,
1096                 0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16,
1097                 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16,
1098                 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),
1099
1100              (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"),
1101               vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
1102                 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
1103                 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
1104                 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16,
1105                 0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16,
1106                 0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16,
1107                 0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16,
1108                 0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16,
1109                 0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16,
1110                 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16,
1111                 0x000a_u16 ]),
1112              // Issue #12318, even-numbered non-BMP planes
1113              (String::from_str("\U00020000"),
1114               vec![0xD840, 0xDC00])];
1115
1116         for p in pairs.iter() {
1117             let (s, u) = (*p).clone();
1118             let s_as_utf16 = s.as_slice().utf16_units().collect::<Vec<u16>>();
1119             let u_as_string = String::from_utf16(u.as_slice()).unwrap();
1120
1121             assert!(str::is_utf16(u.as_slice()));
1122             assert_eq!(s_as_utf16, u);
1123
1124             assert_eq!(u_as_string, s);
1125             assert_eq!(String::from_utf16_lossy(u.as_slice()), s);
1126
1127             assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
1128             assert_eq!(u_as_string.as_slice().utf16_units().collect::<Vec<u16>>(), u);
1129         }
1130     }
1131
1132     #[test]
1133     fn test_utf16_invalid() {
1134         // completely positive cases tested above.
1135         // lead + eof
1136         assert_eq!(String::from_utf16(&[0xD800]), None);
1137         // lead + lead
1138         assert_eq!(String::from_utf16(&[0xD800, 0xD800]), None);
1139
1140         // isolated trail
1141         assert_eq!(String::from_utf16(&[0x0061, 0xDC00]), None);
1142
1143         // general
1144         assert_eq!(String::from_utf16(&[0xD800, 0xd801, 0xdc8b, 0xD800]), None);
1145     }
1146
1147     #[test]
1148     fn test_from_utf16_lossy() {
1149         // completely positive cases tested above.
1150         // lead + eof
1151         assert_eq!(String::from_utf16_lossy(&[0xD800]), String::from_str("\uFFFD"));
1152         // lead + lead
1153         assert_eq!(String::from_utf16_lossy(&[0xD800, 0xD800]), String::from_str("\uFFFD\uFFFD"));
1154
1155         // isolated trail
1156         assert_eq!(String::from_utf16_lossy(&[0x0061, 0xDC00]), String::from_str("a\uFFFD"));
1157
1158         // general
1159         assert_eq!(String::from_utf16_lossy(&[0xD800, 0xd801, 0xdc8b, 0xD800]),
1160                    String::from_str("\uFFFD𐒋\uFFFD"));
1161     }
1162
1163     #[test]
1164     fn test_from_buf_len() {
1165         unsafe {
1166             let a = vec![65u8, 65, 65, 65, 65, 65, 65, 0];
1167             assert_eq!(super::raw::from_buf_len(a.as_ptr(), 3), String::from_str("AAA"));
1168         }
1169     }
1170
1171     #[test]
1172     fn test_from_buf() {
1173         unsafe {
1174             let a = vec![65, 65, 65, 65, 65, 65, 65, 0];
1175             let b = a.as_ptr();
1176             let c = super::raw::from_buf(b);
1177             assert_eq!(c, String::from_str("AAAAAAA"));
1178         }
1179     }
1180
1181     #[test]
1182     fn test_push_bytes() {
1183         let mut s = String::from_str("ABC");
1184         unsafe {
1185             let mv = s.as_mut_vec();
1186             mv.push_all(&[b'D']);
1187         }
1188         assert_eq!(s.as_slice(), "ABCD");
1189     }
1190
1191     #[test]
1192     fn test_push_str() {
1193         let mut s = String::new();
1194         s.push_str("");
1195         assert_eq!(s.as_slice().slice_from(0), "");
1196         s.push_str("abc");
1197         assert_eq!(s.as_slice().slice_from(0), "abc");
1198         s.push_str("ประเทศไทย中华Việt Nam");
1199         assert_eq!(s.as_slice().slice_from(0), "abcประเทศไทย中华Việt Nam");
1200     }
1201
1202     #[test]
1203     fn test_push() {
1204         let mut data = String::from_str("ประเทศไทย中");
1205         data.push('华');
1206         data.push('b'); // 1 byte
1207         data.push('¢'); // 2 byte
1208         data.push('€'); // 3 byte
1209         data.push('𤭢'); // 4 byte
1210         assert_eq!(data.as_slice(), "ประเทศไทย中华b¢€𤭢");
1211     }
1212
1213     #[test]
1214     fn test_pop() {
1215         let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
1216         assert_eq!(data.pop().unwrap(), '𤭢'); // 4 bytes
1217         assert_eq!(data.pop().unwrap(), '€'); // 3 bytes
1218         assert_eq!(data.pop().unwrap(), '¢'); // 2 bytes
1219         assert_eq!(data.pop().unwrap(), 'b'); // 1 bytes
1220         assert_eq!(data.pop().unwrap(), '华');
1221         assert_eq!(data.as_slice(), "ประเทศไทย中");
1222     }
1223
1224     #[test]
1225     fn test_str_truncate() {
1226         let mut s = String::from_str("12345");
1227         s.truncate(5);
1228         assert_eq!(s.as_slice(), "12345");
1229         s.truncate(3);
1230         assert_eq!(s.as_slice(), "123");
1231         s.truncate(0);
1232         assert_eq!(s.as_slice(), "");
1233
1234         let mut s = String::from_str("12345");
1235         let p = s.as_slice().as_ptr();
1236         s.truncate(3);
1237         s.push_str("6");
1238         let p_ = s.as_slice().as_ptr();
1239         assert_eq!(p_, p);
1240     }
1241
1242     #[test]
1243     #[should_fail]
1244     fn test_str_truncate_invalid_len() {
1245         let mut s = String::from_str("12345");
1246         s.truncate(6);
1247     }
1248
1249     #[test]
1250     #[should_fail]
1251     fn test_str_truncate_split_codepoint() {
1252         let mut s = String::from_str("\u00FC"); // ü
1253         s.truncate(1);
1254     }
1255
1256     #[test]
1257     fn test_str_clear() {
1258         let mut s = String::from_str("12345");
1259         s.clear();
1260         assert_eq!(s.len(), 0);
1261         assert_eq!(s.as_slice(), "");
1262     }
1263
1264     #[test]
1265     fn test_str_add() {
1266         let a = String::from_str("12345");
1267         let b = a + "2";
1268         let b = b + String::from_str("2");
1269         assert_eq!(b.len(), 7);
1270         assert_eq!(b.as_slice(), "1234522");
1271     }
1272
1273     #[test]
1274     fn remove() {
1275         let mut s = "ศไทย中华Việt Nam; foobar".to_string();;
1276         assert_eq!(s.remove(0), Some('ศ'));
1277         assert_eq!(s.len(), 33);
1278         assert_eq!(s.as_slice(), "ไทย中华Việt Nam; foobar");
1279         assert_eq!(s.remove(33), None);
1280         assert_eq!(s.remove(300), None);
1281         assert_eq!(s.remove(17), Some('ệ'));
1282         assert_eq!(s.as_slice(), "ไทย中华Vit Nam; foobar");
1283     }
1284
1285     #[test] #[should_fail]
1286     fn remove_bad() {
1287         "ศ".to_string().remove(1);
1288     }
1289
1290     #[test]
1291     fn insert() {
1292         let mut s = "foobar".to_string();
1293         s.insert(0, 'ệ');
1294         assert_eq!(s.as_slice(), "ệfoobar");
1295         s.insert(6, 'ย');
1296         assert_eq!(s.as_slice(), "ệfooยbar");
1297     }
1298
1299     #[test] #[should_fail] fn insert_bad1() { "".to_string().insert(1, 't'); }
1300     #[test] #[should_fail] fn insert_bad2() { "ệ".to_string().insert(1, 't'); }
1301
1302     #[test]
1303     fn test_slicing() {
1304         let s = "foobar".to_string();
1305         assert_eq!("foobar", s[]);
1306         assert_eq!("foo", s[..3]);
1307         assert_eq!("bar", s[3..]);
1308         assert_eq!("oob", s[1..4]);
1309     }
1310
1311     #[test]
1312     fn test_simple_types() {
1313         assert_eq!(1i.to_string(), "1".to_string());
1314         assert_eq!((-1i).to_string(), "-1".to_string());
1315         assert_eq!(200u.to_string(), "200".to_string());
1316         assert_eq!(2u8.to_string(), "2".to_string());
1317         assert_eq!(true.to_string(), "true".to_string());
1318         assert_eq!(false.to_string(), "false".to_string());
1319         assert_eq!(().to_string(), "()".to_string());
1320         assert_eq!(("hi".to_string()).to_string(), "hi".to_string());
1321     }
1322
1323     #[test]
1324     fn test_vectors() {
1325         let x: Vec<int> = vec![];
1326         assert_eq!(x.to_string(), "[]".to_string());
1327         assert_eq!((vec![1i]).to_string(), "[1]".to_string());
1328         assert_eq!((vec![1i, 2, 3]).to_string(), "[1, 2, 3]".to_string());
1329         assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_string() ==
1330                "[[], [1], [1, 1]]".to_string());
1331     }
1332
1333     #[test]
1334     fn test_from_iterator() {
1335         let s = "ศไทย中华Việt Nam".to_string();
1336         let t = "ศไทย中华";
1337         let u = "Việt Nam";
1338
1339         let a: String = s.chars().collect();
1340         assert_eq!(s, a);
1341
1342         let mut b = t.to_string();
1343         b.extend(u.chars());
1344         assert_eq!(s, b);
1345
1346         let c: String = vec![t, u].into_iter().collect();
1347         assert_eq!(s, c);
1348
1349         let mut d = t.to_string();
1350         d.extend(vec![u].into_iter());
1351         assert_eq!(s, d);
1352     }
1353
1354     #[bench]
1355     fn bench_with_capacity(b: &mut Bencher) {
1356         b.iter(|| {
1357             String::with_capacity(100)
1358         });
1359     }
1360
1361     #[bench]
1362     fn bench_push_str(b: &mut Bencher) {
1363         let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
1364         b.iter(|| {
1365             let mut r = String::new();
1366             r.push_str(s);
1367         });
1368     }
1369
1370     #[bench]
1371     fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
1372         let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
1373                   Lorem ipsum dolor sit amet, consectetur. ";
1374
1375         assert_eq!(100, s.len());
1376         b.iter(|| {
1377             let _ = String::from_utf8_lossy(s);
1378         });
1379     }
1380
1381     #[bench]
1382     fn from_utf8_lossy_100_multibyte(b: &mut Bencher) {
1383         let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
1384         assert_eq!(100, s.len());
1385         b.iter(|| {
1386             let _ = String::from_utf8_lossy(s);
1387         });
1388     }
1389
1390     #[bench]
1391     fn from_utf8_lossy_invalid(b: &mut Bencher) {
1392         let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1393         b.iter(|| {
1394             let _ = String::from_utf8_lossy(s);
1395         });
1396     }
1397
1398     #[bench]
1399     fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
1400         let s = Vec::from_elem(100, 0xF5u8);
1401         b.iter(|| {
1402             let _ = String::from_utf8_lossy(s.as_slice());
1403         });
1404     }
1405 }