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