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