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