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