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