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