]> git.lizzy.rs Git - rust.git/blob - src/libcollections/string.rs
02190d11b421fe8ef50443c3f56fe985cc6aaaef
[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 //! A UTF-8 encoded, growable string.
12 //!
13 //! This module contains the [`String`] type, a trait for converting
14 //! [`ToString`]s, and several error types that may result from working with
15 //! [`String`]s.
16 //!
17 //! [`String`]: struct.String.html
18 //! [`ToString`]: trait.ToString.html
19 //!
20 //! # Examples
21 //!
22 //! There are multiple ways to create a new `String` from a string literal:
23 //!
24 //! ```rust
25 //! let s = "Hello".to_string();
26 //!
27 //! let s = String::from("world");
28 //! let s: String = "also this".into();
29 //! ```
30 //!
31 //! You can create a new `String` from an existing one by concatenating with
32 //! `+`:
33 //!
34 //! ```rust
35 //! let s = "Hello".to_string();
36 //!
37 //! let message = s + " world!";
38 //! ```
39 //!
40 //! If you have a vector of valid UTF-8 bytes, you can make a `String` out of
41 //! it. You can do the reverse too.
42 //!
43 //! ```rust
44 //! let sparkle_heart = vec![240, 159, 146, 150];
45 //!
46 //! // We know these bytes are valid, so we'll use `unwrap()`.
47 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
48 //!
49 //! assert_eq!("💖", sparkle_heart);
50 //!
51 //! let bytes = sparkle_heart.into_bytes();
52 //!
53 //! assert_eq!(bytes, [240, 159, 146, 150]);
54 //! ```
55
56 #![stable(feature = "rust1", since = "1.0.0")]
57
58 use core::fmt;
59 use core::hash;
60 use core::iter::FromIterator;
61 use core::mem;
62 use core::ops::{self, Add, Index, IndexMut};
63 use core::ptr;
64 use core::slice;
65 use core::str::pattern::Pattern;
66 use rustc_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
67 use rustc_unicode::str as unicode_str;
68
69 #[allow(deprecated)]
70 use borrow::{Cow, IntoCow};
71 use range::RangeArgument;
72 use str::{self, FromStr, Utf8Error, Chars};
73 use vec::Vec;
74 use boxed::Box;
75
76 /// A UTF-8 encoded, growable string.
77 ///
78 /// The `String` type is the most common string type that has ownership over the
79 /// contents of the string. It has a close relationship with its borrowed
80 /// counterpart, the primitive [`str`].
81 ///
82 /// [`str`]: ../../std/primitive.str.html
83 ///
84 /// # Examples
85 ///
86 /// You can create a `String` from a literal string with `String::from`:
87 ///
88 /// ```
89 /// let hello = String::from("Hello, world!");
90 /// ```
91 ///
92 /// You can append a [`char`] to a `String` with the [`push()`] method, and
93 /// append a [`&str`] with the [`push_str()`] method:
94 ///
95 /// ```
96 /// let mut hello = String::from("Hello, ");
97 ///
98 /// hello.push('w');
99 /// hello.push_str("orld!");
100 /// ```
101 ///
102 /// [`char`]: ../../std/primitive.char.html
103 /// [`push()`]: #method.push
104 /// [`push_str()`]: #method.push_str
105 ///
106 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
107 /// the [`from_utf8()`] method:
108 ///
109 /// ```
110 /// // some bytes, in a vector
111 /// let sparkle_heart = vec![240, 159, 146, 150];
112 ///
113 /// // We know these bytes are valid, so we'll use `unwrap()`.
114 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
115 ///
116 /// assert_eq!("💖", sparkle_heart);
117 /// ```
118 ///
119 /// [`from_utf8()`]: #method.from_utf8
120 ///
121 /// # UTF-8
122 ///
123 /// `String`s are always valid UTF-8. This has a few implications, the first of
124 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
125 /// similar, but without the UTF-8 constraint. The second implication is that
126 /// you cannot index into a `String`:
127 ///
128 /// ```ignore
129 /// let s = "hello";
130 ///
131 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
132 /// ```
133 ///
134 /// [`OsString`]: ../../std/ffi/struct.OsString.html
135 ///
136 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
137 /// does not allow us to do this. Furtheremore, it's not clear what sort of
138 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
139 /// The [`as_bytes()`] and [`chars()`] methods return iterators over the first
140 /// two, respectively.
141 ///
142 /// [`as_bytes()`]: #method.as_bytes
143 /// [`chars()`]: #method.chars
144 ///
145 /// # Deref
146 ///
147 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
148 /// methods. In addition, this means that you can pass a `String` to any
149 /// function which takes a [`&str`] by using an ampersand (`&`):
150 ///
151 /// ```
152 /// fn takes_str(s: &str) { }
153 ///
154 /// let s = String::from("Hello");
155 ///
156 /// takes_str(&s);
157 /// ```
158 ///
159 /// [`&str`]: ../../std/primitive.str.html
160 /// [`Deref`]: ../../std/ops/trait.Deref.html
161 ///
162 /// This will create a [`&str`] from the `String` and pass it in. This
163 /// conversion is very inexpensive, and so generally, functions will accept
164 /// [`&str`]s as arguments unless they need a `String` for some specific reason.
165 ///
166 ///
167 /// # Representation
168 ///
169 /// A `String` is made up of three components: a pointer to some bytes, a
170 /// length, and a capacity. The pointer points to an internal buffer `String`
171 /// uses to store its data. The length is the number of bytes currently stored
172 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
173 /// the length will always be less than or equal to the capacity.
174 ///
175 /// This buffer is always stored on the heap.
176 ///
177 /// You can look at these with the [`as_ptr()`], [`len()`], and [`capacity()`]
178 /// methods:
179 ///
180 /// ```
181 /// use std::mem;
182 ///
183 /// let story = String::from("Once upon a time...");
184 ///
185 /// let ptr = story.as_ptr();
186 /// let len = story.len();
187 /// let capacity = story.capacity();
188 ///
189 /// // story has thirteen bytes
190 /// assert_eq!(19, len);
191 ///
192 /// // Now that we have our parts, we throw the story away.
193 /// mem::forget(story);
194 ///
195 /// // We can re-build a String out of ptr, len, and capacity. This is all
196 /// // unsafe because we are responsible for making sure the components are
197 /// // valid:
198 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
199 ///
200 /// assert_eq!(String::from("Once upon a time..."), s);
201 /// ```
202 ///
203 /// [`as_ptr()`]: #method.as_ptr
204 /// [`len()`]: #method.len
205 /// [`capacity()`]: #method.capacity
206 ///
207 /// If a `String` has enough capacity, adding elements to it will not
208 /// re-allocate. For example, consider this program:
209 ///
210 /// ```
211 /// let mut s = String::new();
212 ///
213 /// println!("{}", s.capacity());
214 ///
215 /// for _ in 0..5 {
216 ///     s.push_str("hello");
217 ///     println!("{}", s.capacity());
218 /// }
219 /// ```
220 ///
221 /// This will output the following:
222 ///
223 /// ```text
224 /// 0
225 /// 5
226 /// 10
227 /// 20
228 /// 20
229 /// 40
230 /// ```
231 ///
232 /// At first, we have no memory allocated at all, but as we append to the
233 /// string, it increases its capacity appropriately. If we instead use the
234 /// [`with_capacity()`] method to allocate the correct capacity initially:
235 ///
236 /// ```
237 /// let mut s = String::with_capacity(25);
238 ///
239 /// println!("{}", s.capacity());
240 ///
241 /// for _ in 0..5 {
242 ///     s.push_str("hello");
243 ///     println!("{}", s.capacity());
244 /// }
245 /// ```
246 ///
247 /// [`with_capacity()`]: #method.with_capacity
248 ///
249 /// We end up with a different output:
250 ///
251 /// ```text
252 /// 25
253 /// 25
254 /// 25
255 /// 25
256 /// 25
257 /// 25
258 /// ```
259 ///
260 /// Here, there's no need to allocate more memory inside the loop.
261 #[derive(PartialOrd, Eq, Ord)]
262 #[stable(feature = "rust1", since = "1.0.0")]
263 pub struct String {
264     vec: Vec<u8>,
265 }
266
267 /// A possible error value when converting a `String` from a UTF-8 byte vector.
268 ///
269 /// This type is the error type for the [`from_utf8()`] method on [`String`]. It
270 /// is designed in such a way to carefully avoid reallocations: the
271 /// [`into_bytes()`] method will give back the byte vector that was used in the
272 /// conversion attempt.
273 ///
274 /// [`from_utf8()`]: struct.String.html#method.from_utf8
275 /// [`String`]: struct.String.html
276 /// [`into_bytes()`]: struct.FromUtf8Error.html#method.into_bytes
277 ///
278 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
279 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
280 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
281 /// through the [`utf8_error()`] method.
282 ///
283 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
284 /// [`std::str`]: ../../std/str/index.html
285 /// [`u8`]: ../../std/primitive.u8.html
286 /// [`&str`]: ../../std/primitive.str.html
287 /// [`utf8_error()`]: #method.utf8_error
288 ///
289 /// # Examples
290 ///
291 /// Basic usage:
292 ///
293 /// ```
294 /// // some invalid bytes, in a vector
295 /// let bytes = vec![0, 159];
296 ///
297 /// let value = String::from_utf8(bytes);
298 ///
299 /// assert!(value.is_err());
300 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
301 /// ```
302 #[stable(feature = "rust1", since = "1.0.0")]
303 #[derive(Debug)]
304 pub struct FromUtf8Error {
305     bytes: Vec<u8>,
306     error: Utf8Error,
307 }
308
309 /// A possible error value when converting a `String` from a UTF-16 byte slice.
310 ///
311 /// This type is the error type for the [`from_utf16()`] method on [`String`].
312 ///
313 /// [`from_utf16()`]: struct.String.html#method.from_utf16
314 /// [`String`]: struct.String.html
315 ///
316 /// # Examples
317 ///
318 /// Basic usage:
319 ///
320 /// ```
321 /// // 𝄞mu<invalid>ic
322 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
323 ///           0xD800, 0x0069, 0x0063];
324 ///
325 /// assert!(String::from_utf16(v).is_err());
326 /// ```
327 #[stable(feature = "rust1", since = "1.0.0")]
328 #[derive(Debug)]
329 pub struct FromUtf16Error(());
330
331 impl String {
332     /// Creates a new empty `String`.
333     ///
334     /// Given that the `String` is empty, this will not allocate any initial
335     /// buffer. While that means that this initial operation is very
336     /// inexpensive, but may cause excessive allocation later, when you add
337     /// data. If you have an idea of how much data the `String` will hold,
338     /// consider the [`with_capacity()`] method to prevent excessive
339     /// re-allocation.
340     ///
341     /// [`with_capacity()`]: #method.with_capacity
342     ///
343     /// # Examples
344     ///
345     /// Basic usage:
346     ///
347     /// ```
348     /// let s = String::new();
349     /// ```
350     #[inline]
351     #[stable(feature = "rust1", since = "1.0.0")]
352     pub fn new() -> String {
353         String { vec: Vec::new() }
354     }
355
356     /// Creates a new empty `String` with a particular capacity.
357     ///
358     /// `String`s have an internal buffer to hold their data. The capacity is
359     /// the length of that buffer, and can be queried with the [`capacity()`]
360     /// method. This method creates an empty `String`, but one with an initial
361     /// buffer that can hold `capacity` bytes. This is useful when you may be
362     /// appending a bunch of data to the `String`, reducing the number of
363     /// reallocations it needs to do.
364     ///
365     /// [`capacity()`]: #method.capacity
366     ///
367     /// If the given capacity is `0`, no allocation will occur, and this method
368     /// is identical to the [`new()`] method.
369     ///
370     /// [`new()`]: #method.new
371     ///
372     /// # Examples
373     ///
374     /// Basic usage:
375     ///
376     /// ```
377     /// let mut s = String::with_capacity(10);
378     ///
379     /// // The String contains no chars, even though it has capacity for more
380     /// assert_eq!(s.len(), 0);
381     ///
382     /// // These are all done without reallocating...
383     /// let cap = s.capacity();
384     /// for i in 0..10 {
385     ///     s.push('a');
386     /// }
387     ///
388     /// assert_eq!(s.capacity(), cap);
389     ///
390     /// // ...but this may make the vector reallocate
391     /// s.push('a');
392     /// ```
393     #[inline]
394     #[stable(feature = "rust1", since = "1.0.0")]
395     pub fn with_capacity(capacity: usize) -> String {
396         String { vec: Vec::with_capacity(capacity) }
397     }
398
399     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
400     // required for this method definition, is not available. Since we don't
401     // require this method for testing purposes, I'll just stub it
402     // NB see the slice::hack module in slice.rs for more information
403     #[inline]
404     #[cfg(test)]
405     pub fn from_str(_: &str) -> String {
406         panic!("not available with cfg(test)");
407     }
408
409     /// Converts a vector of bytes to a `String`.
410     ///
411     /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
412     /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
413     /// two. Not all byte slices are valid `String`s, however: `String`
414     /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
415     /// the bytes are valid UTF-8, and then does the conversion.
416     ///
417     /// [`&str`]: ../../std/primitive.str.html
418     /// [`u8`]: ../../std/primitive.u8.html
419     /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
420     ///
421     /// If you are sure that the byte slice is valid UTF-8, and you don't want
422     /// to incur the overhead of the validity check, there is an unsafe version
423     /// of this function, [`from_utf8_unchecked()`], which has the same behavior
424     /// but skips the check.
425     ///
426     /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
427     ///
428     /// This method will take care to not copy the vector, for efficiency's
429     /// sake.
430     ///
431     /// If you need a `&str` instead of a `String`, consider
432     /// [`str::from_utf8()`].
433     ///
434     /// [`str::from_utf8()`]: ../../std/str/fn.from_utf8.html
435     ///
436     /// # Errors
437     ///
438     /// Returns `Err` if the slice is not UTF-8 with a description as to why the
439     /// provided bytes are not UTF-8. The vector you moved in is also included.
440     ///
441     /// # Examples
442     ///
443     /// Basic usage:
444     ///
445     /// ```
446     /// // some bytes, in a vector
447     /// let sparkle_heart = vec![240, 159, 146, 150];
448     ///
449     /// // We know these bytes are valid, so we'll use `unwrap()`.
450     /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
451     ///
452     /// assert_eq!("💖", sparkle_heart);
453     /// ```
454     ///
455     /// Incorrect bytes:
456     ///
457     /// ```
458     /// // some invalid bytes, in a vector
459     /// let sparkle_heart = vec![0, 159, 146, 150];
460     ///
461     /// assert!(String::from_utf8(sparkle_heart).is_err());
462     /// ```
463     ///
464     /// See the docs for [`FromUtf8Error`] for more details on what you can do
465     /// with this error.
466     ///
467     /// [`FromUtf8Error`]: struct.FromUtf8Error.html
468     #[inline]
469     #[stable(feature = "rust1", since = "1.0.0")]
470     pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
471         match str::from_utf8(&vec) {
472             Ok(..) => Ok(String { vec: vec }),
473             Err(e) => {
474                 Err(FromUtf8Error {
475                     bytes: vec,
476                     error: e,
477                 })
478             }
479         }
480     }
481
482     /// Converts a slice of bytes to a string, including invalid characters.
483     ///
484     /// Strings are made of bytes ([`u8`]), and a slice of bytes
485     /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
486     /// between the two. Not all byte slices are valid strings, however: strings
487     /// are required to be valid UTF-8. During this conversion,
488     /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
489     /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
490     ///
491     /// [`u8`]: ../../std/primitive.u8.html
492     /// [byteslice]: ../../std/primitive.slice.html
493     ///
494     /// If you are sure that the byte slice is valid UTF-8, and you don't want
495     /// to incur the overhead of the conversion, there is an unsafe version
496     /// of this function, [`from_utf8_unchecked()`], which has the same behavior
497     /// but skips the checks.
498     ///
499     /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
500     ///
501     /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
502     /// UTF-8, then we need to insert the replacement characters, which will
503     /// change the size of the string, and hence, require a `String`. But if
504     /// it's already valid UTF-8, we don't need a new allocation. This return
505     /// type allows us to handle both cases.
506     ///
507     /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
508     ///
509     /// # Examples
510     ///
511     /// Basic usage:
512     ///
513     /// ```
514     /// // some bytes, in a vector
515     /// let sparkle_heart = vec![240, 159, 146, 150];
516     ///
517     /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
518     ///
519     /// assert_eq!("💖", sparkle_heart);
520     /// ```
521     ///
522     /// Incorrect bytes:
523     ///
524     /// ```
525     /// // some invalid bytes
526     /// let input = b"Hello \xF0\x90\x80World";
527     /// let output = String::from_utf8_lossy(input);
528     ///
529     /// assert_eq!("Hello �World", output);
530     /// ```
531     #[stable(feature = "rust1", since = "1.0.0")]
532     pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
533         let mut i;
534         match str::from_utf8(v) {
535             Ok(s) => return Cow::Borrowed(s),
536             Err(e) => i = e.valid_up_to(),
537         }
538
539         const TAG_CONT_U8: u8 = 128;
540         const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
541         let total = v.len();
542         fn unsafe_get(xs: &[u8], i: usize) -> u8 {
543             unsafe { *xs.get_unchecked(i) }
544         }
545         fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
546             if i >= total {
547                 0
548             } else {
549                 unsafe_get(xs, i)
550             }
551         }
552
553         let mut res = String::with_capacity(total);
554
555         if i > 0 {
556             unsafe { res.as_mut_vec().extend_from_slice(&v[..i]) };
557         }
558
559         // subseqidx is the index of the first byte of the subsequence we're
560         // looking at.  It's used to copy a bunch of contiguous good codepoints
561         // at once instead of copying them one by one.
562         let mut subseqidx = i;
563
564         while i < total {
565             let i_ = i;
566             let byte = unsafe_get(v, i);
567             i += 1;
568
569             macro_rules! error { () => ({
570                 unsafe {
571                     if subseqidx != i_ {
572                         res.as_mut_vec().extend_from_slice(&v[subseqidx..i_]);
573                     }
574                     subseqidx = i;
575                     res.as_mut_vec().extend_from_slice(REPLACEMENT);
576                 }
577             })}
578
579             if byte < 128 {
580                 // subseqidx handles this
581             } else {
582                 let w = unicode_str::utf8_char_width(byte);
583
584                 match w {
585                     2 => {
586                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
587                             error!();
588                             continue;
589                         }
590                         i += 1;
591                     }
592                     3 => {
593                         match (byte, safe_get(v, i, total)) {
594                             (0xE0, 0xA0...0xBF) => (),
595                             (0xE1...0xEC, 0x80...0xBF) => (),
596                             (0xED, 0x80...0x9F) => (),
597                             (0xEE...0xEF, 0x80...0xBF) => (),
598                             _ => {
599                                 error!();
600                                 continue;
601                             }
602                         }
603                         i += 1;
604                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
605                             error!();
606                             continue;
607                         }
608                         i += 1;
609                     }
610                     4 => {
611                         match (byte, safe_get(v, i, total)) {
612                             (0xF0, 0x90...0xBF) => (),
613                             (0xF1...0xF3, 0x80...0xBF) => (),
614                             (0xF4, 0x80...0x8F) => (),
615                             _ => {
616                                 error!();
617                                 continue;
618                             }
619                         }
620                         i += 1;
621                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
622                             error!();
623                             continue;
624                         }
625                         i += 1;
626                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
627                             error!();
628                             continue;
629                         }
630                         i += 1;
631                     }
632                     _ => {
633                         error!();
634                         continue;
635                     }
636                 }
637             }
638         }
639         if subseqidx < total {
640             unsafe { res.as_mut_vec().extend_from_slice(&v[subseqidx..total]) };
641         }
642         Cow::Owned(res)
643     }
644
645     /// Decode a UTF-16 encoded vector `v` into a `String`, returning `Err`
646     /// if `v` contains any invalid data.
647     ///
648     /// # Examples
649     ///
650     /// Basic usage:
651     ///
652     /// ```
653     /// // 𝄞music
654     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
655     ///           0x0073, 0x0069, 0x0063];
656     /// assert_eq!(String::from("𝄞music"),
657     ///            String::from_utf16(v).unwrap());
658     ///
659     /// // 𝄞mu<invalid>ic
660     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
661     ///           0xD800, 0x0069, 0x0063];
662     /// assert!(String::from_utf16(v).is_err());
663     /// ```
664     #[stable(feature = "rust1", since = "1.0.0")]
665     pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
666         decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
667     }
668
669     /// Decode a UTF-16 encoded vector `v` into a string, replacing
670     /// invalid data with the replacement character (U+FFFD).
671     ///
672     /// # Examples
673     ///
674     /// Basic usage:
675     ///
676     /// ```
677     /// // 𝄞mus<invalid>ic<invalid>
678     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
679     ///           0x0073, 0xDD1E, 0x0069, 0x0063,
680     ///           0xD834];
681     ///
682     /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
683     ///            String::from_utf16_lossy(v));
684     /// ```
685     #[inline]
686     #[stable(feature = "rust1", since = "1.0.0")]
687     pub fn from_utf16_lossy(v: &[u16]) -> String {
688         decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
689     }
690
691     /// Creates a new `String` from a length, capacity, and pointer.
692     ///
693     /// # Safety
694     ///
695     /// This is highly unsafe, due to the number of invariants that aren't
696     /// checked:
697     ///
698     /// * The memory at `ptr` needs to have been previously allocated by the
699     ///   same allocator the standard library uses.
700     /// * `length` needs to be less than or equal to `capacity`.
701     /// * `capacity` needs to be the correct value.
702     ///
703     /// Violating these may cause problems like corrupting the allocator's
704     /// internal datastructures.
705     ///
706     /// # Examples
707     ///
708     /// Basic usage:
709     ///
710     /// ```
711     /// use std::mem;
712     ///
713     /// unsafe {
714     ///     let s = String::from("hello");
715     ///     let ptr = s.as_ptr();
716     ///     let len = s.len();
717     ///     let capacity = s.capacity();
718     ///
719     ///     mem::forget(s);
720     ///
721     ///     let s = String::from_raw_parts(ptr as *mut _, len, capacity);
722     ///
723     ///     assert_eq!(String::from("hello"), s);
724     /// }
725     /// ```
726     #[inline]
727     #[stable(feature = "rust1", since = "1.0.0")]
728     pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
729         String { vec: Vec::from_raw_parts(buf, length, capacity) }
730     }
731
732     /// Converts a vector of bytes to a `String` without checking that the
733     /// string contains valid UTF-8.
734     ///
735     /// See the safe version, [`from_utf8()`], for more details.
736     ///
737     /// [`from_utf8()`]: struct.String.html#method.from_utf8
738     ///
739     /// # Safety
740     ///
741     /// This function is unsafe because it does not check that the bytes passed
742     /// to it are valid UTF-8. If this constraint is violated, it may cause
743     /// memory unsafety issues with future users of the `String`, as the rest of
744     /// the standard library assumes that `String`s are valid UTF-8.
745     ///
746     /// # Examples
747     ///
748     /// Basic usage:
749     ///
750     /// ```
751     /// // some bytes, in a vector
752     /// let sparkle_heart = vec![240, 159, 146, 150];
753     ///
754     /// let sparkle_heart = unsafe {
755     ///     String::from_utf8_unchecked(sparkle_heart)
756     /// };
757     ///
758     /// assert_eq!("💖", sparkle_heart);
759     /// ```
760     #[inline]
761     #[stable(feature = "rust1", since = "1.0.0")]
762     pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
763         String { vec: bytes }
764     }
765
766     /// Converts a `String` into a byte vector.
767     ///
768     /// This consumes the `String`, so we do not need to copy its contents.
769     ///
770     /// # Examples
771     ///
772     /// Basic usage:
773     ///
774     /// ```
775     /// let s = String::from("hello");
776     /// let bytes = s.into_bytes();
777     ///
778     /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
779     /// ```
780     #[inline]
781     #[stable(feature = "rust1", since = "1.0.0")]
782     pub fn into_bytes(self) -> Vec<u8> {
783         self.vec
784     }
785
786     /// Extracts a string slice containing the entire string.
787     #[inline]
788     #[stable(feature = "string_as_str", since = "1.7.0")]
789     pub fn as_str(&self) -> &str {
790         self
791     }
792
793     /// Extracts a string slice containing the entire string.
794     #[inline]
795     #[stable(feature = "string_as_str", since = "1.7.0")]
796     pub fn as_mut_str(&mut self) -> &mut str {
797         self
798     }
799
800     /// Appends a given string slice onto the end of this `String`.
801     ///
802     /// # Examples
803     ///
804     /// Basic usage:
805     ///
806     /// ```
807     /// let mut s = String::from("foo");
808     ///
809     /// s.push_str("bar");
810     ///
811     /// assert_eq!("foobar", s);
812     /// ```
813     #[inline]
814     #[stable(feature = "rust1", since = "1.0.0")]
815     pub fn push_str(&mut self, string: &str) {
816         self.vec.extend_from_slice(string.as_bytes())
817     }
818
819     /// Returns this `String`'s capacity, in bytes.
820     ///
821     /// # Examples
822     ///
823     /// Basic usage:
824     ///
825     /// ```
826     /// let s = String::with_capacity(10);
827     ///
828     /// assert!(s.capacity() >= 10);
829     /// ```
830     #[inline]
831     #[stable(feature = "rust1", since = "1.0.0")]
832     pub fn capacity(&self) -> usize {
833         self.vec.capacity()
834     }
835
836     /// Ensures that this `String`'s capacity is at least `additional` bytes
837     /// larger than its length.
838     ///
839     /// The capacity may be increased by more than `additional` bytes if it
840     /// chooses, to prevent frequent reallocations.
841     ///
842     /// If you do not want this "at least" behavior, see the [`reserve_exact()`]
843     /// method.
844     ///
845     /// [`reserve_exact()`]: #method.reserve_exact
846     ///
847     /// # Panics
848     ///
849     /// Panics if the new capacity overflows `usize`.
850     ///
851     /// # Examples
852     ///
853     /// Basic usage:
854     ///
855     /// ```
856     /// let mut s = String::new();
857     ///
858     /// s.reserve(10);
859     ///
860     /// assert!(s.capacity() >= 10);
861     /// ```
862     ///
863     /// This may not actually increase the capacity:
864     ///
865     /// ```
866     /// let mut s = String::with_capacity(10);
867     /// s.push('a');
868     /// s.push('b');
869     ///
870     /// // s now has a length of 2 and a capacity of 10
871     /// assert_eq!(2, s.len());
872     /// assert_eq!(10, s.capacity());
873     ///
874     /// // Since we already have an extra 8 capacity, calling this...
875     /// s.reserve(8);
876     ///
877     /// // ... doesn't actually increase.
878     /// assert_eq!(10, s.capacity());
879     /// ```
880     #[inline]
881     #[stable(feature = "rust1", since = "1.0.0")]
882     pub fn reserve(&mut self, additional: usize) {
883         self.vec.reserve(additional)
884     }
885
886     /// Ensures that this `String`'s capacity is `additional` bytes
887     /// larger than its length.
888     ///
889     /// Consider using the [`reserve()`] method unless you absolutely know
890     /// better than the allocator.
891     ///
892     /// [`reserve()`]: #method.reserve
893     ///
894     /// # Panics
895     ///
896     /// Panics if the new capacity overflows `usize`.
897     ///
898     /// # Examples
899     ///
900     /// Basic usage:
901     ///
902     /// ```
903     /// let mut s = String::new();
904     ///
905     /// s.reserve_exact(10);
906     ///
907     /// assert!(s.capacity() >= 10);
908     /// ```
909     ///
910     /// This may not actually increase the capacity:
911     ///
912     /// ```
913     /// let mut s = String::with_capacity(10);
914     /// s.push('a');
915     /// s.push('b');
916     ///
917     /// // s now has a length of 2 and a capacity of 10
918     /// assert_eq!(2, s.len());
919     /// assert_eq!(10, s.capacity());
920     ///
921     /// // Since we already have an extra 8 capacity, calling this...
922     /// s.reserve_exact(8);
923     ///
924     /// // ... doesn't actually increase.
925     /// assert_eq!(10, s.capacity());
926     /// ```
927     #[inline]
928     #[stable(feature = "rust1", since = "1.0.0")]
929     pub fn reserve_exact(&mut self, additional: usize) {
930         self.vec.reserve_exact(additional)
931     }
932
933     /// Shrinks the capacity of this `String` to match its length.
934     ///
935     /// # Examples
936     ///
937     /// Basic usage:
938     ///
939     /// ```
940     /// let mut s = String::from("foo");
941     ///
942     /// s.reserve(100);
943     /// assert!(s.capacity() >= 100);
944     ///
945     /// s.shrink_to_fit();
946     /// assert_eq!(3, s.capacity());
947     /// ```
948     #[inline]
949     #[stable(feature = "rust1", since = "1.0.0")]
950     pub fn shrink_to_fit(&mut self) {
951         self.vec.shrink_to_fit()
952     }
953
954     /// Appends the given `char` to the end of this `String`.
955     ///
956     /// # Examples
957     ///
958     /// Basic usage:
959     ///
960     /// ```
961     /// let mut s = String::from("abc");
962     ///
963     /// s.push('1');
964     /// s.push('2');
965     /// s.push('3');
966     ///
967     /// assert_eq!("abc123", s);
968     /// ```
969     #[inline]
970     #[stable(feature = "rust1", since = "1.0.0")]
971     pub fn push(&mut self, ch: char) {
972         match ch.len_utf8() {
973             1 => self.vec.push(ch as u8),
974             ch_len => {
975                 let cur_len = self.len();
976                 // This may use up to 4 bytes.
977                 self.vec.reserve(ch_len);
978
979                 unsafe {
980                     // Attempt to not use an intermediate buffer by just pushing bytes
981                     // directly onto this string.
982                     let slice = slice::from_raw_parts_mut(self.vec
983                                                               .as_mut_ptr()
984                                                               .offset(cur_len as isize),
985                                                           ch_len);
986                     let used = ch.encode_utf8(slice).unwrap_or(0);
987                     self.vec.set_len(cur_len + used);
988                 }
989             }
990         }
991     }
992
993     /// Returns a byte slice of this `String`'s contents.
994     ///
995     /// # Examples
996     ///
997     /// Basic usage:
998     ///
999     /// ```
1000     /// let s = String::from("hello");
1001     ///
1002     /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1003     /// ```
1004     #[inline]
1005     #[stable(feature = "rust1", since = "1.0.0")]
1006     pub fn as_bytes(&self) -> &[u8] {
1007         &self.vec
1008     }
1009
1010     /// Shortens this `String` to the specified length.
1011     ///
1012     /// # Panics
1013     ///
1014     /// Panics if `new_len` > current length, or if `new_len` does not lie on a
1015     /// [`char`] boundary.
1016     ///
1017     /// [`char`]: ../../std/primitive.char.html
1018     ///
1019     /// # Examples
1020     ///
1021     /// Basic usage:
1022     ///
1023     /// ```
1024     /// let mut s = String::from("hello");
1025     ///
1026     /// s.truncate(2);
1027     ///
1028     /// assert_eq!("he", s);
1029     /// ```
1030     #[inline]
1031     #[stable(feature = "rust1", since = "1.0.0")]
1032     pub fn truncate(&mut self, new_len: usize) {
1033         assert!(self.is_char_boundary(new_len));
1034         self.vec.truncate(new_len)
1035     }
1036
1037     /// Removes the last character from the string buffer and returns it.
1038     ///
1039     /// Returns `None` if this `String` is empty.
1040     ///
1041     /// # Examples
1042     ///
1043     /// Basic usage:
1044     ///
1045     /// ```
1046     /// let mut s = String::from("foo");
1047     ///
1048     /// assert_eq!(s.pop(), Some('o'));
1049     /// assert_eq!(s.pop(), Some('o'));
1050     /// assert_eq!(s.pop(), Some('f'));
1051     ///
1052     /// assert_eq!(s.pop(), None);
1053     /// ```
1054     #[inline]
1055     #[stable(feature = "rust1", since = "1.0.0")]
1056     pub fn pop(&mut self) -> Option<char> {
1057         let len = self.len();
1058         if len == 0 {
1059             return None;
1060         }
1061
1062         let ch = self.char_at_reverse(len);
1063         unsafe {
1064             self.vec.set_len(len - ch.len_utf8());
1065         }
1066         Some(ch)
1067     }
1068
1069     /// Removes a `char` from this `String` at a byte position and returns it.
1070     ///
1071     /// This is an `O(n)` operation, as it requires copying every element in the
1072     /// buffer.
1073     ///
1074     /// # Panics
1075     ///
1076     /// Panics if `idx` is larger than or equal to the `String`'s length,
1077     /// or if it does not lie on a [`char`] boundary.
1078     ///
1079     /// [`char`]: ../../std/primitive.char.html
1080     ///
1081     /// # Examples
1082     ///
1083     /// Basic usage:
1084     ///
1085     /// ```
1086     /// let mut s = String::from("foo");
1087     ///
1088     /// assert_eq!(s.remove(0), 'f');
1089     /// assert_eq!(s.remove(1), 'o');
1090     /// assert_eq!(s.remove(0), 'o');
1091     /// ```
1092     #[inline]
1093     #[stable(feature = "rust1", since = "1.0.0")]
1094     pub fn remove(&mut self, idx: usize) -> char {
1095         let len = self.len();
1096         assert!(idx < len);
1097
1098         let ch = self.char_at(idx);
1099         let next = idx + ch.len_utf8();
1100         unsafe {
1101             ptr::copy(self.vec.as_ptr().offset(next as isize),
1102                       self.vec.as_mut_ptr().offset(idx as isize),
1103                       len - next);
1104             self.vec.set_len(len - (next - idx));
1105         }
1106         ch
1107     }
1108
1109     /// Inserts a character into this `String` at a byte position.
1110     ///
1111     /// This is an `O(n)` operation as it requires copying every element in the
1112     /// buffer.
1113     ///
1114     /// # Panics
1115     ///
1116     /// Panics if `idx` is larger than the `String`'s length, or if it does not
1117     /// lie on a [`char`] boundary.
1118     ///
1119     /// [`char`]: ../../std/primitive.char.html
1120     ///
1121     /// # Examples
1122     ///
1123     /// Basic usage:
1124     ///
1125     /// ```
1126     /// let mut s = String::with_capacity(3);
1127     ///
1128     /// s.insert(0, 'f');
1129     /// s.insert(1, 'o');
1130     /// s.insert(2, 'o');
1131     ///
1132     /// assert_eq!("foo", s);
1133     /// ```
1134     #[inline]
1135     #[stable(feature = "rust1", since = "1.0.0")]
1136     pub fn insert(&mut self, idx: usize, ch: char) {
1137         let len = self.len();
1138         assert!(idx <= len);
1139         assert!(self.is_char_boundary(idx));
1140         self.vec.reserve(4);
1141         let mut bits = [0; 4];
1142         let amt = ch.encode_utf8(&mut bits).unwrap();
1143
1144         unsafe {
1145             ptr::copy(self.vec.as_ptr().offset(idx as isize),
1146                       self.vec.as_mut_ptr().offset((idx + amt) as isize),
1147                       len - idx);
1148             ptr::copy(bits.as_ptr(),
1149                       self.vec.as_mut_ptr().offset(idx as isize),
1150                       amt);
1151             self.vec.set_len(len + amt);
1152         }
1153     }
1154
1155     /// Returns a mutable reference to the contents of this `String`.
1156     ///
1157     /// # Safety
1158     ///
1159     /// This function is unsafe because it does not check that the bytes passed
1160     /// to it are valid UTF-8. If this constraint is violated, it may cause
1161     /// memory unsafety issues with future users of the `String`, as the rest of
1162     /// the standard library assumes that `String`s are valid UTF-8.
1163     ///
1164     /// # Examples
1165     ///
1166     /// Basic usage:
1167     ///
1168     /// ```
1169     /// let mut s = String::from("hello");
1170     ///
1171     /// unsafe {
1172     ///     let vec = s.as_mut_vec();
1173     ///     assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1174     ///
1175     ///     vec.reverse();
1176     /// }
1177     /// assert_eq!(s, "olleh");
1178     /// ```
1179     #[inline]
1180     #[stable(feature = "rust1", since = "1.0.0")]
1181     pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1182         &mut self.vec
1183     }
1184
1185     /// Returns the length of this `String`, in bytes.
1186     ///
1187     /// # Examples
1188     ///
1189     /// Basic usage:
1190     ///
1191     /// ```
1192     /// let a = String::from("foo");
1193     ///
1194     /// assert_eq!(a.len(), 3);
1195     /// ```
1196     #[inline]
1197     #[stable(feature = "rust1", since = "1.0.0")]
1198     pub fn len(&self) -> usize {
1199         self.vec.len()
1200     }
1201
1202     /// Returns `true` if this `String` has a length of zero.
1203     ///
1204     /// Returns `false` otherwise.
1205     ///
1206     /// # Examples
1207     ///
1208     /// Basic usage:
1209     ///
1210     /// ```
1211     /// let mut v = String::new();
1212     /// assert!(v.is_empty());
1213     ///
1214     /// v.push('a');
1215     /// assert!(!v.is_empty());
1216     /// ```
1217     #[inline]
1218     #[stable(feature = "rust1", since = "1.0.0")]
1219     pub fn is_empty(&self) -> bool {
1220         self.len() == 0
1221     }
1222
1223     /// Truncates this `String`, removing all contents.
1224     ///
1225     /// While this means the `String` will have a length of zero, it does not
1226     /// touch its capacity.
1227     ///
1228     /// # Examples
1229     ///
1230     /// Basic usage:
1231     ///
1232     /// ```
1233     /// let mut s = String::from("foo");
1234     ///
1235     /// s.clear();
1236     ///
1237     /// assert!(s.is_empty());
1238     /// assert_eq!(0, s.len());
1239     /// assert_eq!(3, s.capacity());
1240     /// ```
1241     #[inline]
1242     #[stable(feature = "rust1", since = "1.0.0")]
1243     pub fn clear(&mut self) {
1244         self.vec.clear()
1245     }
1246
1247     /// Create a draining iterator that removes the specified range in the string
1248     /// and yields the removed chars.
1249     ///
1250     /// Note: The element range is removed even if the iterator is not
1251     /// consumed until the end.
1252     ///
1253     /// # Panics
1254     ///
1255     /// Panics if the starting point or end point do not lie on a [`char`]
1256     /// boundary, or if they're out of bounds.
1257     ///
1258     /// [`char`]: ../../std/primitive.char.html
1259     ///
1260     /// # Examples
1261     ///
1262     /// Basic usage:
1263     ///
1264     /// ```
1265     /// let mut s = String::from("α is alpha, β is beta");
1266     /// let beta_offset = s.find('β').unwrap_or(s.len());
1267     ///
1268     /// // Remove the range up until the β from the string
1269     /// let t: String = s.drain(..beta_offset).collect();
1270     /// assert_eq!(t, "α is alpha, ");
1271     /// assert_eq!(s, "β is beta");
1272     ///
1273     /// // A full range clears the string
1274     /// s.drain(..);
1275     /// assert_eq!(s, "");
1276     /// ```
1277     #[stable(feature = "drain", since = "1.6.0")]
1278     pub fn drain<R>(&mut self, range: R) -> Drain
1279         where R: RangeArgument<usize>
1280     {
1281         // Memory safety
1282         //
1283         // The String version of Drain does not have the memory safety issues
1284         // of the vector version. The data is just plain bytes.
1285         // Because the range removal happens in Drop, if the Drain iterator is leaked,
1286         // the removal will not happen.
1287         let len = self.len();
1288         let start = *range.start().unwrap_or(&0);
1289         let end = *range.end().unwrap_or(&len);
1290
1291         // Take out two simultaneous borrows. The &mut String won't be accessed
1292         // until iteration is over, in Drop.
1293         let self_ptr = self as *mut _;
1294         // slicing does the appropriate bounds checks
1295         let chars_iter = self[start..end].chars();
1296
1297         Drain {
1298             start: start,
1299             end: end,
1300             iter: chars_iter,
1301             string: self_ptr,
1302         }
1303     }
1304
1305     /// Converts this `String` into a `Box<str>`.
1306     ///
1307     /// This will drop any excess capacity.
1308     ///
1309     /// # Examples
1310     ///
1311     /// Basic usage:
1312     ///
1313     /// ```
1314     /// let s = String::from("hello");
1315     ///
1316     /// let b = s.into_boxed_str();
1317     /// ```
1318     #[stable(feature = "box_str", since = "1.4.0")]
1319     pub fn into_boxed_str(self) -> Box<str> {
1320         let slice = self.vec.into_boxed_slice();
1321         unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
1322     }
1323 }
1324
1325 impl FromUtf8Error {
1326     /// Returns the bytes that were attempted to convert to a `String`.
1327     ///
1328     /// This method is carefully constructed to avoid allocation. It will
1329     /// consume the error, moving out the bytes, so that a copy of the bytes
1330     /// does not need to be made.
1331     ///
1332     /// # Examples
1333     ///
1334     /// Basic usage:
1335     ///
1336     /// ```
1337     /// // some invalid bytes, in a vector
1338     /// let bytes = vec![0, 159];
1339     ///
1340     /// let value = String::from_utf8(bytes);
1341     ///
1342     /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1343     /// ```
1344     #[stable(feature = "rust1", since = "1.0.0")]
1345     pub fn into_bytes(self) -> Vec<u8> {
1346         self.bytes
1347     }
1348
1349     /// Fetch a `Utf8Error` to get more details about the conversion failure.
1350     ///
1351     /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1352     /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1353     /// an analogue to `FromUtf8Error`. See its documentation for more details
1354     /// on using it.
1355     ///
1356     /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1357     /// [`std::str`]: ../../std/str/index.html
1358     /// [`u8`]: ../../std/primitive.u8.html
1359     /// [`&str`]: ../../std/primitive.str.html
1360     ///
1361     /// # Examples
1362     ///
1363     /// Basic usage:
1364     ///
1365     /// ```
1366     /// // some invalid bytes, in a vector
1367     /// let bytes = vec![0, 159];
1368     ///
1369     /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1370     ///
1371     /// // the first byte is invalid here
1372     /// assert_eq!(1, error.valid_up_to());
1373     /// ```
1374     #[stable(feature = "rust1", since = "1.0.0")]
1375     pub fn utf8_error(&self) -> Utf8Error {
1376         self.error
1377     }
1378 }
1379
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 impl fmt::Display for FromUtf8Error {
1382     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1383         fmt::Display::fmt(&self.error, f)
1384     }
1385 }
1386
1387 #[stable(feature = "rust1", since = "1.0.0")]
1388 impl fmt::Display for FromUtf16Error {
1389     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1390         fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1391     }
1392 }
1393
1394 #[stable(feature = "rust1", since = "1.0.0")]
1395 impl Clone for String {
1396     fn clone(&self) -> Self {
1397         String { vec: self.vec.clone() }
1398     }
1399
1400     fn clone_from(&mut self, source: &Self) {
1401         self.vec.clone_from(&source.vec);
1402     }
1403 }
1404
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl FromIterator<char> for String {
1407     fn from_iter<I: IntoIterator<Item = char>>(iterable: I) -> String {
1408         let mut buf = String::new();
1409         buf.extend(iterable);
1410         buf
1411     }
1412 }
1413
1414 #[stable(feature = "rust1", since = "1.0.0")]
1415 impl<'a> FromIterator<&'a str> for String {
1416     fn from_iter<I: IntoIterator<Item = &'a str>>(iterable: I) -> String {
1417         let mut buf = String::new();
1418         buf.extend(iterable);
1419         buf
1420     }
1421 }
1422
1423 #[stable(feature = "extend_string", since = "1.4.0")]
1424 impl FromIterator<String> for String {
1425     fn from_iter<I: IntoIterator<Item = String>>(iterable: I) -> String {
1426         let mut buf = String::new();
1427         buf.extend(iterable);
1428         buf
1429     }
1430 }
1431
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl Extend<char> for String {
1434     fn extend<I: IntoIterator<Item = char>>(&mut self, iterable: I) {
1435         let iterator = iterable.into_iter();
1436         let (lower_bound, _) = iterator.size_hint();
1437         self.reserve(lower_bound);
1438         for ch in iterator {
1439             self.push(ch)
1440         }
1441     }
1442 }
1443
1444 #[stable(feature = "extend_ref", since = "1.2.0")]
1445 impl<'a> Extend<&'a char> for String {
1446     fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iterable: I) {
1447         self.extend(iterable.into_iter().cloned());
1448     }
1449 }
1450
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 impl<'a> Extend<&'a str> for String {
1453     fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iterable: I) {
1454         for s in iterable {
1455             self.push_str(s)
1456         }
1457     }
1458 }
1459
1460 #[stable(feature = "extend_string", since = "1.4.0")]
1461 impl Extend<String> for String {
1462     fn extend<I: IntoIterator<Item = String>>(&mut self, iterable: I) {
1463         for s in iterable {
1464             self.push_str(&s)
1465         }
1466     }
1467 }
1468
1469 /// A convenience impl that delegates to the impl for `&str`
1470 #[unstable(feature = "pattern",
1471            reason = "API not fully fleshed out and ready to be stabilized",
1472            issue = "27721")]
1473 impl<'a, 'b> Pattern<'a> for &'b String {
1474     type Searcher = <&'b str as Pattern<'a>>::Searcher;
1475
1476     fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1477         self[..].into_searcher(haystack)
1478     }
1479
1480     #[inline]
1481     fn is_contained_in(self, haystack: &'a str) -> bool {
1482         self[..].is_contained_in(haystack)
1483     }
1484
1485     #[inline]
1486     fn is_prefix_of(self, haystack: &'a str) -> bool {
1487         self[..].is_prefix_of(haystack)
1488     }
1489 }
1490
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 impl PartialEq for String {
1493     #[inline]
1494     fn eq(&self, other: &String) -> bool {
1495         PartialEq::eq(&self[..], &other[..])
1496     }
1497     #[inline]
1498     fn ne(&self, other: &String) -> bool {
1499         PartialEq::ne(&self[..], &other[..])
1500     }
1501 }
1502
1503 macro_rules! impl_eq {
1504     ($lhs:ty, $rhs: ty) => {
1505         #[stable(feature = "rust1", since = "1.0.0")]
1506         impl<'a, 'b> PartialEq<$rhs> for $lhs {
1507             #[inline]
1508             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1509             #[inline]
1510             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1511         }
1512
1513         #[stable(feature = "rust1", since = "1.0.0")]
1514         impl<'a, 'b> PartialEq<$lhs> for $rhs {
1515             #[inline]
1516             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1517             #[inline]
1518             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1519         }
1520
1521     }
1522 }
1523
1524 impl_eq! { String, str }
1525 impl_eq! { String, &'a str }
1526 impl_eq! { Cow<'a, str>, str }
1527 impl_eq! { Cow<'a, str>, &'b str }
1528 impl_eq! { Cow<'a, str>, String }
1529
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl Default for String {
1532     #[inline]
1533     fn default() -> String {
1534         String::new()
1535     }
1536 }
1537
1538 #[stable(feature = "rust1", since = "1.0.0")]
1539 impl fmt::Display for String {
1540     #[inline]
1541     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1542         fmt::Display::fmt(&**self, f)
1543     }
1544 }
1545
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 impl fmt::Debug for String {
1548     #[inline]
1549     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1550         fmt::Debug::fmt(&**self, f)
1551     }
1552 }
1553
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 impl hash::Hash for String {
1556     #[inline]
1557     fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1558         (**self).hash(hasher)
1559     }
1560 }
1561
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl<'a> Add<&'a str> for String {
1564     type Output = String;
1565
1566     #[inline]
1567     fn add(mut self, other: &str) -> String {
1568         self.push_str(other);
1569         self
1570     }
1571 }
1572
1573 #[stable(feature = "rust1", since = "1.0.0")]
1574 impl ops::Index<ops::Range<usize>> for String {
1575     type Output = str;
1576
1577     #[inline]
1578     fn index(&self, index: ops::Range<usize>) -> &str {
1579         &self[..][index]
1580     }
1581 }
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 impl ops::Index<ops::RangeTo<usize>> for String {
1584     type Output = str;
1585
1586     #[inline]
1587     fn index(&self, index: ops::RangeTo<usize>) -> &str {
1588         &self[..][index]
1589     }
1590 }
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 impl ops::Index<ops::RangeFrom<usize>> for String {
1593     type Output = str;
1594
1595     #[inline]
1596     fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1597         &self[..][index]
1598     }
1599 }
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 impl ops::Index<ops::RangeFull> for String {
1602     type Output = str;
1603
1604     #[inline]
1605     fn index(&self, _index: ops::RangeFull) -> &str {
1606         unsafe { str::from_utf8_unchecked(&self.vec) }
1607     }
1608 }
1609 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1610 impl ops::Index<ops::RangeInclusive<usize>> for String {
1611     type Output = str;
1612
1613     #[inline]
1614     fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1615         Index::index(&**self, index)
1616     }
1617 }
1618 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1619 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1620     type Output = str;
1621
1622     #[inline]
1623     fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1624         Index::index(&**self, index)
1625     }
1626 }
1627
1628 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1629 impl ops::IndexMut<ops::Range<usize>> for String {
1630     #[inline]
1631     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1632         &mut self[..][index]
1633     }
1634 }
1635 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1636 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1637     #[inline]
1638     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1639         &mut self[..][index]
1640     }
1641 }
1642 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1643 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1644     #[inline]
1645     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1646         &mut self[..][index]
1647     }
1648 }
1649 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1650 impl ops::IndexMut<ops::RangeFull> for String {
1651     #[inline]
1652     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1653         unsafe { mem::transmute(&mut *self.vec) }
1654     }
1655 }
1656 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1657 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
1658     #[inline]
1659     fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1660         IndexMut::index_mut(&mut **self, index)
1661     }
1662 }
1663 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1664 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
1665     #[inline]
1666     fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1667         IndexMut::index_mut(&mut **self, index)
1668     }
1669 }
1670
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl ops::Deref for String {
1673     type Target = str;
1674
1675     #[inline]
1676     fn deref(&self) -> &str {
1677         unsafe { str::from_utf8_unchecked(&self.vec) }
1678     }
1679 }
1680
1681 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1682 impl ops::DerefMut for String {
1683     #[inline]
1684     fn deref_mut(&mut self) -> &mut str {
1685         unsafe { mem::transmute(&mut *self.vec) }
1686     }
1687 }
1688
1689 /// An error when parsing a `String`.
1690 ///
1691 /// This `enum` is slightly awkward: it will never actually exist. This error is
1692 /// part of the type signature of the implementation of [`FromStr`] on
1693 /// [`String`]. The return type of [`from_str()`], requires that an error be
1694 /// defined, but, given that a [`String`] can always be made into a new
1695 /// [`String`] without error, this type will never actually be returned. As
1696 /// such, it is only here to satisfy said signature, and is useless otherwise.
1697 ///
1698 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1699 /// [`String`]: struct.String.html
1700 /// [`from_str()`]: ../../std/str/trait.FromStr.html#tymethod.from_str
1701 #[stable(feature = "str_parse_error", since = "1.5.0")]
1702 #[derive(Copy)]
1703 pub enum ParseError {}
1704
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 impl FromStr for String {
1707     type Err = ParseError;
1708     #[inline]
1709     fn from_str(s: &str) -> Result<String, ParseError> {
1710         Ok(String::from(s))
1711     }
1712 }
1713
1714 #[stable(feature = "str_parse_error", since = "1.5.0")]
1715 impl Clone for ParseError {
1716     fn clone(&self) -> ParseError {
1717         match *self {}
1718     }
1719 }
1720
1721 #[stable(feature = "str_parse_error", since = "1.5.0")]
1722 impl fmt::Debug for ParseError {
1723     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1724         match *self {}
1725     }
1726 }
1727
1728 #[stable(feature = "str_parse_error2", since = "1.8.0")]
1729 impl fmt::Display for ParseError {
1730     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1731         match *self {}
1732     }
1733 }
1734
1735 #[stable(feature = "str_parse_error", since = "1.5.0")]
1736 impl PartialEq for ParseError {
1737     fn eq(&self, _: &ParseError) -> bool {
1738         match *self {}
1739     }
1740 }
1741
1742 #[stable(feature = "str_parse_error", since = "1.5.0")]
1743 impl Eq for ParseError {}
1744
1745 /// A trait for converting a value to a `String`.
1746 ///
1747 /// This trait is automatically implemented for any type which implements the
1748 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1749 /// [`Display`] should be implemented instead, and you get the `ToString`
1750 /// implementation for free.
1751 ///
1752 /// [`Display`]: ../../std/fmt/trait.Display.html
1753 #[stable(feature = "rust1", since = "1.0.0")]
1754 pub trait ToString {
1755     /// Converts the given value to a `String`.
1756     ///
1757     /// # Examples
1758     ///
1759     /// Basic usage:
1760     ///
1761     /// ```
1762     /// let i = 5;
1763     /// let five = String::from("5");
1764     ///
1765     /// assert_eq!(five, i.to_string());
1766     /// ```
1767     #[stable(feature = "rust1", since = "1.0.0")]
1768     fn to_string(&self) -> String;
1769 }
1770
1771 #[stable(feature = "rust1", since = "1.0.0")]
1772 impl<T: fmt::Display + ?Sized> ToString for T {
1773     #[inline]
1774     fn to_string(&self) -> String {
1775         use core::fmt::Write;
1776         let mut buf = String::new();
1777         let _ = buf.write_fmt(format_args!("{}", self));
1778         buf.shrink_to_fit();
1779         buf
1780     }
1781 }
1782
1783 #[stable(feature = "rust1", since = "1.0.0")]
1784 impl AsRef<str> for String {
1785     #[inline]
1786     fn as_ref(&self) -> &str {
1787         self
1788     }
1789 }
1790
1791 #[stable(feature = "rust1", since = "1.0.0")]
1792 impl AsRef<[u8]> for String {
1793     #[inline]
1794     fn as_ref(&self) -> &[u8] {
1795         self.as_bytes()
1796     }
1797 }
1798
1799 #[stable(feature = "rust1", since = "1.0.0")]
1800 impl<'a> From<&'a str> for String {
1801     #[cfg(not(test))]
1802     #[inline]
1803     fn from(s: &'a str) -> String {
1804         String { vec: <[_]>::to_vec(s.as_bytes()) }
1805     }
1806
1807     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1808     // required for this method definition, is not available. Since we don't
1809     // require this method for testing purposes, I'll just stub it
1810     // NB see the slice::hack module in slice.rs for more information
1811     #[inline]
1812     #[cfg(test)]
1813     fn from(_: &str) -> String {
1814         panic!("not available with cfg(test)");
1815     }
1816 }
1817
1818 #[stable(feature = "rust1", since = "1.0.0")]
1819 impl<'a> From<&'a str> for Cow<'a, str> {
1820     #[inline]
1821     fn from(s: &'a str) -> Cow<'a, str> {
1822         Cow::Borrowed(s)
1823     }
1824 }
1825
1826 #[stable(feature = "rust1", since = "1.0.0")]
1827 impl<'a> From<String> for Cow<'a, str> {
1828     #[inline]
1829     fn from(s: String) -> Cow<'a, str> {
1830         Cow::Owned(s)
1831     }
1832 }
1833
1834 #[stable(feature = "rust1", since = "1.0.0")]
1835 impl Into<Vec<u8>> for String {
1836     fn into(self) -> Vec<u8> {
1837         self.into_bytes()
1838     }
1839 }
1840
1841 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1842            issue= "27735")]
1843 #[allow(deprecated)]
1844 impl IntoCow<'static, str> for String {
1845     #[inline]
1846     fn into_cow(self) -> Cow<'static, str> {
1847         Cow::Owned(self)
1848     }
1849 }
1850
1851 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1852            issue = "27735")]
1853 #[allow(deprecated)]
1854 impl<'a> IntoCow<'a, str> for &'a str {
1855     #[inline]
1856     fn into_cow(self) -> Cow<'a, str> {
1857         Cow::Borrowed(self)
1858     }
1859 }
1860
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 impl fmt::Write for String {
1863     #[inline]
1864     fn write_str(&mut self, s: &str) -> fmt::Result {
1865         self.push_str(s);
1866         Ok(())
1867     }
1868
1869     #[inline]
1870     fn write_char(&mut self, c: char) -> fmt::Result {
1871         self.push(c);
1872         Ok(())
1873     }
1874 }
1875
1876 /// A draining iterator for `String`.
1877 ///
1878 /// This struct is created by the [`drain()`] method on [`String`]. See its
1879 /// documentation for more.
1880 ///
1881 /// [`drain()`]: struct.String.html#method.drain
1882 /// [`String`]: struct.String.html
1883 #[stable(feature = "drain", since = "1.6.0")]
1884 pub struct Drain<'a> {
1885     /// Will be used as &'a mut String in the destructor
1886     string: *mut String,
1887     /// Start of part to remove
1888     start: usize,
1889     /// End of part to remove
1890     end: usize,
1891     /// Current remaining range to remove
1892     iter: Chars<'a>,
1893 }
1894
1895 #[stable(feature = "drain", since = "1.6.0")]
1896 unsafe impl<'a> Sync for Drain<'a> {}
1897 #[stable(feature = "drain", since = "1.6.0")]
1898 unsafe impl<'a> Send for Drain<'a> {}
1899
1900 #[stable(feature = "drain", since = "1.6.0")]
1901 impl<'a> Drop for Drain<'a> {
1902     fn drop(&mut self) {
1903         unsafe {
1904             // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1905             // panic code being inserted again.
1906             let self_vec = (*self.string).as_mut_vec();
1907             if self.start <= self.end && self.end <= self_vec.len() {
1908                 self_vec.drain(self.start..self.end);
1909             }
1910         }
1911     }
1912 }
1913
1914 #[stable(feature = "drain", since = "1.6.0")]
1915 impl<'a> Iterator for Drain<'a> {
1916     type Item = char;
1917
1918     #[inline]
1919     fn next(&mut self) -> Option<char> {
1920         self.iter.next()
1921     }
1922
1923     fn size_hint(&self) -> (usize, Option<usize>) {
1924         self.iter.size_hint()
1925     }
1926 }
1927
1928 #[stable(feature = "drain", since = "1.6.0")]
1929 impl<'a> DoubleEndedIterator for Drain<'a> {
1930     #[inline]
1931     fn next_back(&mut self) -> Option<char> {
1932         self.iter.next_back()
1933     }
1934 }