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