]> git.lizzy.rs Git - rust.git/blob - src/libcollections/string.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[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 //! [`ToString`]: trait.ToString.html
18 //!
19 //! # Examples
20 //!
21 //! There are multiple ways to create a new [`String`] from a string literal:
22 //!
23 //! ```
24 //! let s = "Hello".to_string();
25 //!
26 //! let s = String::from("world");
27 //! let s: String = "also this".into();
28 //! ```
29 //!
30 //! You can create a new [`String`] from an existing one by concatenating with
31 //! `+`:
32 //!
33 //! [`String`]: struct.String.html
34 //!
35 //! ```
36 //! let s = "Hello".to_string();
37 //!
38 //! let message = s + " world!";
39 //! ```
40 //!
41 //! If you have a vector of valid UTF-8 bytes, you can make a `String` out of
42 //! it. You can do the reverse too.
43 //!
44 //! ```
45 //! let sparkle_heart = vec![240, 159, 146, 150];
46 //!
47 //! // We know these bytes are valid, so we'll use `unwrap()`.
48 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
49 //!
50 //! assert_eq!("💖", sparkle_heart);
51 //!
52 //! let bytes = sparkle_heart.into_bytes();
53 //!
54 //! assert_eq!(bytes, [240, 159, 146, 150]);
55 //! ```
56
57 #![stable(feature = "rust1", since = "1.0.0")]
58
59 use core::fmt;
60 use core::hash;
61 use core::iter::{FromIterator, FusedIterator};
62 use core::mem;
63 use core::ops::{self, Add, AddAssign, Index, IndexMut};
64 use core::ptr;
65 use core::str as core_str;
66 use core::str::pattern::Pattern;
67 use std_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
68
69 use borrow::{Cow, ToOwned};
70 use range::RangeArgument;
71 use Bound::{Excluded, Included, Unbounded};
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. Furthermore, it's not clear what sort of
138 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
139 /// The [`bytes`] and [`chars`] methods return iterators over the first
140 /// two, respectively.
141 ///
142 /// [`bytes`]: #method.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 nineteen 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     /// The inverse of this method is [`as_bytes`].
437     ///
438     /// [`as_bytes`]: #method.as_bytes
439     ///
440     /// # Errors
441     ///
442     /// Returns `Err` if the slice is not UTF-8 with a description as to why the
443     /// provided bytes are not UTF-8. The vector you moved in is also included.
444     ///
445     /// # Examples
446     ///
447     /// Basic usage:
448     ///
449     /// ```
450     /// // some bytes, in a vector
451     /// let sparkle_heart = vec![240, 159, 146, 150];
452     ///
453     /// // We know these bytes are valid, so we'll use `unwrap()`.
454     /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
455     ///
456     /// assert_eq!("💖", sparkle_heart);
457     /// ```
458     ///
459     /// Incorrect bytes:
460     ///
461     /// ```
462     /// // some invalid bytes, in a vector
463     /// let sparkle_heart = vec![0, 159, 146, 150];
464     ///
465     /// assert!(String::from_utf8(sparkle_heart).is_err());
466     /// ```
467     ///
468     /// See the docs for [`FromUtf8Error`] for more details on what you can do
469     /// with this error.
470     ///
471     /// [`FromUtf8Error`]: struct.FromUtf8Error.html
472     #[inline]
473     #[stable(feature = "rust1", since = "1.0.0")]
474     pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
475         match str::from_utf8(&vec) {
476             Ok(..) => Ok(String { vec: vec }),
477             Err(e) => {
478                 Err(FromUtf8Error {
479                     bytes: vec,
480                     error: e,
481                 })
482             }
483         }
484     }
485
486     /// Converts a slice of bytes to a string, including invalid characters.
487     ///
488     /// Strings are made of bytes ([`u8`]), and a slice of bytes
489     /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
490     /// between the two. Not all byte slices are valid strings, however: strings
491     /// are required to be valid UTF-8. During this conversion,
492     /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
493     /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
494     ///
495     /// [`u8`]: ../../std/primitive.u8.html
496     /// [byteslice]: ../../std/primitive.slice.html
497     ///
498     /// If you are sure that the byte slice is valid UTF-8, and you don't want
499     /// to incur the overhead of the conversion, there is an unsafe version
500     /// of this function, [`from_utf8_unchecked`], which has the same behavior
501     /// but skips the checks.
502     ///
503     /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
504     ///
505     /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
506     /// UTF-8, then we need to insert the replacement characters, which will
507     /// change the size of the string, and hence, require a `String`. But if
508     /// it's already valid UTF-8, we don't need a new allocation. This return
509     /// type allows us to handle both cases.
510     ///
511     /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
512     ///
513     /// # Examples
514     ///
515     /// Basic usage:
516     ///
517     /// ```
518     /// // some bytes, in a vector
519     /// let sparkle_heart = vec![240, 159, 146, 150];
520     ///
521     /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
522     ///
523     /// assert_eq!("💖", sparkle_heart);
524     /// ```
525     ///
526     /// Incorrect bytes:
527     ///
528     /// ```
529     /// // some invalid bytes
530     /// let input = b"Hello \xF0\x90\x80World";
531     /// let output = String::from_utf8_lossy(input);
532     ///
533     /// assert_eq!("Hello �World", output);
534     /// ```
535     #[stable(feature = "rust1", since = "1.0.0")]
536     pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
537         let mut i;
538         match str::from_utf8(v) {
539             Ok(s) => return Cow::Borrowed(s),
540             Err(e) => i = e.valid_up_to(),
541         }
542
543         const TAG_CONT_U8: u8 = 128;
544         const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
545         let total = v.len();
546         fn unsafe_get(xs: &[u8], i: usize) -> u8 {
547             unsafe { *xs.get_unchecked(i) }
548         }
549         fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
550             if i >= total { 0 } else { unsafe_get(xs, i) }
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 = core_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     /// The ownership of `ptr` is effectively transferred to the
707     /// `String` which may then deallocate, reallocate or change the
708     /// contents of memory pointed to by the pointer at will. Ensure
709     /// that nothing else uses the pointer after calling this
710     /// function.
711     ///
712     /// # Examples
713     ///
714     /// Basic usage:
715     ///
716     /// ```
717     /// use std::mem;
718     ///
719     /// unsafe {
720     ///     let s = String::from("hello");
721     ///     let ptr = s.as_ptr();
722     ///     let len = s.len();
723     ///     let capacity = s.capacity();
724     ///
725     ///     mem::forget(s);
726     ///
727     ///     let s = String::from_raw_parts(ptr as *mut _, len, capacity);
728     ///
729     ///     assert_eq!(String::from("hello"), s);
730     /// }
731     /// ```
732     #[inline]
733     #[stable(feature = "rust1", since = "1.0.0")]
734     pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
735         String { vec: Vec::from_raw_parts(buf, length, capacity) }
736     }
737
738     /// Converts a vector of bytes to a `String` without checking that the
739     /// string contains valid UTF-8.
740     ///
741     /// See the safe version, [`from_utf8`], for more details.
742     ///
743     /// [`from_utf8`]: struct.String.html#method.from_utf8
744     ///
745     /// # Safety
746     ///
747     /// This function is unsafe because it does not check that the bytes passed
748     /// to it are valid UTF-8. If this constraint is violated, it may cause
749     /// memory unsafety issues with future users of the `String`, as the rest of
750     /// the standard library assumes that `String`s are valid UTF-8.
751     ///
752     /// # Examples
753     ///
754     /// Basic usage:
755     ///
756     /// ```
757     /// // some bytes, in a vector
758     /// let sparkle_heart = vec![240, 159, 146, 150];
759     ///
760     /// let sparkle_heart = unsafe {
761     ///     String::from_utf8_unchecked(sparkle_heart)
762     /// };
763     ///
764     /// assert_eq!("💖", sparkle_heart);
765     /// ```
766     #[inline]
767     #[stable(feature = "rust1", since = "1.0.0")]
768     pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
769         String { vec: bytes }
770     }
771
772     /// Converts a `String` into a byte vector.
773     ///
774     /// This consumes the `String`, so we do not need to copy its contents.
775     ///
776     /// # Examples
777     ///
778     /// Basic usage:
779     ///
780     /// ```
781     /// let s = String::from("hello");
782     /// let bytes = s.into_bytes();
783     ///
784     /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
785     /// ```
786     #[inline]
787     #[stable(feature = "rust1", since = "1.0.0")]
788     pub fn into_bytes(self) -> Vec<u8> {
789         self.vec
790     }
791
792     /// Extracts a string slice containing the entire string.
793     #[inline]
794     #[stable(feature = "string_as_str", since = "1.7.0")]
795     pub fn as_str(&self) -> &str {
796         self
797     }
798
799     /// Extracts a string slice containing the entire string.
800     #[inline]
801     #[stable(feature = "string_as_str", since = "1.7.0")]
802     pub fn as_mut_str(&mut self) -> &mut str {
803         self
804     }
805
806     /// Appends a given string slice onto the end of this `String`.
807     ///
808     /// # Examples
809     ///
810     /// Basic usage:
811     ///
812     /// ```
813     /// let mut s = String::from("foo");
814     ///
815     /// s.push_str("bar");
816     ///
817     /// assert_eq!("foobar", s);
818     /// ```
819     #[inline]
820     #[stable(feature = "rust1", since = "1.0.0")]
821     pub fn push_str(&mut self, string: &str) {
822         self.vec.extend_from_slice(string.as_bytes())
823     }
824
825     /// Returns this `String`'s capacity, in bytes.
826     ///
827     /// # Examples
828     ///
829     /// Basic usage:
830     ///
831     /// ```
832     /// let s = String::with_capacity(10);
833     ///
834     /// assert!(s.capacity() >= 10);
835     /// ```
836     #[inline]
837     #[stable(feature = "rust1", since = "1.0.0")]
838     pub fn capacity(&self) -> usize {
839         self.vec.capacity()
840     }
841
842     /// Ensures that this `String`'s capacity is at least `additional` bytes
843     /// larger than its length.
844     ///
845     /// The capacity may be increased by more than `additional` bytes if it
846     /// chooses, to prevent frequent reallocations.
847     ///
848     /// If you do not want this "at least" behavior, see the [`reserve_exact`]
849     /// method.
850     ///
851     /// [`reserve_exact`]: #method.reserve_exact
852     ///
853     /// # Panics
854     ///
855     /// Panics if the new capacity overflows `usize`.
856     ///
857     /// # Examples
858     ///
859     /// Basic usage:
860     ///
861     /// ```
862     /// let mut s = String::new();
863     ///
864     /// s.reserve(10);
865     ///
866     /// assert!(s.capacity() >= 10);
867     /// ```
868     ///
869     /// This may not actually increase the capacity:
870     ///
871     /// ```
872     /// let mut s = String::with_capacity(10);
873     /// s.push('a');
874     /// s.push('b');
875     ///
876     /// // s now has a length of 2 and a capacity of 10
877     /// assert_eq!(2, s.len());
878     /// assert_eq!(10, s.capacity());
879     ///
880     /// // Since we already have an extra 8 capacity, calling this...
881     /// s.reserve(8);
882     ///
883     /// // ... doesn't actually increase.
884     /// assert_eq!(10, s.capacity());
885     /// ```
886     #[inline]
887     #[stable(feature = "rust1", since = "1.0.0")]
888     pub fn reserve(&mut self, additional: usize) {
889         self.vec.reserve(additional)
890     }
891
892     /// Ensures that this `String`'s capacity is `additional` bytes
893     /// larger than its length.
894     ///
895     /// Consider using the [`reserve`] method unless you absolutely know
896     /// better than the allocator.
897     ///
898     /// [`reserve`]: #method.reserve
899     ///
900     /// # Panics
901     ///
902     /// Panics if the new capacity overflows `usize`.
903     ///
904     /// # Examples
905     ///
906     /// Basic usage:
907     ///
908     /// ```
909     /// let mut s = String::new();
910     ///
911     /// s.reserve_exact(10);
912     ///
913     /// assert!(s.capacity() >= 10);
914     /// ```
915     ///
916     /// This may not actually increase the capacity:
917     ///
918     /// ```
919     /// let mut s = String::with_capacity(10);
920     /// s.push('a');
921     /// s.push('b');
922     ///
923     /// // s now has a length of 2 and a capacity of 10
924     /// assert_eq!(2, s.len());
925     /// assert_eq!(10, s.capacity());
926     ///
927     /// // Since we already have an extra 8 capacity, calling this...
928     /// s.reserve_exact(8);
929     ///
930     /// // ... doesn't actually increase.
931     /// assert_eq!(10, s.capacity());
932     /// ```
933     #[inline]
934     #[stable(feature = "rust1", since = "1.0.0")]
935     pub fn reserve_exact(&mut self, additional: usize) {
936         self.vec.reserve_exact(additional)
937     }
938
939     /// Shrinks the capacity of this `String` to match its length.
940     ///
941     /// # Examples
942     ///
943     /// Basic usage:
944     ///
945     /// ```
946     /// let mut s = String::from("foo");
947     ///
948     /// s.reserve(100);
949     /// assert!(s.capacity() >= 100);
950     ///
951     /// s.shrink_to_fit();
952     /// assert_eq!(3, s.capacity());
953     /// ```
954     #[inline]
955     #[stable(feature = "rust1", since = "1.0.0")]
956     pub fn shrink_to_fit(&mut self) {
957         self.vec.shrink_to_fit()
958     }
959
960     /// Appends the given `char` to the end of this `String`.
961     ///
962     /// # Examples
963     ///
964     /// Basic usage:
965     ///
966     /// ```
967     /// let mut s = String::from("abc");
968     ///
969     /// s.push('1');
970     /// s.push('2');
971     /// s.push('3');
972     ///
973     /// assert_eq!("abc123", s);
974     /// ```
975     #[inline]
976     #[stable(feature = "rust1", since = "1.0.0")]
977     pub fn push(&mut self, ch: char) {
978         match ch.len_utf8() {
979             1 => self.vec.push(ch as u8),
980             _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
981         }
982     }
983
984     /// Returns a byte slice of this `String`'s contents.
985     ///
986     /// The inverse of this method is [`from_utf8`].
987     ///
988     /// [`from_utf8`]: #method.from_utf8
989     ///
990     /// # Examples
991     ///
992     /// Basic usage:
993     ///
994     /// ```
995     /// let s = String::from("hello");
996     ///
997     /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
998     /// ```
999     #[inline]
1000     #[stable(feature = "rust1", since = "1.0.0")]
1001     pub fn as_bytes(&self) -> &[u8] {
1002         &self.vec
1003     }
1004
1005     /// Shortens this `String` to the specified length.
1006     ///
1007     /// If `new_len` is greater than the string's current length, this has no
1008     /// effect.
1009     ///
1010     /// Note that this method has no effect on the allocated capacity
1011     /// of the string
1012     ///
1013     /// # Panics
1014     ///
1015     /// Panics if `new_len` does not lie on a [`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         if new_len <= self.len() {
1034             assert!(self.is_char_boundary(new_len));
1035             self.vec.truncate(new_len)
1036         }
1037     }
1038
1039     /// Removes the last character from the string buffer and returns it.
1040     ///
1041     /// Returns `None` if this `String` is empty.
1042     ///
1043     /// # Examples
1044     ///
1045     /// Basic usage:
1046     ///
1047     /// ```
1048     /// let mut s = String::from("foo");
1049     ///
1050     /// assert_eq!(s.pop(), Some('o'));
1051     /// assert_eq!(s.pop(), Some('o'));
1052     /// assert_eq!(s.pop(), Some('f'));
1053     ///
1054     /// assert_eq!(s.pop(), None);
1055     /// ```
1056     #[inline]
1057     #[stable(feature = "rust1", since = "1.0.0")]
1058     pub fn pop(&mut self) -> Option<char> {
1059         let ch = match self.chars().rev().next() {
1060             Some(ch) => ch,
1061             None => return None,
1062         };
1063         let newlen = self.len() - ch.len_utf8();
1064         unsafe {
1065             self.vec.set_len(newlen);
1066         }
1067         Some(ch)
1068     }
1069
1070     /// Removes a `char` from this `String` at a byte position and returns it.
1071     ///
1072     /// This is an `O(n)` operation, as it requires copying every element in the
1073     /// buffer.
1074     ///
1075     /// # Panics
1076     ///
1077     /// Panics if `idx` is larger than or equal to the `String`'s length,
1078     /// or if it does not lie on a [`char`] boundary.
1079     ///
1080     /// [`char`]: ../../std/primitive.char.html
1081     ///
1082     /// # Examples
1083     ///
1084     /// Basic usage:
1085     ///
1086     /// ```
1087     /// let mut s = String::from("foo");
1088     ///
1089     /// assert_eq!(s.remove(0), 'f');
1090     /// assert_eq!(s.remove(1), 'o');
1091     /// assert_eq!(s.remove(0), 'o');
1092     /// ```
1093     #[inline]
1094     #[stable(feature = "rust1", since = "1.0.0")]
1095     pub fn remove(&mut self, idx: usize) -> char {
1096         let ch = match self[idx..].chars().next() {
1097             Some(ch) => ch,
1098             None => panic!("cannot remove a char from the end of a string"),
1099         };
1100
1101         let next = idx + ch.len_utf8();
1102         let len = self.len();
1103         unsafe {
1104             ptr::copy(self.vec.as_ptr().offset(next as isize),
1105                       self.vec.as_mut_ptr().offset(idx as isize),
1106                       len - next);
1107             self.vec.set_len(len - (next - idx));
1108         }
1109         ch
1110     }
1111
1112     /// Inserts a character into this `String` at a byte position.
1113     ///
1114     /// This is an `O(n)` operation as it requires copying every element in the
1115     /// buffer.
1116     ///
1117     /// # Panics
1118     ///
1119     /// Panics if `idx` is larger than the `String`'s length, or if it does not
1120     /// lie on a [`char`] boundary.
1121     ///
1122     /// [`char`]: ../../std/primitive.char.html
1123     ///
1124     /// # Examples
1125     ///
1126     /// Basic usage:
1127     ///
1128     /// ```
1129     /// let mut s = String::with_capacity(3);
1130     ///
1131     /// s.insert(0, 'f');
1132     /// s.insert(1, 'o');
1133     /// s.insert(2, 'o');
1134     ///
1135     /// assert_eq!("foo", s);
1136     /// ```
1137     #[inline]
1138     #[stable(feature = "rust1", since = "1.0.0")]
1139     pub fn insert(&mut self, idx: usize, ch: char) {
1140         assert!(self.is_char_boundary(idx));
1141         let mut bits = [0; 4];
1142         let bits = ch.encode_utf8(&mut bits).as_bytes();
1143
1144         unsafe {
1145             self.insert_bytes(idx, bits);
1146         }
1147     }
1148
1149     unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1150         let len = self.len();
1151         let amt = bytes.len();
1152         self.vec.reserve(amt);
1153
1154         ptr::copy(self.vec.as_ptr().offset(idx as isize),
1155                   self.vec.as_mut_ptr().offset((idx + amt) as isize),
1156                   len - idx);
1157         ptr::copy(bytes.as_ptr(),
1158                   self.vec.as_mut_ptr().offset(idx as isize),
1159                   amt);
1160         self.vec.set_len(len + amt);
1161     }
1162
1163     /// Inserts a string slice into this `String` at a byte position.
1164     ///
1165     /// This is an `O(n)` operation as it requires copying every element in the
1166     /// buffer.
1167     ///
1168     /// # Panics
1169     ///
1170     /// Panics if `idx` is larger than the `String`'s length, or if it does not
1171     /// lie on a [`char`] boundary.
1172     ///
1173     /// [`char`]: ../../std/primitive.char.html
1174     ///
1175     /// # Examples
1176     ///
1177     /// Basic usage:
1178     ///
1179     /// ```
1180     /// let mut s = String::from("bar");
1181     ///
1182     /// s.insert_str(0, "foo");
1183     ///
1184     /// assert_eq!("foobar", s);
1185     /// ```
1186     #[inline]
1187     #[stable(feature = "insert_str", since = "1.16.0")]
1188     pub fn insert_str(&mut self, idx: usize, string: &str) {
1189         assert!(self.is_char_boundary(idx));
1190
1191         unsafe {
1192             self.insert_bytes(idx, string.as_bytes());
1193         }
1194     }
1195
1196     /// Returns a mutable reference to the contents of this `String`.
1197     ///
1198     /// # Safety
1199     ///
1200     /// This function is unsafe because it does not check that the bytes passed
1201     /// to it are valid UTF-8. If this constraint is violated, it may cause
1202     /// memory unsafety issues with future users of the `String`, as the rest of
1203     /// the standard library assumes that `String`s are valid UTF-8.
1204     ///
1205     /// # Examples
1206     ///
1207     /// Basic usage:
1208     ///
1209     /// ```
1210     /// let mut s = String::from("hello");
1211     ///
1212     /// unsafe {
1213     ///     let vec = s.as_mut_vec();
1214     ///     assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1215     ///
1216     ///     vec.reverse();
1217     /// }
1218     /// assert_eq!(s, "olleh");
1219     /// ```
1220     #[inline]
1221     #[stable(feature = "rust1", since = "1.0.0")]
1222     pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1223         &mut self.vec
1224     }
1225
1226     /// Returns the length of this `String`, in bytes.
1227     ///
1228     /// # Examples
1229     ///
1230     /// Basic usage:
1231     ///
1232     /// ```
1233     /// let a = String::from("foo");
1234     ///
1235     /// assert_eq!(a.len(), 3);
1236     /// ```
1237     #[inline]
1238     #[stable(feature = "rust1", since = "1.0.0")]
1239     pub fn len(&self) -> usize {
1240         self.vec.len()
1241     }
1242
1243     /// Returns `true` if this `String` has a length of zero.
1244     ///
1245     /// Returns `false` otherwise.
1246     ///
1247     /// # Examples
1248     ///
1249     /// Basic usage:
1250     ///
1251     /// ```
1252     /// let mut v = String::new();
1253     /// assert!(v.is_empty());
1254     ///
1255     /// v.push('a');
1256     /// assert!(!v.is_empty());
1257     /// ```
1258     #[inline]
1259     #[stable(feature = "rust1", since = "1.0.0")]
1260     pub fn is_empty(&self) -> bool {
1261         self.len() == 0
1262     }
1263
1264     /// Splits the string into two at the given index.
1265     ///
1266     /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1267     /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1268     /// boundary of a UTF-8 code point.
1269     ///
1270     /// Note that the capacity of `self` does not change.
1271     ///
1272     /// # Panics
1273     ///
1274     /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1275     /// code point of the string.
1276     ///
1277     /// # Examples
1278     ///
1279     /// ```
1280     /// # fn main() {
1281     /// let mut hello = String::from("Hello, World!");
1282     /// let world = hello.split_off(7);
1283     /// assert_eq!(hello, "Hello, ");
1284     /// assert_eq!(world, "World!");
1285     /// # }
1286     /// ```
1287     #[inline]
1288     #[stable(feature = "string_split_off", since = "1.16.0")]
1289     pub fn split_off(&mut self, at: usize) -> String {
1290         assert!(self.is_char_boundary(at));
1291         let other = self.vec.split_off(at);
1292         unsafe { String::from_utf8_unchecked(other) }
1293     }
1294
1295     /// Truncates this `String`, removing all contents.
1296     ///
1297     /// While this means the `String` will have a length of zero, it does not
1298     /// touch its capacity.
1299     ///
1300     /// # Examples
1301     ///
1302     /// Basic usage:
1303     ///
1304     /// ```
1305     /// let mut s = String::from("foo");
1306     ///
1307     /// s.clear();
1308     ///
1309     /// assert!(s.is_empty());
1310     /// assert_eq!(0, s.len());
1311     /// assert_eq!(3, s.capacity());
1312     /// ```
1313     #[inline]
1314     #[stable(feature = "rust1", since = "1.0.0")]
1315     pub fn clear(&mut self) {
1316         self.vec.clear()
1317     }
1318
1319     /// Create a draining iterator that removes the specified range in the string
1320     /// and yields the removed chars.
1321     ///
1322     /// Note: The element range is removed even if the iterator is not
1323     /// consumed until the end.
1324     ///
1325     /// # Panics
1326     ///
1327     /// Panics if the starting point or end point do not lie on a [`char`]
1328     /// boundary, or if they're out of bounds.
1329     ///
1330     /// [`char`]: ../../std/primitive.char.html
1331     ///
1332     /// # Examples
1333     ///
1334     /// Basic usage:
1335     ///
1336     /// ```
1337     /// let mut s = String::from("α is alpha, β is beta");
1338     /// let beta_offset = s.find('β').unwrap_or(s.len());
1339     ///
1340     /// // Remove the range up until the β from the string
1341     /// let t: String = s.drain(..beta_offset).collect();
1342     /// assert_eq!(t, "α is alpha, ");
1343     /// assert_eq!(s, "β is beta");
1344     ///
1345     /// // A full range clears the string
1346     /// s.drain(..);
1347     /// assert_eq!(s, "");
1348     /// ```
1349     #[stable(feature = "drain", since = "1.6.0")]
1350     pub fn drain<R>(&mut self, range: R) -> Drain
1351         where R: RangeArgument<usize>
1352     {
1353         // Memory safety
1354         //
1355         // The String version of Drain does not have the memory safety issues
1356         // of the vector version. The data is just plain bytes.
1357         // Because the range removal happens in Drop, if the Drain iterator is leaked,
1358         // the removal will not happen.
1359         let len = self.len();
1360         let start = match range.start() {
1361             Included(&n) => n,
1362             Excluded(&n) => n + 1,
1363             Unbounded => 0,
1364         };
1365         let end = match range.end() {
1366             Included(&n) => n + 1,
1367             Excluded(&n) => n,
1368             Unbounded => len,
1369         };
1370
1371         // Take out two simultaneous borrows. The &mut String won't be accessed
1372         // until iteration is over, in Drop.
1373         let self_ptr = self as *mut _;
1374         // slicing does the appropriate bounds checks
1375         let chars_iter = self[start..end].chars();
1376
1377         Drain {
1378             start: start,
1379             end: end,
1380             iter: chars_iter,
1381             string: self_ptr,
1382         }
1383     }
1384
1385     /// Converts this `String` into a `Box<str>`.
1386     ///
1387     /// This will drop any excess capacity.
1388     ///
1389     /// # Examples
1390     ///
1391     /// Basic usage:
1392     ///
1393     /// ```
1394     /// let s = String::from("hello");
1395     ///
1396     /// let b = s.into_boxed_str();
1397     /// ```
1398     #[stable(feature = "box_str", since = "1.4.0")]
1399     pub fn into_boxed_str(self) -> Box<str> {
1400         let slice = self.vec.into_boxed_slice();
1401         unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
1402     }
1403 }
1404
1405 impl FromUtf8Error {
1406     /// Returns the bytes that were attempted to convert to a `String`.
1407     ///
1408     /// This method is carefully constructed to avoid allocation. It will
1409     /// consume the error, moving out the bytes, so that a copy of the bytes
1410     /// does not need to be made.
1411     ///
1412     /// # Examples
1413     ///
1414     /// Basic usage:
1415     ///
1416     /// ```
1417     /// // some invalid bytes, in a vector
1418     /// let bytes = vec![0, 159];
1419     ///
1420     /// let value = String::from_utf8(bytes);
1421     ///
1422     /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1423     /// ```
1424     #[stable(feature = "rust1", since = "1.0.0")]
1425     pub fn into_bytes(self) -> Vec<u8> {
1426         self.bytes
1427     }
1428
1429     /// Fetch a `Utf8Error` to get more details about the conversion failure.
1430     ///
1431     /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1432     /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1433     /// an analogue to `FromUtf8Error`. See its documentation for more details
1434     /// on using it.
1435     ///
1436     /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1437     /// [`std::str`]: ../../std/str/index.html
1438     /// [`u8`]: ../../std/primitive.u8.html
1439     /// [`&str`]: ../../std/primitive.str.html
1440     ///
1441     /// # Examples
1442     ///
1443     /// Basic usage:
1444     ///
1445     /// ```
1446     /// // some invalid bytes, in a vector
1447     /// let bytes = vec![0, 159];
1448     ///
1449     /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1450     ///
1451     /// // the first byte is invalid here
1452     /// assert_eq!(1, error.valid_up_to());
1453     /// ```
1454     #[stable(feature = "rust1", since = "1.0.0")]
1455     pub fn utf8_error(&self) -> Utf8Error {
1456         self.error
1457     }
1458 }
1459
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 impl fmt::Display for FromUtf8Error {
1462     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1463         fmt::Display::fmt(&self.error, f)
1464     }
1465 }
1466
1467 #[stable(feature = "rust1", since = "1.0.0")]
1468 impl fmt::Display for FromUtf16Error {
1469     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1470         fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1471     }
1472 }
1473
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 impl Clone for String {
1476     fn clone(&self) -> Self {
1477         String { vec: self.vec.clone() }
1478     }
1479
1480     fn clone_from(&mut self, source: &Self) {
1481         self.vec.clone_from(&source.vec);
1482     }
1483 }
1484
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl FromIterator<char> for String {
1487     fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1488         let mut buf = String::new();
1489         buf.extend(iter);
1490         buf
1491     }
1492 }
1493
1494 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1495 impl<'a> FromIterator<&'a char> for String {
1496     fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1497         let mut buf = String::new();
1498         buf.extend(iter);
1499         buf
1500     }
1501 }
1502
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl<'a> FromIterator<&'a str> for String {
1505     fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1506         let mut buf = String::new();
1507         buf.extend(iter);
1508         buf
1509     }
1510 }
1511
1512 #[stable(feature = "extend_string", since = "1.4.0")]
1513 impl FromIterator<String> for String {
1514     fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1515         let mut buf = String::new();
1516         buf.extend(iter);
1517         buf
1518     }
1519 }
1520
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 impl Extend<char> for String {
1523     fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1524         let iterator = iter.into_iter();
1525         let (lower_bound, _) = iterator.size_hint();
1526         self.reserve(lower_bound);
1527         for ch in iterator {
1528             self.push(ch)
1529         }
1530     }
1531 }
1532
1533 #[stable(feature = "extend_ref", since = "1.2.0")]
1534 impl<'a> Extend<&'a char> for String {
1535     fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1536         self.extend(iter.into_iter().cloned());
1537     }
1538 }
1539
1540 #[stable(feature = "rust1", since = "1.0.0")]
1541 impl<'a> Extend<&'a str> for String {
1542     fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1543         for s in iter {
1544             self.push_str(s)
1545         }
1546     }
1547 }
1548
1549 #[stable(feature = "extend_string", since = "1.4.0")]
1550 impl Extend<String> for String {
1551     fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1552         for s in iter {
1553             self.push_str(&s)
1554         }
1555     }
1556 }
1557
1558 /// A convenience impl that delegates to the impl for `&str`
1559 #[unstable(feature = "pattern",
1560            reason = "API not fully fleshed out and ready to be stabilized",
1561            issue = "27721")]
1562 impl<'a, 'b> Pattern<'a> for &'b String {
1563     type Searcher = <&'b str as Pattern<'a>>::Searcher;
1564
1565     fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1566         self[..].into_searcher(haystack)
1567     }
1568
1569     #[inline]
1570     fn is_contained_in(self, haystack: &'a str) -> bool {
1571         self[..].is_contained_in(haystack)
1572     }
1573
1574     #[inline]
1575     fn is_prefix_of(self, haystack: &'a str) -> bool {
1576         self[..].is_prefix_of(haystack)
1577     }
1578 }
1579
1580 #[stable(feature = "rust1", since = "1.0.0")]
1581 impl PartialEq for String {
1582     #[inline]
1583     fn eq(&self, other: &String) -> bool {
1584         PartialEq::eq(&self[..], &other[..])
1585     }
1586     #[inline]
1587     fn ne(&self, other: &String) -> bool {
1588         PartialEq::ne(&self[..], &other[..])
1589     }
1590 }
1591
1592 macro_rules! impl_eq {
1593     ($lhs:ty, $rhs: ty) => {
1594         #[stable(feature = "rust1", since = "1.0.0")]
1595         impl<'a, 'b> PartialEq<$rhs> for $lhs {
1596             #[inline]
1597             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1598             #[inline]
1599             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1600         }
1601
1602         #[stable(feature = "rust1", since = "1.0.0")]
1603         impl<'a, 'b> PartialEq<$lhs> for $rhs {
1604             #[inline]
1605             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1606             #[inline]
1607             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1608         }
1609
1610     }
1611 }
1612
1613 impl_eq! { String, str }
1614 impl_eq! { String, &'a str }
1615 impl_eq! { Cow<'a, str>, str }
1616 impl_eq! { Cow<'a, str>, &'b str }
1617 impl_eq! { Cow<'a, str>, String }
1618
1619 #[stable(feature = "rust1", since = "1.0.0")]
1620 impl Default for String {
1621     /// Creates an empty `String`.
1622     #[inline]
1623     fn default() -> String {
1624         String::new()
1625     }
1626 }
1627
1628 #[stable(feature = "rust1", since = "1.0.0")]
1629 impl fmt::Display for String {
1630     #[inline]
1631     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1632         fmt::Display::fmt(&**self, f)
1633     }
1634 }
1635
1636 #[stable(feature = "rust1", since = "1.0.0")]
1637 impl fmt::Debug for String {
1638     #[inline]
1639     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1640         fmt::Debug::fmt(&**self, f)
1641     }
1642 }
1643
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 impl hash::Hash for String {
1646     #[inline]
1647     fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1648         (**self).hash(hasher)
1649     }
1650 }
1651
1652 /// Implements the `+` operator for concatenating two strings.
1653 ///
1654 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1655 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1656 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1657 /// repeated concatenation.
1658 ///
1659 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1660 /// `String`.
1661 ///
1662 /// # Examples
1663 ///
1664 /// Concatenating two `String`s takes the first by value and borrows the second:
1665 ///
1666 /// ```
1667 /// let a = String::from("hello");
1668 /// let b = String::from(" world");
1669 /// let c = a + &b;
1670 /// // `a` is moved and can no longer be used here.
1671 /// ```
1672 ///
1673 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1674 ///
1675 /// ```
1676 /// let a = String::from("hello");
1677 /// let b = String::from(" world");
1678 /// let c = a.clone() + &b;
1679 /// // `a` is still valid here.
1680 /// ```
1681 ///
1682 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1683 ///
1684 /// ```
1685 /// let a = "hello";
1686 /// let b = " world";
1687 /// let c = a.to_string() + b;
1688 /// ```
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 impl<'a> Add<&'a str> for String {
1691     type Output = String;
1692
1693     #[inline]
1694     fn add(mut self, other: &str) -> String {
1695         self.push_str(other);
1696         self
1697     }
1698 }
1699
1700 /// Implements the `+=` operator for appending to a `String`.
1701 ///
1702 /// This has the same behavior as the [`push_str`] method.
1703 ///
1704 /// [`push_str`]: struct.String.html#method.push_str
1705 #[stable(feature = "stringaddassign", since = "1.12.0")]
1706 impl<'a> AddAssign<&'a str> for String {
1707     #[inline]
1708     fn add_assign(&mut self, other: &str) {
1709         self.push_str(other);
1710     }
1711 }
1712
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 impl ops::Index<ops::Range<usize>> for String {
1715     type Output = str;
1716
1717     #[inline]
1718     fn index(&self, index: ops::Range<usize>) -> &str {
1719         &self[..][index]
1720     }
1721 }
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl ops::Index<ops::RangeTo<usize>> for String {
1724     type Output = str;
1725
1726     #[inline]
1727     fn index(&self, index: ops::RangeTo<usize>) -> &str {
1728         &self[..][index]
1729     }
1730 }
1731 #[stable(feature = "rust1", since = "1.0.0")]
1732 impl ops::Index<ops::RangeFrom<usize>> for String {
1733     type Output = str;
1734
1735     #[inline]
1736     fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1737         &self[..][index]
1738     }
1739 }
1740 #[stable(feature = "rust1", since = "1.0.0")]
1741 impl ops::Index<ops::RangeFull> for String {
1742     type Output = str;
1743
1744     #[inline]
1745     fn index(&self, _index: ops::RangeFull) -> &str {
1746         unsafe { str::from_utf8_unchecked(&self.vec) }
1747     }
1748 }
1749 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1750 impl ops::Index<ops::RangeInclusive<usize>> for String {
1751     type Output = str;
1752
1753     #[inline]
1754     fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1755         Index::index(&**self, index)
1756     }
1757 }
1758 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1759 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1760     type Output = str;
1761
1762     #[inline]
1763     fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1764         Index::index(&**self, index)
1765     }
1766 }
1767
1768 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1769 impl ops::IndexMut<ops::Range<usize>> for String {
1770     #[inline]
1771     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1772         &mut self[..][index]
1773     }
1774 }
1775 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1776 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1777     #[inline]
1778     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1779         &mut self[..][index]
1780     }
1781 }
1782 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1783 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1784     #[inline]
1785     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1786         &mut self[..][index]
1787     }
1788 }
1789 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1790 impl ops::IndexMut<ops::RangeFull> for String {
1791     #[inline]
1792     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1793         unsafe { mem::transmute(&mut *self.vec) }
1794     }
1795 }
1796 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1797 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
1798     #[inline]
1799     fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1800         IndexMut::index_mut(&mut **self, index)
1801     }
1802 }
1803 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1804 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
1805     #[inline]
1806     fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1807         IndexMut::index_mut(&mut **self, index)
1808     }
1809 }
1810
1811 #[stable(feature = "rust1", since = "1.0.0")]
1812 impl ops::Deref for String {
1813     type Target = str;
1814
1815     #[inline]
1816     fn deref(&self) -> &str {
1817         unsafe { str::from_utf8_unchecked(&self.vec) }
1818     }
1819 }
1820
1821 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1822 impl ops::DerefMut for String {
1823     #[inline]
1824     fn deref_mut(&mut self) -> &mut str {
1825         unsafe { mem::transmute(&mut *self.vec) }
1826     }
1827 }
1828
1829 /// An error when parsing a `String`.
1830 ///
1831 /// This `enum` is slightly awkward: it will never actually exist. This error is
1832 /// part of the type signature of the implementation of [`FromStr`] on
1833 /// [`String`]. The return type of [`from_str`], requires that an error be
1834 /// defined, but, given that a [`String`] can always be made into a new
1835 /// [`String`] without error, this type will never actually be returned. As
1836 /// such, it is only here to satisfy said signature, and is useless otherwise.
1837 ///
1838 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1839 /// [`String`]: struct.String.html
1840 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
1841 #[stable(feature = "str_parse_error", since = "1.5.0")]
1842 #[derive(Copy)]
1843 pub enum ParseError {}
1844
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 impl FromStr for String {
1847     type Err = ParseError;
1848     #[inline]
1849     fn from_str(s: &str) -> Result<String, ParseError> {
1850         Ok(String::from(s))
1851     }
1852 }
1853
1854 #[stable(feature = "str_parse_error", since = "1.5.0")]
1855 impl Clone for ParseError {
1856     fn clone(&self) -> ParseError {
1857         match *self {}
1858     }
1859 }
1860
1861 #[stable(feature = "str_parse_error", since = "1.5.0")]
1862 impl fmt::Debug for ParseError {
1863     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1864         match *self {}
1865     }
1866 }
1867
1868 #[stable(feature = "str_parse_error2", since = "1.8.0")]
1869 impl fmt::Display for ParseError {
1870     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1871         match *self {}
1872     }
1873 }
1874
1875 #[stable(feature = "str_parse_error", since = "1.5.0")]
1876 impl PartialEq for ParseError {
1877     fn eq(&self, _: &ParseError) -> bool {
1878         match *self {}
1879     }
1880 }
1881
1882 #[stable(feature = "str_parse_error", since = "1.5.0")]
1883 impl Eq for ParseError {}
1884
1885 /// A trait for converting a value to a `String`.
1886 ///
1887 /// This trait is automatically implemented for any type which implements the
1888 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1889 /// [`Display`] should be implemented instead, and you get the `ToString`
1890 /// implementation for free.
1891 ///
1892 /// [`Display`]: ../../std/fmt/trait.Display.html
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 pub trait ToString {
1895     /// Converts the given value to a `String`.
1896     ///
1897     /// # Examples
1898     ///
1899     /// Basic usage:
1900     ///
1901     /// ```
1902     /// let i = 5;
1903     /// let five = String::from("5");
1904     ///
1905     /// assert_eq!(five, i.to_string());
1906     /// ```
1907     #[stable(feature = "rust1", since = "1.0.0")]
1908     fn to_string(&self) -> String;
1909 }
1910
1911 /// # Panics
1912 ///
1913 /// In this implementation, the `to_string` method panics
1914 /// if the `Display` implementation returns an error.
1915 /// This indicates an incorrect `Display` implementation
1916 /// since `fmt::Write for String` never returns an error itself.
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 impl<T: fmt::Display + ?Sized> ToString for T {
1919     #[inline]
1920     default fn to_string(&self) -> String {
1921         use core::fmt::Write;
1922         let mut buf = String::new();
1923         buf.write_fmt(format_args!("{}", self))
1924            .expect("a Display implementation return an error unexpectedly");
1925         buf.shrink_to_fit();
1926         buf
1927     }
1928 }
1929
1930 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
1931 impl ToString for str {
1932     #[inline]
1933     fn to_string(&self) -> String {
1934         String::from(self)
1935     }
1936 }
1937
1938 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
1939 impl<'a> ToString for Cow<'a, str> {
1940     #[inline]
1941     fn to_string(&self) -> String {
1942         self[..].to_owned()
1943     }
1944 }
1945
1946 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
1947 impl ToString for String {
1948     #[inline]
1949     fn to_string(&self) -> String {
1950         self.to_owned()
1951     }
1952 }
1953
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 impl AsRef<str> for String {
1956     #[inline]
1957     fn as_ref(&self) -> &str {
1958         self
1959     }
1960 }
1961
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 impl AsRef<[u8]> for String {
1964     #[inline]
1965     fn as_ref(&self) -> &[u8] {
1966         self.as_bytes()
1967     }
1968 }
1969
1970 #[stable(feature = "rust1", since = "1.0.0")]
1971 impl<'a> From<&'a str> for String {
1972     fn from(s: &'a str) -> String {
1973         s.to_owned()
1974     }
1975 }
1976
1977 // note: test pulls in libstd, which causes errors here
1978 #[cfg(not(test))]
1979 #[stable(feature = "string_from_box", since = "1.17.0")]
1980 impl From<Box<str>> for String {
1981     fn from(s: Box<str>) -> String {
1982         s.into_string()
1983     }
1984 }
1985
1986 #[stable(feature = "box_from_str", since = "1.17.0")]
1987 impl Into<Box<str>> for String {
1988     fn into(self) -> Box<str> {
1989         self.into_boxed_str()
1990     }
1991 }
1992
1993 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
1994 impl<'a> From<Cow<'a, str>> for String {
1995     fn from(s: Cow<'a, str>) -> String {
1996         s.into_owned()
1997     }
1998 }
1999
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 impl<'a> From<&'a str> for Cow<'a, str> {
2002     #[inline]
2003     fn from(s: &'a str) -> Cow<'a, str> {
2004         Cow::Borrowed(s)
2005     }
2006 }
2007
2008 #[stable(feature = "rust1", since = "1.0.0")]
2009 impl<'a> From<String> for Cow<'a, str> {
2010     #[inline]
2011     fn from(s: String) -> Cow<'a, str> {
2012         Cow::Owned(s)
2013     }
2014 }
2015
2016 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2017 impl<'a> FromIterator<char> for Cow<'a, str> {
2018     fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2019         Cow::Owned(FromIterator::from_iter(it))
2020     }
2021 }
2022
2023 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2024 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2025     fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2026         Cow::Owned(FromIterator::from_iter(it))
2027     }
2028 }
2029
2030 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2031 impl<'a> FromIterator<String> for Cow<'a, str> {
2032     fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2033         Cow::Owned(FromIterator::from_iter(it))
2034     }
2035 }
2036
2037 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2038 impl From<String> for Vec<u8> {
2039     fn from(string: String) -> Vec<u8> {
2040         string.into_bytes()
2041     }
2042 }
2043
2044 #[stable(feature = "rust1", since = "1.0.0")]
2045 impl fmt::Write for String {
2046     #[inline]
2047     fn write_str(&mut self, s: &str) -> fmt::Result {
2048         self.push_str(s);
2049         Ok(())
2050     }
2051
2052     #[inline]
2053     fn write_char(&mut self, c: char) -> fmt::Result {
2054         self.push(c);
2055         Ok(())
2056     }
2057 }
2058
2059 /// A draining iterator for `String`.
2060 ///
2061 /// This struct is created by the [`drain`] method on [`String`]. See its
2062 /// documentation for more.
2063 ///
2064 /// [`drain`]: struct.String.html#method.drain
2065 /// [`String`]: struct.String.html
2066 #[stable(feature = "drain", since = "1.6.0")]
2067 pub struct Drain<'a> {
2068     /// Will be used as &'a mut String in the destructor
2069     string: *mut String,
2070     /// Start of part to remove
2071     start: usize,
2072     /// End of part to remove
2073     end: usize,
2074     /// Current remaining range to remove
2075     iter: Chars<'a>,
2076 }
2077
2078 #[stable(feature = "collection_debug", since = "1.17.0")]
2079 impl<'a> fmt::Debug for Drain<'a> {
2080     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2081         f.pad("Drain { .. }")
2082     }
2083 }
2084
2085 #[stable(feature = "drain", since = "1.6.0")]
2086 unsafe impl<'a> Sync for Drain<'a> {}
2087 #[stable(feature = "drain", since = "1.6.0")]
2088 unsafe impl<'a> Send for Drain<'a> {}
2089
2090 #[stable(feature = "drain", since = "1.6.0")]
2091 impl<'a> Drop for Drain<'a> {
2092     fn drop(&mut self) {
2093         unsafe {
2094             // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2095             // panic code being inserted again.
2096             let self_vec = (*self.string).as_mut_vec();
2097             if self.start <= self.end && self.end <= self_vec.len() {
2098                 self_vec.drain(self.start..self.end);
2099             }
2100         }
2101     }
2102 }
2103
2104 #[stable(feature = "drain", since = "1.6.0")]
2105 impl<'a> Iterator for Drain<'a> {
2106     type Item = char;
2107
2108     #[inline]
2109     fn next(&mut self) -> Option<char> {
2110         self.iter.next()
2111     }
2112
2113     fn size_hint(&self) -> (usize, Option<usize>) {
2114         self.iter.size_hint()
2115     }
2116 }
2117
2118 #[stable(feature = "drain", since = "1.6.0")]
2119 impl<'a> DoubleEndedIterator for Drain<'a> {
2120     #[inline]
2121     fn next_back(&mut self) -> Option<char> {
2122         self.iter.next_back()
2123     }
2124 }
2125
2126 #[unstable(feature = "fused", issue = "35602")]
2127 impl<'a> FusedIterator for Drain<'a> {}