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