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