]> git.lizzy.rs Git - rust.git/blob - src/libcollections/string.rs
fix: add feature to doc tests
[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 a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1407     ///
1408     /// # Examples
1409     ///
1410     /// Basic usage:
1411     ///
1412     /// ```
1413     /// #![feature(from_utf8_error_as_bytes)]
1414     /// // some invalid bytes, in a vector
1415     /// let bytes = vec![0, 159];
1416     ///
1417     /// let value = String::from_utf8(bytes);
1418     ///
1419     /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1420     /// ```
1421     #[unstable(feature = "from_utf8_error_as_bytes", issue = "40895")]
1422     pub fn as_bytes(&self) -> &[u8] {
1423         &self.bytes[..]
1424     }
1425
1426     /// Returns the bytes that were attempted to convert to a `String`.
1427     ///
1428     /// This method is carefully constructed to avoid allocation. It will
1429     /// consume the error, moving out the bytes, so that a copy of the bytes
1430     /// does not need to be made.
1431     ///
1432     /// # Examples
1433     ///
1434     /// Basic usage:
1435     ///
1436     /// ```
1437     /// // some invalid bytes, in a vector
1438     /// let bytes = vec![0, 159];
1439     ///
1440     /// let value = String::from_utf8(bytes);
1441     ///
1442     /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1443     /// ```
1444     #[stable(feature = "rust1", since = "1.0.0")]
1445     pub fn into_bytes(self) -> Vec<u8> {
1446         self.bytes
1447     }
1448
1449     /// Fetch a `Utf8Error` to get more details about the conversion failure.
1450     ///
1451     /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1452     /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1453     /// an analogue to `FromUtf8Error`. See its documentation for more details
1454     /// on using it.
1455     ///
1456     /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1457     /// [`std::str`]: ../../std/str/index.html
1458     /// [`u8`]: ../../std/primitive.u8.html
1459     /// [`&str`]: ../../std/primitive.str.html
1460     ///
1461     /// # Examples
1462     ///
1463     /// Basic usage:
1464     ///
1465     /// ```
1466     /// // some invalid bytes, in a vector
1467     /// let bytes = vec![0, 159];
1468     ///
1469     /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1470     ///
1471     /// // the first byte is invalid here
1472     /// assert_eq!(1, error.valid_up_to());
1473     /// ```
1474     #[stable(feature = "rust1", since = "1.0.0")]
1475     pub fn utf8_error(&self) -> Utf8Error {
1476         self.error
1477     }
1478 }
1479
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 impl fmt::Display for FromUtf8Error {
1482     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1483         fmt::Display::fmt(&self.error, f)
1484     }
1485 }
1486
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 impl fmt::Display for FromUtf16Error {
1489     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1490         fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1491     }
1492 }
1493
1494 #[stable(feature = "rust1", since = "1.0.0")]
1495 impl Clone for String {
1496     fn clone(&self) -> Self {
1497         String { vec: self.vec.clone() }
1498     }
1499
1500     fn clone_from(&mut self, source: &Self) {
1501         self.vec.clone_from(&source.vec);
1502     }
1503 }
1504
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl FromIterator<char> for String {
1507     fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1508         let mut buf = String::new();
1509         buf.extend(iter);
1510         buf
1511     }
1512 }
1513
1514 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1515 impl<'a> FromIterator<&'a char> for String {
1516     fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1517         let mut buf = String::new();
1518         buf.extend(iter);
1519         buf
1520     }
1521 }
1522
1523 #[stable(feature = "rust1", since = "1.0.0")]
1524 impl<'a> FromIterator<&'a str> for String {
1525     fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1526         let mut buf = String::new();
1527         buf.extend(iter);
1528         buf
1529     }
1530 }
1531
1532 #[stable(feature = "extend_string", since = "1.4.0")]
1533 impl FromIterator<String> for String {
1534     fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1535         let mut buf = String::new();
1536         buf.extend(iter);
1537         buf
1538     }
1539 }
1540
1541 #[stable(feature = "rust1", since = "1.0.0")]
1542 impl Extend<char> for String {
1543     fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1544         let iterator = iter.into_iter();
1545         let (lower_bound, _) = iterator.size_hint();
1546         self.reserve(lower_bound);
1547         for ch in iterator {
1548             self.push(ch)
1549         }
1550     }
1551 }
1552
1553 #[stable(feature = "extend_ref", since = "1.2.0")]
1554 impl<'a> Extend<&'a char> for String {
1555     fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1556         self.extend(iter.into_iter().cloned());
1557     }
1558 }
1559
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl<'a> Extend<&'a str> for String {
1562     fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1563         for s in iter {
1564             self.push_str(s)
1565         }
1566     }
1567 }
1568
1569 #[stable(feature = "extend_string", since = "1.4.0")]
1570 impl Extend<String> for String {
1571     fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1572         for s in iter {
1573             self.push_str(&s)
1574         }
1575     }
1576 }
1577
1578 /// A convenience impl that delegates to the impl for `&str`
1579 #[unstable(feature = "pattern",
1580            reason = "API not fully fleshed out and ready to be stabilized",
1581            issue = "27721")]
1582 impl<'a, 'b> Pattern<'a> for &'b String {
1583     type Searcher = <&'b str as Pattern<'a>>::Searcher;
1584
1585     fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1586         self[..].into_searcher(haystack)
1587     }
1588
1589     #[inline]
1590     fn is_contained_in(self, haystack: &'a str) -> bool {
1591         self[..].is_contained_in(haystack)
1592     }
1593
1594     #[inline]
1595     fn is_prefix_of(self, haystack: &'a str) -> bool {
1596         self[..].is_prefix_of(haystack)
1597     }
1598 }
1599
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 impl PartialEq for String {
1602     #[inline]
1603     fn eq(&self, other: &String) -> bool {
1604         PartialEq::eq(&self[..], &other[..])
1605     }
1606     #[inline]
1607     fn ne(&self, other: &String) -> bool {
1608         PartialEq::ne(&self[..], &other[..])
1609     }
1610 }
1611
1612 macro_rules! impl_eq {
1613     ($lhs:ty, $rhs: ty) => {
1614         #[stable(feature = "rust1", since = "1.0.0")]
1615         impl<'a, 'b> PartialEq<$rhs> for $lhs {
1616             #[inline]
1617             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1618             #[inline]
1619             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1620         }
1621
1622         #[stable(feature = "rust1", since = "1.0.0")]
1623         impl<'a, 'b> PartialEq<$lhs> for $rhs {
1624             #[inline]
1625             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1626             #[inline]
1627             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1628         }
1629
1630     }
1631 }
1632
1633 impl_eq! { String, str }
1634 impl_eq! { String, &'a str }
1635 impl_eq! { Cow<'a, str>, str }
1636 impl_eq! { Cow<'a, str>, &'b str }
1637 impl_eq! { Cow<'a, str>, String }
1638
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 impl Default for String {
1641     /// Creates an empty `String`.
1642     #[inline]
1643     fn default() -> String {
1644         String::new()
1645     }
1646 }
1647
1648 #[stable(feature = "rust1", since = "1.0.0")]
1649 impl fmt::Display for String {
1650     #[inline]
1651     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1652         fmt::Display::fmt(&**self, f)
1653     }
1654 }
1655
1656 #[stable(feature = "rust1", since = "1.0.0")]
1657 impl fmt::Debug for String {
1658     #[inline]
1659     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1660         fmt::Debug::fmt(&**self, f)
1661     }
1662 }
1663
1664 #[stable(feature = "rust1", since = "1.0.0")]
1665 impl hash::Hash for String {
1666     #[inline]
1667     fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1668         (**self).hash(hasher)
1669     }
1670 }
1671
1672 /// Implements the `+` operator for concatenating two strings.
1673 ///
1674 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1675 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1676 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1677 /// repeated concatenation.
1678 ///
1679 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1680 /// `String`.
1681 ///
1682 /// # Examples
1683 ///
1684 /// Concatenating two `String`s takes the first by value and borrows the second:
1685 ///
1686 /// ```
1687 /// let a = String::from("hello");
1688 /// let b = String::from(" world");
1689 /// let c = a + &b;
1690 /// // `a` is moved and can no longer be used here.
1691 /// ```
1692 ///
1693 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1694 ///
1695 /// ```
1696 /// let a = String::from("hello");
1697 /// let b = String::from(" world");
1698 /// let c = a.clone() + &b;
1699 /// // `a` is still valid here.
1700 /// ```
1701 ///
1702 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1703 ///
1704 /// ```
1705 /// let a = "hello";
1706 /// let b = " world";
1707 /// let c = a.to_string() + b;
1708 /// ```
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 impl<'a> Add<&'a str> for String {
1711     type Output = String;
1712
1713     #[inline]
1714     fn add(mut self, other: &str) -> String {
1715         self.push_str(other);
1716         self
1717     }
1718 }
1719
1720 /// Implements the `+=` operator for appending to a `String`.
1721 ///
1722 /// This has the same behavior as the [`push_str`] method.
1723 ///
1724 /// [`push_str`]: struct.String.html#method.push_str
1725 #[stable(feature = "stringaddassign", since = "1.12.0")]
1726 impl<'a> AddAssign<&'a str> for String {
1727     #[inline]
1728     fn add_assign(&mut self, other: &str) {
1729         self.push_str(other);
1730     }
1731 }
1732
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 impl ops::Index<ops::Range<usize>> for String {
1735     type Output = str;
1736
1737     #[inline]
1738     fn index(&self, index: ops::Range<usize>) -> &str {
1739         &self[..][index]
1740     }
1741 }
1742 #[stable(feature = "rust1", since = "1.0.0")]
1743 impl ops::Index<ops::RangeTo<usize>> for String {
1744     type Output = str;
1745
1746     #[inline]
1747     fn index(&self, index: ops::RangeTo<usize>) -> &str {
1748         &self[..][index]
1749     }
1750 }
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 impl ops::Index<ops::RangeFrom<usize>> for String {
1753     type Output = str;
1754
1755     #[inline]
1756     fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1757         &self[..][index]
1758     }
1759 }
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 impl ops::Index<ops::RangeFull> for String {
1762     type Output = str;
1763
1764     #[inline]
1765     fn index(&self, _index: ops::RangeFull) -> &str {
1766         unsafe { str::from_utf8_unchecked(&self.vec) }
1767     }
1768 }
1769 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1770 impl ops::Index<ops::RangeInclusive<usize>> for String {
1771     type Output = str;
1772
1773     #[inline]
1774     fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1775         Index::index(&**self, index)
1776     }
1777 }
1778 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1779 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1780     type Output = str;
1781
1782     #[inline]
1783     fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1784         Index::index(&**self, index)
1785     }
1786 }
1787
1788 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1789 impl ops::IndexMut<ops::Range<usize>> for String {
1790     #[inline]
1791     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1792         &mut self[..][index]
1793     }
1794 }
1795 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1796 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1797     #[inline]
1798     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1799         &mut self[..][index]
1800     }
1801 }
1802 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1803 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1804     #[inline]
1805     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1806         &mut self[..][index]
1807     }
1808 }
1809 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1810 impl ops::IndexMut<ops::RangeFull> for String {
1811     #[inline]
1812     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1813         unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
1814     }
1815 }
1816 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1817 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
1818     #[inline]
1819     fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1820         IndexMut::index_mut(&mut **self, index)
1821     }
1822 }
1823 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1824 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
1825     #[inline]
1826     fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1827         IndexMut::index_mut(&mut **self, index)
1828     }
1829 }
1830
1831 #[stable(feature = "rust1", since = "1.0.0")]
1832 impl ops::Deref for String {
1833     type Target = str;
1834
1835     #[inline]
1836     fn deref(&self) -> &str {
1837         unsafe { str::from_utf8_unchecked(&self.vec) }
1838     }
1839 }
1840
1841 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1842 impl ops::DerefMut for String {
1843     #[inline]
1844     fn deref_mut(&mut self) -> &mut str {
1845         unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
1846     }
1847 }
1848
1849 /// An error when parsing a `String`.
1850 ///
1851 /// This `enum` is slightly awkward: it will never actually exist. This error is
1852 /// part of the type signature of the implementation of [`FromStr`] on
1853 /// [`String`]. The return type of [`from_str`], requires that an error be
1854 /// defined, but, given that a [`String`] can always be made into a new
1855 /// [`String`] without error, this type will never actually be returned. As
1856 /// such, it is only here to satisfy said signature, and is useless otherwise.
1857 ///
1858 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1859 /// [`String`]: struct.String.html
1860 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
1861 #[stable(feature = "str_parse_error", since = "1.5.0")]
1862 #[derive(Copy)]
1863 pub enum ParseError {}
1864
1865 #[stable(feature = "rust1", since = "1.0.0")]
1866 impl FromStr for String {
1867     type Err = ParseError;
1868     #[inline]
1869     fn from_str(s: &str) -> Result<String, ParseError> {
1870         Ok(String::from(s))
1871     }
1872 }
1873
1874 #[stable(feature = "str_parse_error", since = "1.5.0")]
1875 impl Clone for ParseError {
1876     fn clone(&self) -> ParseError {
1877         match *self {}
1878     }
1879 }
1880
1881 #[stable(feature = "str_parse_error", since = "1.5.0")]
1882 impl fmt::Debug for ParseError {
1883     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1884         match *self {}
1885     }
1886 }
1887
1888 #[stable(feature = "str_parse_error2", since = "1.8.0")]
1889 impl fmt::Display for ParseError {
1890     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1891         match *self {}
1892     }
1893 }
1894
1895 #[stable(feature = "str_parse_error", since = "1.5.0")]
1896 impl PartialEq for ParseError {
1897     fn eq(&self, _: &ParseError) -> bool {
1898         match *self {}
1899     }
1900 }
1901
1902 #[stable(feature = "str_parse_error", since = "1.5.0")]
1903 impl Eq for ParseError {}
1904
1905 /// A trait for converting a value to a `String`.
1906 ///
1907 /// This trait is automatically implemented for any type which implements the
1908 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1909 /// [`Display`] should be implemented instead, and you get the `ToString`
1910 /// implementation for free.
1911 ///
1912 /// [`Display`]: ../../std/fmt/trait.Display.html
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 pub trait ToString {
1915     /// Converts the given value to a `String`.
1916     ///
1917     /// # Examples
1918     ///
1919     /// Basic usage:
1920     ///
1921     /// ```
1922     /// let i = 5;
1923     /// let five = String::from("5");
1924     ///
1925     /// assert_eq!(five, i.to_string());
1926     /// ```
1927     #[stable(feature = "rust1", since = "1.0.0")]
1928     fn to_string(&self) -> String;
1929 }
1930
1931 /// # Panics
1932 ///
1933 /// In this implementation, the `to_string` method panics
1934 /// if the `Display` implementation returns an error.
1935 /// This indicates an incorrect `Display` implementation
1936 /// since `fmt::Write for String` never returns an error itself.
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 impl<T: fmt::Display + ?Sized> ToString for T {
1939     #[inline]
1940     default fn to_string(&self) -> String {
1941         use core::fmt::Write;
1942         let mut buf = String::new();
1943         buf.write_fmt(format_args!("{}", self))
1944            .expect("a Display implementation return an error unexpectedly");
1945         buf.shrink_to_fit();
1946         buf
1947     }
1948 }
1949
1950 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
1951 impl ToString for str {
1952     #[inline]
1953     fn to_string(&self) -> String {
1954         String::from(self)
1955     }
1956 }
1957
1958 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
1959 impl<'a> ToString for Cow<'a, str> {
1960     #[inline]
1961     fn to_string(&self) -> String {
1962         self[..].to_owned()
1963     }
1964 }
1965
1966 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
1967 impl ToString for String {
1968     #[inline]
1969     fn to_string(&self) -> String {
1970         self.to_owned()
1971     }
1972 }
1973
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 impl AsRef<str> for String {
1976     #[inline]
1977     fn as_ref(&self) -> &str {
1978         self
1979     }
1980 }
1981
1982 #[stable(feature = "rust1", since = "1.0.0")]
1983 impl AsRef<[u8]> for String {
1984     #[inline]
1985     fn as_ref(&self) -> &[u8] {
1986         self.as_bytes()
1987     }
1988 }
1989
1990 #[stable(feature = "rust1", since = "1.0.0")]
1991 impl<'a> From<&'a str> for String {
1992     fn from(s: &'a str) -> String {
1993         s.to_owned()
1994     }
1995 }
1996
1997 // note: test pulls in libstd, which causes errors here
1998 #[cfg(not(test))]
1999 #[stable(feature = "string_from_box", since = "1.17.0")]
2000 impl From<Box<str>> for String {
2001     fn from(s: Box<str>) -> String {
2002         s.into_string()
2003     }
2004 }
2005
2006 #[stable(feature = "box_from_str", since = "1.17.0")]
2007 impl Into<Box<str>> for String {
2008     fn into(self) -> Box<str> {
2009         self.into_boxed_str()
2010     }
2011 }
2012
2013 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2014 impl<'a> From<Cow<'a, str>> for String {
2015     fn from(s: Cow<'a, str>) -> String {
2016         s.into_owned()
2017     }
2018 }
2019
2020 #[stable(feature = "rust1", since = "1.0.0")]
2021 impl<'a> From<&'a str> for Cow<'a, str> {
2022     #[inline]
2023     fn from(s: &'a str) -> Cow<'a, str> {
2024         Cow::Borrowed(s)
2025     }
2026 }
2027
2028 #[stable(feature = "rust1", since = "1.0.0")]
2029 impl<'a> From<String> for Cow<'a, str> {
2030     #[inline]
2031     fn from(s: String) -> Cow<'a, str> {
2032         Cow::Owned(s)
2033     }
2034 }
2035
2036 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2037 impl<'a> FromIterator<char> for Cow<'a, str> {
2038     fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2039         Cow::Owned(FromIterator::from_iter(it))
2040     }
2041 }
2042
2043 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2044 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2045     fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2046         Cow::Owned(FromIterator::from_iter(it))
2047     }
2048 }
2049
2050 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2051 impl<'a> FromIterator<String> for Cow<'a, str> {
2052     fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2053         Cow::Owned(FromIterator::from_iter(it))
2054     }
2055 }
2056
2057 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2058 impl From<String> for Vec<u8> {
2059     fn from(string: String) -> Vec<u8> {
2060         string.into_bytes()
2061     }
2062 }
2063
2064 #[stable(feature = "rust1", since = "1.0.0")]
2065 impl fmt::Write for String {
2066     #[inline]
2067     fn write_str(&mut self, s: &str) -> fmt::Result {
2068         self.push_str(s);
2069         Ok(())
2070     }
2071
2072     #[inline]
2073     fn write_char(&mut self, c: char) -> fmt::Result {
2074         self.push(c);
2075         Ok(())
2076     }
2077 }
2078
2079 /// A draining iterator for `String`.
2080 ///
2081 /// This struct is created by the [`drain`] method on [`String`]. See its
2082 /// documentation for more.
2083 ///
2084 /// [`drain`]: struct.String.html#method.drain
2085 /// [`String`]: struct.String.html
2086 #[stable(feature = "drain", since = "1.6.0")]
2087 pub struct Drain<'a> {
2088     /// Will be used as &'a mut String in the destructor
2089     string: *mut String,
2090     /// Start of part to remove
2091     start: usize,
2092     /// End of part to remove
2093     end: usize,
2094     /// Current remaining range to remove
2095     iter: Chars<'a>,
2096 }
2097
2098 #[stable(feature = "collection_debug", since = "1.17.0")]
2099 impl<'a> fmt::Debug for Drain<'a> {
2100     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2101         f.pad("Drain { .. }")
2102     }
2103 }
2104
2105 #[stable(feature = "drain", since = "1.6.0")]
2106 unsafe impl<'a> Sync for Drain<'a> {}
2107 #[stable(feature = "drain", since = "1.6.0")]
2108 unsafe impl<'a> Send for Drain<'a> {}
2109
2110 #[stable(feature = "drain", since = "1.6.0")]
2111 impl<'a> Drop for Drain<'a> {
2112     fn drop(&mut self) {
2113         unsafe {
2114             // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2115             // panic code being inserted again.
2116             let self_vec = (*self.string).as_mut_vec();
2117             if self.start <= self.end && self.end <= self_vec.len() {
2118                 self_vec.drain(self.start..self.end);
2119             }
2120         }
2121     }
2122 }
2123
2124 #[stable(feature = "drain", since = "1.6.0")]
2125 impl<'a> Iterator for Drain<'a> {
2126     type Item = char;
2127
2128     #[inline]
2129     fn next(&mut self) -> Option<char> {
2130         self.iter.next()
2131     }
2132
2133     fn size_hint(&self) -> (usize, Option<usize>) {
2134         self.iter.size_hint()
2135     }
2136 }
2137
2138 #[stable(feature = "drain", since = "1.6.0")]
2139 impl<'a> DoubleEndedIterator for Drain<'a> {
2140     #[inline]
2141     fn next_back(&mut self) -> Option<char> {
2142         self.iter.next_back()
2143     }
2144 }
2145
2146 #[unstable(feature = "fused", issue = "35602")]
2147 impl<'a> FusedIterator for Drain<'a> {}