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